Spaces:
Sleeping
Sleeping
Commit History
-
Speed up chat + emit >=10 figures/tables per Phase-2 model run
Two user-visible fixes from the post-deployment feedback: 1. Chat felt slower than before the fallback chain landed. Root cause was not the chain itself (it exits on the first parseable response), but three pile-on effects that compound on a cold HF worker: a. max_tokens was 900 for a JSON output that is well under 200. The Gemini free tier generates up to the cap. Lowered to 400. b. Every chat call re-built the provider object, paying the GeminiProvider/_http setup cost on a cold worker. Now cached at module level (_provider_cache). c. LLMConfig.timeout_s was 30s, so a stalled provider cost the full 30 before the chain rolled over. Lowered to 12 with a CDPR_LLM_TIMEOUT_S env override for slow links. gradio_app.py also pre-warms the chain at module load time so the FIRST chat after a Space restart doesn't pay construction cost --- it pays it once, before the user even sees the page. simulation_builder gains…0c4152d
-
LLM fallback chain + Reset button + Accordion UI + per-run audit
Three independent fixes, all driven by the user's report after the last deployment: 1. LLM fallback chain (Gemini 429 -> OpenRouter -> echo). Gemini's free tier rate-limits aggressively (HTTP 429). When the 429 fires the chat used to die with a 'low confidence' note and the user had no fallback. cdpr.llm.config.resolve_fallback_chain now returns an ordered provider list driven by CDPR_LLM_FALLBACK_ CHAIN or, when unset, by which keys are configured. simulation_ builder.describe_to_request walks the chain and uses whichever provider returns parseable JSON first; the echo stub is appended unconditionally so the call never raises. BuilderResult.notes reports which providers were tried and which won. docs/llm- providers.md gains a 'Automatic fallback chain' section. 2. Reset button + collapsible accordion sections. Robot & dynamics / Trajectory / Time / Controller are now wrapped in gr.Accordion (default open=False, like file-tree folders). The Traj…a89fdfb -
Gemini: switch to gemini-2.0-flash; move key to header; redact errors
Three issues surfaced in the live chat box on the HF Space, all from the same Gemini call: LLM provider 'gemini' is unavailable: Gemini call failed: Client error '404 Not Found' for url 'https://generativelanguage.googleapis.com/v1beta/models/ gemini-1.5-flash:generateContent?key=AQ.Ab8RN6Ic8-CB7kqKS1-... (1) Google retired the gemini-1.5 family in mid-2025; the endpoint now returns 404 with a misleading 'model not found' wording. Switching the DEFAULT_MODELS['gemini'] entry to the current free-tier successor 'gemini-2.0-flash' (1M context, same JSON structured-output behaviour) restores parsing. (2) The provider was passing the key in the URL query string, so httpx's HTTPStatusError quoted the FULL request URL including ?key=... into the exception message --- which surfaced verbatim in the chat box and the build log. The key is now sent via the 'x-goog-api-key' HTTP header instead, so even when the next 4xx fires the URL no longer carrie…0f51210 -
LLM provider abstraction + conversational simulation builder + token leak fix
Implements the directive's LLM integration layer cleanly: five providers, zero hard SDK dependencies, never crashes when no key is configured. Also fixes the immediate security issue: the previous deploy attempt embedded a write-scope HF token directly in the git remote URL (visible to anyone running git remote -v). Security fix The token-embedded remote URL was sanitised: git remote set-url space https://huggingface.co/spaces/JoeTach/cdpr-simulator The leaked token MUST also be revoked manually at https://huggingface.co/settings/tokens . See the runbook in docs/hf-auth-troubleshoot.md for the full rotation procedure. src/cdpr/llm/ --- provider-agnostic LLM layer base.py LLMProvider Protocol + LLMMessage / LLMResponse dataclasses + LLMUnavailableError. config.py LLMConfig.from_env() that reads .env via dotenv (optional dep), with canonical env-var names (GEMINI_API_KEY, OPENROUTER_API_KEY, OLLAMA…1f10b7b
-
Smart data ingestion + figure safety + synthetic manifest + HF auth fix
Addresses the directive's six Major Problems without disturbing the primary Gradio workflow at http://127.0.0.1:7860. Major Problem 1 — robust multi-format CSV ingestion New module cdpr.ingest.smart_loader provides load_dataset() and ProfileReport across CSV / TSV / TXT / XLSX / XLS / ODS / Parquet / Feather. Auto-detects format from extension and magic bytes; missing engine surfaces a clean ImportError with the install command rather than a tangled traceback. Timestamp handling: any column whose normalised name matches the alias table (time/timestamp/ts/sec/date/...) OR any string column whose first non-null values parse as datetime is converted to seconds-from-first-sample under a new 't' column. The directive's exact failure case --- 2025-05-07 15:01:27.548198 --- yields t = 0, 1, 2, 3, 4 (seconds). Missing-value handling: recognises the full sentinel set the directive listed (none/None/NULL/NaN/nan/N/A/missing/blank plus common spreadshe…2ad96a7
-
Five built-in CDPR_SIMULATOR examples (3 trajectories + 2 data-driven)
Implements the directive's selectable demonstration set as built-in tutorials accessible identically from PowerShell and the Streamlit GUI. The registry in scripts/examples.py is the single source of truth. Phase 1 — physics-based motion simulation: * circle --- 3-DoF planar circular tracking on the dissertation_8cable robot. 0.05 m radius, 2 revolutions, ~12.6 s, quintic time-scaling for smooth start / stop. * spiral --- 6-DoF helical sweep (the directive's "one example with all six DoFs" requirement). 3-revolution spiral at z = 0.65 m +/- 0.04 m with bounded sinusoidal yaw (+/-17°), pitch (+/-6°) and roll (+/-3°) at distinct phase offsets. Bounded amplitudes (not monotonic rotations) are essential under pure PD: without orientation feedforward, a growing angle saturates the QP --- bounded oscillation keeps the angular error inside the cable wrench envelope…4a660db -
Phase-2 hardening sweep: parametric robots, URL CSVs, schema aliases
Implements all 14 improvements proposed in the post-mortem of the dissertation_8cable CSV failure log: #1 Register dissertation_8cable in the canonical build_robot() factory. The directive geometry moved from scripts/run_simulation.py into src/cdpr/robots/dissertation.py and is now reachable through the same public API as the catalog robots. Replay / PPO / SAC no longer crash on CSVs produced by --preset dissertation-circle. #2 Persist the full robot description (anchors, attachments, mass, inertia, tension bounds) in manifest.json under a new "robot_spec" block. A manifest-aware helper, robot_from_manifest_or_catalog, rebuilds any robot from this block --- catalog OR custom JSON OR inline override. Phase-2 workflows now work on any run_simulation.py output regardless of geometry source. #3 Cable-indexed column filter requires a numeric suffix. ``Layer`` no longer crashes the loader with int('ayer'). Same fix in train_from_csv, compare_…bdbf666 -
Unified Phase-1 + Phase-2 workflow with dual web/PowerShell parity
This commit fulfils the unified recovery directive: Phase-1 defined- trajectory simulation and Phase-2 CSV-driven training are now first- class on both the PowerShell terminal and the Streamlit web interface, with the CLI as the guaranteed scientific fallback while the deployed Streamlit Cloud worker remains intermittently flaky. Phase-1 (scripts/run_simulation.py): * 13 publication-grade figures per run (was 6) --- position, velocity, angular_velocity, acceleration, cable_tensions, cable_lengths, cable_stretch, tracking_error, rms_error_evolution, condition_number, trajectory_xy/_xz/_yz, scene_3d. Each plot wrapped in try/except so a single failure never drops the others; matplotlib figures are explicitly closed after savefig to bound worker memory. Phase-2 (scripts/train_from_csv.py + scripts/compare_models.py): * Five workflows on the CSVs Phase-1 emits: replay (analytic re-sim), mlp + pinn (supervised inverse-dynamics fit, z-scored I/O so loss curves are interpretab…310e4a9 -
Add PowerShell CLI escape hatch + Streamlit diagnostic fallback
The deployed Streamlit Cloud worker keeps blanking on every interaction even after the GUI was reconciled with the real SimulationRequest / TrajectorySpec contract --- the issue is now almost certainly in Streamlit Cloud's runtime, not in the Python script. Render, Cloudflare Pages, Supabase, and GitHub Actions are all green; only the Streamlit worker is unreliable. This commit lands two escape hatches plus one diagnostic toggle so the user is not blocked by the Cloud-side flakiness: scripts/run_simulation.py PowerShell-friendly local driver: python scripts/run_simulation.py --robot ipanema_class --kind circle produces every plot the Streamlit GUI would have shown, plus a timeseries CSV and a manifest with the git hash, into ./out/<robot>-<kind>-<timestamp>/. Each plot is wrapped in its own try/except so a single render failure does not drop the others. scripts/call_render.ps1 PowerShell wrapper around the live FastAPI on Render: .\scripts\call_render.…6045fb3 -
gui: match SimulationRequest contract exactly
The previous rewrite invented field names that SimulationRequest / TrajectorySpec / build_robot / PlatformState do not have. The new in-page error surface caught it on first try ("got an unexpected keyword argument 'tension_min'"). Reconciled the GUI with the actual spec dataclasses: * Robot identifiers now use the canonical names from cdpr.interface.specs --- ``point_mass_3d``, ``planar_translational``, ``ipanema_class``, ``cogiro_class`` (build_robot rejects the short ``ipanema`` etc. forms). * Removed the ``tension_min`` / ``tension_max`` inputs --- they are not SimulationRequest fields. Limits live in the tension distribution solver and are exposed through the tension_objective choice instead. * ``gravity`` is a 3-tuple, not a bool. Added a single "Apply gravity" checkbox that toggles between ``(0,0,-9.81)`` and ``(0,0,0)``. * Circle params use ``axis`` + ``angle_span`` (not ``period``); Lissajous uses ``amplitudes`` / ``frequencies`` / ``phases`` plural. All match…f2c274d -
Fix CI on 3.11+3.12 and harden Streamlit against any-rerun blank
CI was failing for two unrelated reasons that the new verbose pytest log finally surfaced: * **Python 3.12 — TypeError in KelvinVoigtModel.diagnostics().** ``@dataclass(slots=True)`` replaces the original class object with a freshly constructed slotted one. The ``__class__`` cell that zero-arg ``super()`` captures at compile time still points to the pre- replacement class, but ``self`` is an instance of the post-replacement class --- so the runtime check ``isinstance(self, __class__)`` raises ``TypeError: super(type, obj): obj must be an instance or subtype of type``. Replaced with an explicit ``CableModel.diagnostics(self, ...)`` call; this is correct here because ``CableModel`` is the single base class (no diamond inheritance). * **Python 3.11 — SyntaxError in cdpr/reports/bundle.py:216.** An f-string slot contained ``r.scenario_name.replace('_', r'\_')``. PEP 701 lifted the "no backslash in f-string expression" rule only in 3.12. Hoisted the ``.replace()`` …5cc4e7f -
Streamlit lazy per-tab render + CI diagnostics
GUI (src/cdpr/interface/gui.py): - matplotlib.use("Agg", force=True) defensively in case the module is imported through a non-streamlit_app entry-point. - CDPR_GUI_FRUGAL env knob trims the default workload to 0.5 s / 5 ms so the free-tier Streamlit Cloud worker (~1 GB) does not OOM on the first Run simulation click. - Result tabs are now lazy: each tab renders its figure only after the user clicks "Render <key>", and the figure is cached in session_state for the rest of the session. Previously six matplotlib figures — including the 3D scene — were rendered on every script rerun, which silently killed the worker and left a blank page. - 3D scene is marked "heavy" with an explicit caption; its trajectory is subsampled to 200 points to bound memory. - Plot helpers import matplotlib / plots2d / scene lazily so the initial module load stays cheap. - _log() writes to stderr so the Streamlit Cloud manage-app log shows what the worker was doing right before it died. - Ever…d02aecd
-
Streamlit GUI: form-batched parameters + visible error surfacing
The previous GUI re-ran the entire script on every widget change. When the trajectory kind toggled between hold/line/circle/lissajous, the dynamically-appearing slider blocks (Ax/Ay/Az/fx/fy/fz, or radius, or the text inputs) caused widget-key collisions and intermediate runs that crashed silently on Streamlit Cloud's free tier --- leaving a blank page after any sidebar interaction. Fixes: - All parameter widgets live inside a single st.form('params_form'). Streamlit only re-runs the script when the user clicks 'Apply parameters'. Editing a slider mid-form no longer triggers a rerun. - Every widget carries an explicit key= so state persists cleanly across reruns regardless of which conditional branch is active. - All kind-specific widgets are always rendered (just read selectively based on kind). Avoids the appear/disappear race. - _parse_xyz wraps the text inputs in a try/except --- a half-typed '0.1, 0.' no longer raises ValueError. - render() wraps everything in try/exc…206bfca -
FastAPI: friendly root route at GET / (was 404)
Adds a JSON service descriptor listing the available endpoints and linking to the auto-generated OpenAPI docs at /docs and /redoc. The 404 at root was correct but unhelpful when someone visits the Render URL in a browser. All five API tests still pass.04f9f25 -
Add Supabase storage adapter with lazy dual-write mirror
- cdpr.storage.supabase: optional SupabaseMirror that copies experiment metadata into Supabase when SUPABASE_URL + SUPABASE_SERVICE_ROLE_KEY are set; local disk stays the source of truth. - recorder.record_simulation gains mirror_to_supabase / supabase_metrics kwargs; defaults preserve Phase 1-6 behaviour (no cloud writes). - supabase/config.toml links the project (ref nohbtlhhisfiajjsbguy). - supabase/migrations/20260526000001_initial_schema.sql replicates the schema as a CLI-runnable migration. - pyproject: [storage] extra installs the supabase Python client. Recording tests pass (5/5); module imports cleanly without supabase-py installed (lazy guard returns False).52db224 -
Initial commit: cdpr Phases 1-7 + deployment scaffolding
Scientific core (Phase 1): - Pose/Twist/Wrench primitives, SE(3) algebra - Robot configuration (anchors, attachments, inertia, cable limits) - Inverse + forward kinematics, structure matrix - Tension distribution (bounded QP), wrench feasibility - Three per-cable physics: massless, linear-elastic, Irvine catenary - Rigid-body Newton-Euler dynamics, RK4 + semi-implicit integrators - Workspace analysis (WCW, WFW, voxel grid) - Parametric trajectories with retiming - Reference robot catalogue (IPAnema-class, CoGiRo-class) Visualisation + ingestion + reports (Phase 2): - 2D analytics, 3D scene with tension heatmap and singularity indicator - Animation (playback, frame stepping, live streaming) with MP4/GIF export - Workspace volume rendering - Experiment recording (CSV + JSON metadata + reproducibility manifest) - Replay engine + dataset comparison - Publication-grade reports: LaTeX figures, booktabs tables, Markdown - FastAPI service + Streamlit research console - Optional external-physi…5f38e95