Spaces:
Runtime error
Runtime error
Download hf_app.py from Adarsh-Saurabh/MetaVision: direct link, hf CLI and curl.
- Browser
- Download file 15.6 kB
-
https://huggingface.co/spaces/Adarsh-Saurabh/MetaVision/resolve/main/hf_app.py
- Command line
-
hf download hf://spaces/Adarsh-Saurabh/MetaVision/hf_app.py
-
curl -L -o hf_app.py https://huggingface.co/spaces/Adarsh-Saurabh/MetaVision/resolve/main/hf_app.py
15.6 kB
| """Hugging Face Gradio entry point: public workspace and authenticated /admin.""" | |
| import hmac | |
| import html | |
| import json | |
| import os | |
| from functools import partial | |
| import gradio as gr | |
| import uvicorn | |
| from dotenv import load_dotenv | |
| from fastapi import FastAPI | |
| from fastapi.responses import HTMLResponse | |
| from second_brain.agents import compute_financials, inr | |
| from second_brain.tools import APP_NAMES | |
| from second_brain.workflow import Workflow | |
| load_dotenv(override=False) | |
| SCENARIOS = { | |
| "Normal approval": "S1-approved", | |
| "Full demo · retry and concurrent edit": "S1-main-demo", | |
| "Two authorised contacts disagree": "S1-authorized-conflict", | |
| "Conflict followed by sponsor confirmation": "S1-conflict-clarified", | |
| "Unverified competing message": "S1-unauthorized-whatsapp", | |
| "Tracker failure and retry": "S1-tracker-failure", | |
| "Timeout after a write": "S1-timeout-after-write", | |
| "Email unavailable": "S1-gmail-unavailable", | |
| "Privacy check unavailable": "S1-privacy-agent-failure", | |
| } | |
| SCOPES = {"Business records": "business_records", "Team notifications": "internal_notifications", | |
| "Send sponsor reply": "sponsor_send"} | |
| STATUS = {"ready": "Ready for a sponsor update", "ingested": "Update received · ready to analyse", | |
| "awaiting_approval": "Your approval is needed", "approved": "Approved · ready to apply", | |
| "awaiting_delta_approval": "A record changed · review the updated plan", | |
| "executed": "Changes applied · ready to check", "verified": "Results verified", | |
| "rejected": "Plan rejected", "needs_clarification": "Sponsor clarification needed", | |
| "blocked": "Stopped safely", "failed": "Execution stopped", "verification_failed": "Checks failed"} | |
| CSS = """ | |
| .gradio-container {max-width: 1240px !important; margin: auto;} | |
| .hero {padding: 28px; border: 1px solid #dfe6f0; border-radius: 18px; | |
| background: linear-gradient(120deg,#eef2ff,#f0fdfa); color:#172b4d; margin-bottom:18px;} | |
| .hero p {color:#52627a; max-width:720px; line-height:1.6;} | |
| .hero h1 {font-size:34px; letter-spacing:-1px; margin:8px 0;} | |
| .eyebrow {font-size:12px; letter-spacing:2px; color:#4f46e5; font-weight:700;} | |
| .metrics {display:grid; grid-template-columns:repeat(3,1fr); gap:14px; margin:18px 0;} | |
| .metric {border:1px solid #dfe6f0; border-radius:12px; padding:18px;} | |
| .metric span {display:block; font-size:13px; opacity:.75; margin-bottom:8px;} | |
| .metric strong {font-size:24px;} | |
| @media(max-width:600px){.metrics{grid-template-columns:1fr}.hero h1{font-size:27px}} | |
| """ | |
| def check_host_gpu(): | |
| if not os.environ.get("SPACE_ID"): | |
| return "Local preview · no ZeroGPU allocation requested." | |
| import torch | |
| return "ZeroGPU available: " + torch.cuda.get_device_name(0) | |
| # ZeroGPU requires a registered GPU function even when the main workflow uses the CPU. | |
| if os.environ.get("SPACE_ID"): | |
| import spaces | |
| check_host_gpu = spaces.GPU(duration=10)(check_host_gpu) | |
| def close_workflow(wf): | |
| if wf is not None: | |
| wf.close() | |
| def new_workflow(scenario="S1-approved", use_llm=False): | |
| if scenario not in SCENARIOS.values(): | |
| raise ValueError("Unknown demo scenario") | |
| return Workflow(scenario, use_llm=use_llm) | |
| def advance(wf, command, scopes, *, admin=False): | |
| """All mutations go through the engine's existing stage and approval checks.""" | |
| if wf is None: | |
| wf = new_workflow() | |
| if not isinstance(scopes, list) or any(scope not in SCOPES for scope in scopes): | |
| raise ValueError("Unknown approval scope") | |
| selected = [SCOPES[scope] for scope in scopes] | |
| if command == "review": | |
| if wf.stage == "ready": | |
| wf.ingest() | |
| for activation in sorted(wf.store.scenario["activation"], key=lambda item: item["order"]): | |
| if activation["phase"] == "trigger" and activation["source_id"] != wf.trigger_id: | |
| wf.store.deliver(activation["source_id"]) | |
| wf.analyze() | |
| elif command == "approve": | |
| if not selected: | |
| raise ValueError("Select at least one approval scope") | |
| if wf.stage == "awaiting_delta_approval": | |
| wf.approve_delta([scope for scope in selected if scope in wf.approvals[0]["scopes"]]) | |
| else: | |
| wf.approve(selected) | |
| elif command == "reject": | |
| wf.reject() | |
| elif command == "execute": | |
| wf.execute() | |
| elif command == "verify": | |
| wf.verify() | |
| elif command == "clarify" and admin: | |
| confirmations = [a["source_id"] for a in wf.store.scenario["activation"] if a["phase"] == "clarification"] | |
| if not confirmations: | |
| raise ValueError("No sponsor confirmation is available in this scenario") | |
| wf.clarify(confirmations[0]) | |
| elif command == "replay" and admin: | |
| wf.replay(10) | |
| else: | |
| raise ValueError("Action is not available") | |
| return wf | |
| def format_value(field, value): | |
| if field.endswith("_paise") and isinstance(value, int): | |
| return inr(value) | |
| if field == "entries" and isinstance(value, list): | |
| return "\n".join(entry["text"] for entry in value) | |
| if field == "condition_evaluation" and isinstance(value, dict): | |
| return ("met" if value.get("satisfied") else "not met") + " · balance " + inr(value.get("observed_paise", 0)) | |
| if isinstance(value, (dict, list)): | |
| return json.dumps(value, ensure_ascii=False) | |
| return "—" if value is None else str(value) | |
| def snapshot(wf): | |
| store = wf.store | |
| sponsor = store.get("sponsor", "sponsor-aster") | |
| balance = compute_financials(store)["forecast_balance_paise"] | |
| metrics = '<div class="metrics">' + "".join( | |
| f'<div class="metric"><span>{label}</span><strong>{html.escape(value)}</strong></div>' | |
| for label, value in (("Sponsor commitment", inr(sponsor["commitment_paise"])), | |
| ("Sponsor level", sponsor["tier"]), ("Budget after costs", inr(balance)))) + '</div>' | |
| source = store.source(wf.trigger_id) | |
| message = source["body"] if source else "Aster Labs has sent a sponsorship update. Select Review sponsor update to receive and analyse it." | |
| status = f"### {STATUS.get(wf.stage, wf.stage)}\n\n" | |
| rows = [] | |
| if wf.plan: | |
| status += wf.proposal["summary"] + "\n\n" | |
| status += f"**Proposed budget after costs:** {inr(wf.plan['financials']['forecast_balance_paise'])}\n\n" | |
| if wf.plan["flags"]: | |
| status += "**Your team still needs to decide:**\n" + "\n".join(f"- {flag}" for flag in wf.plan["flags"]) | |
| for action in wf.plan["actions"]: | |
| changes = "; ".join( | |
| f"{field.replace('_paise', '').replace('_', ' ')}: " | |
| f"{format_value(field, action['before'].get(field))} → {format_value(field, value)}" | |
| for field, value in action["changes"].items()) | |
| rows.append([APP_NAMES.get(action["kind"], action["kind"]), action["target_id"], changes, | |
| next(label for label, scope in SCOPES.items() if scope == action["scope"]), | |
| wf.action_status.get(action["op_key"], "pending")]) | |
| if wf.clarification_questions: | |
| status += "\n\n" + "\n".join(f"- {q}" for q in wf.clarification_questions) | |
| if wf.stage in ("blocked", "failed", "verification_failed"): | |
| status += "\n\nPending changes have stopped. Review the evidence with the organiser." | |
| checks = "Results have not been checked yet." | |
| if wf.verification: | |
| checks = f"**{wf.verification['passed']} passed · {wf.verification['failed']} failed**\n\n" | |
| checks += "\n".join(f"- {'PASS' if c['ok'] else 'FAIL'} · {c['name']}: {c['detail']}" for c in wf.verification["checks"]) | |
| drafts = "\n\n".join(f"{d['subject']} · {'sent in demo' if d.get('sent') else 'draft, not sent'}\n{d['body']}" | |
| for d in store.list("draft")) or "No sponsor reply yet." | |
| stage = wf.stage | |
| buttons = [gr.update(interactive=stage in stages) for stages in ( | |
| {"ready", "ingested"}, {"awaiting_approval", "awaiting_delta_approval"}, | |
| {"awaiting_approval", "awaiting_delta_approval"}, {"approved"}, {"executed"}, | |
| {"needs_clarification", "blocked"}, {"verified"})] | |
| diagnostics = {"scenario": store.scenario["scenario_id"], "stage": stage, "effects": store.effect_count(), | |
| "approvals": wf.approvals, "ledger": store.ops(), "replay": wf.replay_result, | |
| "timeline": store.logs()} | |
| return [wf, metrics, message, status, rows, checks, drafts, *buttons, diagnostics] | |
| def build_page(*, admin=False): | |
| with gr.Blocks(title="MetaVision · " + ("Admin" if admin else "My workspace")) as page: | |
| # shortcut: demo sessions live in memory; add durable user storage before using real team data. | |
| state = gr.State(None, time_to_live=3600, delete_callback=close_workflow) | |
| gr.HTML('<div class="hero"><div class="eyebrow">METAVISION / ' | |
| + ('ADMIN CONSOLE' if admin else 'MY WORKSPACE') + '</div><h1>' | |
| + ('See every step. Stay in control.' if admin else 'Less catching up. More moving forward.') | |
| + '</h1><p>Turn a sponsor update into a clear plan across your team’s apps. ' | |
| 'Review the evidence, approve the changes, and check the results.</p></div>') | |
| gr.Markdown("[My workspace](/) · [Admin console](/admin/)" + (" · [Sign out](/admin/logout)" if admin else "")) | |
| gr.Markdown("**Interactive demo · synthetic data.** Each visitor has a separate workspace. No real email or connected account is used.") | |
| if admin: | |
| with gr.Row(): | |
| scenario = gr.Dropdown(list(SCENARIOS), value="Full demo · retry and concurrent edit", label="Demo scenario") | |
| live = gr.Checkbox(False, label="Use live Gemini for extraction", interactive=bool(os.environ.get("GEMINI_API_KEY"))) | |
| metrics = gr.HTML() | |
| with gr.Row(): | |
| with gr.Column(scale=2): | |
| status = gr.Markdown() | |
| review = gr.Button("1. Review sponsor update", variant="primary") | |
| with gr.Accordion("Source message", open=True): | |
| message = gr.Textbox(label="Sponsor message", lines=6, interactive=False) | |
| with gr.Column(scale=1): | |
| gr.Markdown("### You decide what happens\nChoose permissions, then approve. The sponsor reply stays a draft unless you allow sending.") | |
| scopes = gr.CheckboxGroup(list(SCOPES), value=["Business records", "Team notifications"], label="Approval permissions") | |
| approve = gr.Button("2. Approve selected changes") | |
| reject = gr.Button("Reject plan", variant="stop") | |
| execute = gr.Button("3. Apply approved changes") | |
| verify = gr.Button("4. Check the results") | |
| reset = gr.Button("Start a fresh demo") | |
| clarify = gr.Button("Deliver sponsor confirmation", visible=admin) | |
| replay = gr.Button("Replay email ×10", visible=admin) | |
| gr.Markdown("### Your change plan\nReview the exact changes before approving. Current totals above update after execution.") | |
| plan = gr.Dataframe(headers=["App", "Record", "Proposed change", "Permission", "Status"], | |
| datatype=["str"] * 5, interactive=False, wrap=True) | |
| with gr.Accordion("Sponsor reply", open=False): | |
| drafts = gr.Textbox(label="Reply status and content", lines=7, interactive=False) | |
| with gr.Accordion("Result details", open=False): | |
| checks = gr.Markdown() | |
| if admin: | |
| with gr.Accordion("Operator diagnostics", open=False): | |
| diagnostics = gr.JSON(label="Timeline, approvals and operation ledger") | |
| outputs = [state, metrics, message, status, plan, checks, drafts, | |
| review, approve, reject, execute, verify, clarify, replay] | |
| if admin: | |
| outputs.append(diagnostics) | |
| def view(wf): | |
| result = snapshot(wf) | |
| return result if admin else result[:-1] | |
| def initialise(wf, scenario_name=None, use_llm=False): | |
| if wf is not None: | |
| wf.close() | |
| return view(new_workflow(SCENARIOS[scenario_name] if admin else "S1-approved", use_llm if admin else False)) | |
| def act(wf, selected, command): | |
| try: | |
| wf = advance(wf, command, selected, admin=admin) | |
| except (ValueError, RuntimeError) as exc: | |
| gr.Warning(str(exc)) | |
| if wf is None: | |
| wf = new_workflow() | |
| return view(wf) | |
| initial_inputs = [state, scenario, live] if admin else [state] | |
| event_options = dict(outputs=outputs, concurrency_id="workspace", concurrency_limit=1, api_name=False) | |
| page.load(initialise, inputs=initial_inputs, **event_options) | |
| reset.click(initialise, inputs=initial_inputs, **event_options) | |
| for button, command in ((review, "review"), (approve, "approve"), (reject, "reject"), | |
| (execute, "execute"), (verify, "verify"), (clarify, "clarify"), (replay, "replay")): | |
| if admin or command not in ("clarify", "replay"): | |
| button.click(partial(act, command=command), inputs=[state, scopes], **event_options) | |
| if admin: | |
| gr.Markdown("Scenario and Gemini settings take effect when you select **Start a fresh demo**. This console has its own session; public visitors cannot access its diagnostics or settings.") | |
| with gr.Accordion("Hosting health check", open=False): | |
| gr.Markdown("Optional: allocates ZeroGPU briefly to verify the hosting hardware. This uses your GPU quota; the normal workflow does not.") | |
| host_check = gr.Button("Check ZeroGPU hardware") | |
| host_result = gr.Textbox(label="Hosting result", interactive=False) | |
| host_check.click(check_host_gpu, outputs=host_result, api_name=False) | |
| return page.queue(max_size=32) | |
| def admin_auth(username, password): | |
| expected = os.environ.get("ADMIN_PASSWORD", "") | |
| return bool(expected) and hmac.compare_digest(username.encode(), b"admin") and hmac.compare_digest(password.encode(), expected.encode()) | |
| def create_app(): | |
| app = FastAPI(docs_url=None, redoc_url=None) | |
| theme = gr.themes.Soft(primary_hue="indigo", secondary_hue="teal", font=["Inter", "sans-serif"]) | |
| options = dict(css=CSS, theme=theme, footer_links=[], show_error=False, | |
| blocked_paths=[os.path.abspath(".env"), os.path.abspath(".git"), os.path.abspath("runtime")]) | |
| if os.environ.get("ADMIN_PASSWORD"): | |
| app = gr.mount_gradio_app(app, build_page(admin=True), path="/admin", auth=admin_auth, | |
| auth_message="MetaVision admin · username: admin", **options) | |
| else: | |
| def admin_disabled(rest=""): | |
| return HTMLResponse("<h1>Admin access is disabled</h1><p>Set ADMIN_PASSWORD in your Space secrets.</p><a href='/'>My workspace</a>", status_code=503) | |
| return gr.mount_gradio_app(app, build_page(), path="/", **options) | |
| if __name__ == "__main__": | |
| app = create_app() | |
| if os.environ.get("SPACE_ID"): | |
| # FastAPI mounting bypasses the ZeroGPU startup hook normally called by Gradio.launch. | |
| from spaces.zero import startup | |
| startup() | |
| uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("APP_PORT", "7860"))) | |