import random
from collections import Counter, defaultdict
from datetime import date, timedelta
from prefab_ui.actions import AppendState, OpenLink, PopState, SetState, ShowToast, ToggleState
from prefab_ui.app import PrefabApp
from prefab_ui.parts import (
   Alert, AlertDescription, AlertTitle, Badge, Button, Card, CardContent,
   CardDescription, CardFooter, CardHeader, CardTitle, Code, Column,
   DataTable, DataTableColumn, Kind, Grid, H2, Enter, Markdown, Mermaid,
   Metric, Muted, Progress, Ring, Row, Slider, Small, Swap, Tab, Tabs,
   Textual content
)
from prefab_ui.parts.charts import (
   BarChart, ChartSeries, LineChart, PieChart, RadarChart, ScatterChart,
   Sparkline
)
from prefab_ui.parts.control_flow import Else, ForEach, If
from prefab_ui.rx import EVENT, STATE
random.seed(42)
TODAY = date.as we speak()
DATES = (TODAY - timedelta(days=29 - i) for i in vary(30))
REGIONS = ("All", "APAC", "EMEA", "NA", "LATAM")
PIPELINES = (
   "Buyer 360 ETL",
   "Bill OCR",
   "LLM Triage",
   "Danger Scoring",
   "Forecast Sync",
   "Warehouse Load",
)
OWNERS = ("Knowledge Platform", "AI Apps", "Income Ops", "Danger Engineering")
STATES = ("Accomplished", "Accomplished", "Accomplished", "Accomplished", "Late", "Failed")
PRIORITIES = ("P0", "P1", "P2", "P3")
runs = ()
daily_region_rows = ()
for d in DATES:
   for area in REGIONS(1:):
       region_bias = {
           "APAC": 0.96,
           "EMEA": 0.94,
           "NA": 0.97,
           "LATAM": 0.91,
       }(area)
       quantity = random.randint(32, 78)
       failures = 0
       late = 0
       total_cost = 0.0
       total_latency = 0.0
       total_revenue = 0.0
       for i in vary(quantity):
           pipeline = random.selection(PIPELINES)
           proprietor = random.selection(OWNERS)
           state = random.selections(
               STATES,
               weights=(
                   region_bias * 10,
                   6,
                   4,
                   3,
                   1.2,
                   max(0.2, (1 - region_bias) * 16),
               ),
               ok=1,
           )(0)
           period = max(
               12,
               int(
                   random.gauss(95, 35)
                   + (20 if state == "Late" else 0)
                   + (45 if state == "Failed" else 0)
               ),
           )
           price = spherical(max(0.09, random.lognormvariate(-1.15, 0.55) + period / 1800), 2)
           income = spherical(random.uniform(1.2, 8.5) * (1.3 if state == "Accomplished" else 0.6), 2)
           precedence = random.selections(PRIORITIES, weights=(1, 3, 7, 10), ok=1)(0)
           if state == "Failed":
               failures += 1
           if state == "Late":
               late += 1
           total_cost += price
           total_latency += period
           total_revenue += income
           if d >= TODAY - timedelta(days=10) and (state in {"Failed", "Late"} or random.random() < 0.05):
               runs.append({
                   "run_id": f"{d.strftime('%mpercentd')}-{area(:2)}-{len(runs)+1:04d}",
                   "date": d.strftime("%Y-%m-%d"),
                   "pipeline": pipeline,
                   "proprietor": proprietor,
                   "area": area,
                   "state": state,
                   "precedence": precedence,
                   "duration_s": period,
                   "cost_usd": price,
                   "revenue_k": income,
                   "sla_gap": spherical(max(0, period - 120) / 60, 1),
               })
       daily_region_rows.append({
           "date": d.strftime("%b %d"),
           "area": area,
           "runs": quantity,
           "failures": failures,
           "late": late,
           "success_rate": spherical(100 * (quantity - failures - late * 0.35) / quantity, 1),
           "avg_latency": spherical(total_latency / quantity, 1),
           "cost_usd": spherical(total_cost, 2),
           "revenue_k": spherical(total_revenue, 1),
       })
runs = sorted(
   runs,
   key=lambda r: (r("precedence"), r("state") != "Failed", -r("duration_s"))
)(:80)
def aggregate_daily(rows):
   by_date = defaultdict(lambda: {
       "date": "",
       "runs": 0,
       "failures": 0,
       "late": 0,
       "cost_usd": 0.0,
       "revenue_k": 0.0,
       "latency_weighted": 0.0,
   })
   for r in rows:
       bucket = by_date(r("date"))
       bucket("date") = r("date")
       bucket("runs") += r("runs")
       bucket("failures") += r("failures")
       bucket("late") += r("late")
       bucket("cost_usd") += r("cost_usd")
       bucket("revenue_k") += r("revenue_k")
       bucket("latency_weighted") += r("avg_latency") * r("runs")
   out = ()
   for d in (x.strftime("%b %d") for x in DATES):
       b = by_date(d)
       if b("runs"):
           b("success_rate") = spherical(100 * (b("runs") - b("failures") - b("late") * 0.35) / b("runs"), 1)
           b("avg_latency") = spherical(b("latency_weighted") / b("runs"), 1)
           b("cost_usd") = spherical(b("cost_usd"), 2)
           b("revenue_k") = spherical(b("revenue_k"), 1)
           del b("latency_weighted")
           out.append(dict(b))
   return out
def aggregate_regions(rows):
   by_region = defaultdict(lambda: {
       "area": "",
       "runs": 0,
       "failures": 0,
       "late": 0,
       "cost_usd": 0.0,
       "revenue_k": 0.0,
       "latency_weighted": 0.0,
   })
   for r in rows:
       b = by_region(r("area"))
       b("area") = r("area")
       b("runs") += r("runs")
       b("failures") += r("failures")
       b("late") += r("late")
       b("cost_usd") += r("cost_usd")
       b("revenue_k") += r("revenue_k")
       b("latency_weighted") += r("avg_latency") * r("runs")
   out = ()
   for area in REGIONS(1:):
       b = by_region(area)
       b("success_rate") = spherical(100 * (b("runs") - b("failures") - b("late") * 0.35) / b("runs"), 1)
       b("avg_latency") = spherical(b("latency_weighted") / b("runs"), 1)
       b("cost_usd") = spherical(b("cost_usd"), 2)
       b("revenue_k") = spherical(b("revenue_k"), 1)
       b("roi") = spherical(b("revenue_k") / max(1, b("cost_usd")), 1)
       del b("latency_weighted")
       out.append(dict(b))
   return out
def make_status_rows(table_rows):
   counts = Counter(r("state") for r in table_rows)
   return ({"state": ok, "rely": v} for ok, v in counts.gadgets())
def make_pipeline_rows(table_rows):
   counts = Counter(r("pipeline") for r in table_rows)
   return ({"pipeline": ok, "rely": v} for ok, v in counts.most_common())
def make_kpis(area, daily_rows, table_rows):
   runs_count = sum(r("runs") for r in daily_rows)
   failures = sum(r("failures") for r in daily_rows)
   late = sum(r("late") for r in daily_rows)
   price = sum(r("cost_usd") for r in daily_rows)
   income = sum(r("revenue_k") for r in daily_rows)
   return {
       "area": area,
       "runs": runs_count,
       "success_rate": spherical(100 * (runs_count - failures - late * 0.35) / max(1, runs_count), 1),
       "avg_latency": spherical(sum(r("avg_latency") * r("runs") for r in daily_rows) / max(1, runs_count), 1),
       "cost_usd": spherical(price, 2),
       "revenue_k": spherical(income, 1),
       "roi": spherical(income / max(1, price), 1),
       "open_issues": len(table_rows),
       "p0p1": sum(1 for r in table_rows if r("precedence") in {"P0", "P1"}),
       "failure_rate": spherical(100 * failures / max(1, runs_count), 2),
       "spark": (r("success_rate") for r in daily_rows(-14:)),
   }
DAILY_BY_REGION = {"All": aggregate_daily(daily_region_rows)}
REGION_ROWS = aggregate_regions(daily_region_rows)
for area in REGIONS(1:):
   DAILY_BY_REGION(area) = (r for r in daily_region_rows if r("area") == area)
RUNS_BY_REGION = {
   area: (r for r in runs if area == "All" or r("area") == area)
   for area in REGIONS
}
STATUS_BY_REGION = {
   area: make_status_rows(RUNS_BY_REGION(area))
   for area in REGIONS
}
PIPELINE_BY_REGION = {
   area: make_pipeline_rows(RUNS_BY_REGION(area))
   for area in REGIONS
}
KPI_BY_REGION = {
   area: make_kpis(area, DAILY_BY_REGION(area), RUNS_BY_REGION(area))
   for area in REGIONS
}
WATCHLIST = sorted(
   runs,
   key=lambda r: (r("precedence"), r("state") != "Failed", -r("sla_gap"))
)(:8)
SCATTER_ROWS = (
   {
       "area": r("area"),
       "success_rate": r("success_rate"),
       "cost_usd": r("cost_usd"),
       "avg_latency": r("avg_latency"),
   }
   for r in REGION_ROWS
)
RADAR_ROWS = (
   {"metric": "Success", **{r("area"): r("success_rate") for r in REGION_ROWS}},
   {"metric": "ROI", **{r("area"): min(100, r("roi") * 8) for r in REGION_ROWS}},
   {"metric": "Latency", **{r("area"): max(0, 100 - r("avg_latency") / 2) for r in REGION_ROWS}},
   {"metric": "Value", **{r("area"): max(0, 100 - r("cost_usd") / 20) for r in REGION_ROWS}},
)
REGION_ACTIONS = {
   area: (
       SetState("selected_region", area),
       SetState("line_rows", DAILY_BY_REGION(area)),
       SetState("table_rows", RUNS_BY_REGION(area)),
       SetState("status_rows", STATUS_BY_REGION(area)),
       SetState("pipeline_rows", PIPELINE_BY_REGION(area)),
       SetState("region_kpis", KPI_BY_REGION(area)),
       SetState("selected_run", None),
       ShowToast(f"Area set to {area}", variant="data", period=1800),
   )
   for area in REGIONS
}
'''

Von admin

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert