Spaces:
Sleeping
Sleeping
shehanmakani
fix: replace random Eg/efficiency in Type II score with deterministic ML prediction
b90b0f5 Download api/main_v2.py from chemenovausa/orbitchem-api: direct link, hf CLI and curl.
- Browser
- Download file 28.9 kB
-
https://huggingface.co/spaces/chemenovausa/orbitchem-api/resolve/main/api/main_v2.py
- Command line
-
hf download hf://spaces/chemenovausa/orbitchem-api/api/main_v2.py
-
curl -L -o main_v2.py https://huggingface.co/spaces/chemenovausa/orbitchem-api/resolve/main/api/main_v2.py
28.9 kB
| """ | |
| OrbitChem API v1.1 β drop-in replacement for main.py with: | |
| - _load_db() merges ingredients_db_space.csv (38 space-grade materials) | |
| - /spacecraft-full uses vertical="space" for regulatory_guardian | |
| Run: uvicorn api.main_v2:app --port 8003 | |
| """ | |
| import sys, os | |
| sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | |
| from fastapi import FastAPI, HTTPException, Request | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from fastapi.responses import StreamingResponse | |
| ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | |
| DB_PATH = os.path.join(ROOT, "data", "ingredients_db.csv") | |
| _EXTRA_ORIGINS = [o.strip() for o in os.getenv("ALLOWED_ORIGINS", "").split(",") if o.strip()] | |
| app = FastAPI( | |
| title="OrbitChem API", | |
| version="1.1.0", | |
| description="ChemeNova LLC β Aerospace & Space Materials Chemistry Intelligence", | |
| ) | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=[ | |
| "http://localhost:5173", | |
| "http://localhost:3001", | |
| "https://chemenova.com", | |
| "https://www.chemenova.com", | |
| "https://app.chemenova.com", | |
| "https://orbitchem.chemenova.com", | |
| *_EXTRA_ORIGINS, | |
| ], | |
| allow_origin_regex=r"https://orbitchem-web.*\.vercel\.app", | |
| allow_credentials=True, allow_methods=["*"], allow_headers=["*"], | |
| ) | |
| def _load_db(): | |
| import pandas as pd | |
| df = pd.read_csv(DB_PATH) | |
| space_path = os.path.join(os.path.dirname(DB_PATH), "ingredients_db_space.csv") | |
| if os.path.exists(space_path): | |
| df_space = pd.read_csv(space_path) | |
| df = pd.concat([df, df_space], ignore_index=True) | |
| return df | |
| def _serialize(obj): | |
| if obj is None: return None | |
| if hasattr(obj, "__dict__"): | |
| return {k: _serialize(v) for k, v in obj.__dict__.items()} | |
| if isinstance(obj, dict): | |
| return {k: _serialize(v) for k, v in obj.items()} | |
| if isinstance(obj, list): | |
| return [_serialize(i) for i in obj] | |
| return obj | |
| def root(): | |
| return {"service":"OrbitChem API","version":"1.1.0","docs":"/docs","health":"/health","status":"ok"} | |
| def health(): | |
| return { | |
| "status": "ok", | |
| "service": "OrbitChem", | |
| "version": "1.1.0", | |
| "modules": [ | |
| "outgassing", "radiation_stability", "thermal_cycling", | |
| "circular_formulation_engine", "regulatory_guardian", | |
| "materials_adapter", "amdt", | |
| ], | |
| } | |
| def list_materials(): | |
| """List all space-grade materials with key properties.""" | |
| try: | |
| import pandas as pd | |
| db = _load_db() | |
| space_df = db[db["Vertical"] == "space"] if "Vertical" in db.columns else db | |
| materials = [] | |
| for _, row in space_df.iterrows(): | |
| materials.append({ | |
| "name": row.get("Ingredient", ""), | |
| "function": row.get("Function", ""), | |
| "vp_kPa": row.get("Vapour_Pressure_kPa", None), | |
| "cte_ppm_K": row.get("CTE_ppm_K", None), | |
| "modulus_GPa": row.get("Elastic_Modulus_GPa", None), | |
| "uts_MPa": row.get("Tensile_Strength_MPa", None), | |
| "cost_usd_kg": row.get("Cost_USD_kg", None), | |
| }) | |
| return {"count": len(materials), "materials": materials} | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| async def outgassing(request: Request): | |
| """ | |
| NASA/ESA outgassing screening (ASTM E595). | |
| Body: { "blend": {"Material A": 60, ...} } | |
| Returns: TML, CVCM, VCM predictions, NASA/ESA pass/fail | |
| """ | |
| body = await request.json() | |
| blend = body.get("blend", {}) | |
| try: | |
| from modules.outgassing import run_outgassing_screen | |
| db = _load_db() | |
| result = run_outgassing_screen(blend, db) | |
| return _serialize(result) | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| async def radiation_stability(request: Request): | |
| """ | |
| Radiation stability prediction for spacecraft materials. | |
| Body: { | |
| "blend": {...}, | |
| "environment": "LEO", # LEO | GEO | deep_space | ISS | lunar | |
| "mission_years": 5.0 | |
| } | |
| """ | |
| body = await request.json() | |
| blend = body.get("blend", {}) | |
| environment = body.get("environment", "LEO") | |
| mission_yrs = float(body.get("mission_years", 5.0)) | |
| try: | |
| from modules.radiation_stability import run_radiation_stability | |
| db = _load_db() | |
| result = run_radiation_stability(blend, db, environment, mission_yrs) | |
| return _serialize(result) | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| async def thermal_cycling(request: Request): | |
| """ | |
| Thermal cycling fatigue prediction (Coffin-Manson + delamination G). | |
| Body: { | |
| "blend": {...}, | |
| "orbit": "LEO", # LEO | GEO | MEO | lunar | deep_space | |
| "mission_years": 5.0, | |
| "substrate": "aluminum" # aluminum | titanium | carbon_fiber | invar | silicon | steel | |
| } | |
| """ | |
| body = await request.json() | |
| blend = body.get("blend", {}) | |
| orbit = body.get("orbit", "LEO") | |
| mission_yrs = float(body.get("mission_years", 5.0)) | |
| substrate = body.get("substrate", "aluminum") | |
| try: | |
| from modules.thermal_cycling import run_thermal_cycling | |
| db = _load_db() | |
| result = run_thermal_cycling(blend, db, orbit, mission_yrs, substrate) | |
| return _serialize(result) | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| async def materials_profile(request: Request): | |
| """ | |
| Run pymatgen/matminer materials featurization on the blend. | |
| Body: { "blend": {...}, "vertical": "industrial" } | |
| """ | |
| body = await request.json() | |
| blend = body.get("blend", {}) | |
| vertical = body.get("vertical", "industrial") | |
| try: | |
| from modules.public_integrations import execute_public_integration_plan | |
| db = _load_db() | |
| result = execute_public_integration_plan( | |
| blend=blend, db=db, | |
| vertical=vertical, platform="orbitchem", | |
| ) | |
| return result.to_dict() | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| async def spacecraft_full(request: Request): | |
| """ | |
| Full OrbitChem qualification suite: outgassing + radiation + thermal cycling. | |
| Body: { | |
| "blend": {...}, | |
| "environment": "LEO", | |
| "orbit": "LEO", | |
| "mission_years": 5.0, | |
| "substrate": "aluminum" | |
| } | |
| """ | |
| body = await request.json() | |
| blend = body.get("blend", {}) | |
| environment = body.get("environment", "LEO") | |
| orbit = body.get("orbit", "LEO") | |
| mission_yrs = float(body.get("mission_years", 5.0)) | |
| substrate = body.get("substrate", "aluminum") | |
| try: | |
| from modules.outgassing import run_outgassing_screen | |
| from modules.radiation_stability import run_radiation_stability | |
| from modules.thermal_cycling import run_thermal_cycling | |
| from modules.circular_formulation_engine import run_circular_formulation_engine | |
| from modules.regulatory_guardian import run_regulatory_guardian | |
| db = _load_db() | |
| outgas = run_outgassing_screen(blend, db) | |
| rad = run_radiation_stability(blend, db, environment, mission_yrs) | |
| thermal = run_thermal_cycling(blend, db, orbit, mission_yrs, substrate) | |
| circular = run_circular_formulation_engine(blend, db) | |
| guardian = run_regulatory_guardian(blend, db, "space", circular) | |
| return { | |
| "outgassing": _serialize(outgas), | |
| "radiation": _serialize(rad), | |
| "thermal_cycling": _serialize(thermal), | |
| "circular": _serialize(circular), | |
| "guardian": _serialize(guardian), | |
| "qualification_summary": { | |
| "nasa_outgas_pass": outgas.nasa_pass, | |
| "esa_outgas_pass": outgas.esa_pass, | |
| "radiation_rating": rad.overall_rating, | |
| "thermal_pass": thermal.blend_passes, | |
| "guardian_status": guardian.status, | |
| }, | |
| } | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # FORMULATE (standard + streaming SSE) β from IntelliForm Enterprise | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| async def formulate(request: Request): | |
| """ | |
| Formulate a blend from a natural-language request. | |
| Body: { "input_text": "...", "vertical": "space", "batch_size": 1000, "opt_mode": "lp" } | |
| """ | |
| body = await request.json() | |
| try: | |
| from modules.llm_parser import parse_request | |
| from modules.optimizer import run_optimization | |
| from modules.verticals import filter_db_by_vertical | |
| from modules.ecometrics import compute_ecometrics | |
| from modules.regulatory import get_blend_report | |
| db = _load_db() | |
| parsed = parse_request(body.get("input_text", ""), body.get("llm_provider")) | |
| vdb = filter_db_by_vertical(db, body.get("vertical", "space")) | |
| result = run_optimization(vdb, | |
| max_cost=parsed.max_cost, | |
| min_bio=parsed.min_bio, | |
| min_perf=parsed.min_perf, | |
| max_concentration=0.70, | |
| vertical=body.get("vertical", "space")) | |
| eco = compute_ecometrics(result.blend, db) if result.success else None | |
| reg = get_blend_report(result.blend) if result.success else None | |
| return { | |
| "success": result.success, | |
| "blend": result.blend, | |
| "cost_per_kg": result.cost_per_kg, | |
| "bio_pct": result.bio_pct, | |
| "perf_score": result.perf_score, | |
| "parsed": _serialize(parsed), | |
| "eco": _serialize(eco), | |
| "reg": _serialize(reg), | |
| } | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| async def formulate_stream(request: Request): | |
| """ | |
| SSE streaming formulation β emits status events then a complete event. | |
| Frontend: use fetch() + ReadableStream (EventSource doesn't support POST). | |
| """ | |
| import asyncio, json as _json | |
| body = await request.json() | |
| async def generate(): | |
| statuses = [ | |
| "Initialising materials database...", | |
| f"Loading {body.get('vertical', 'space')} ingredient set...", | |
| "Parsing mission formulation brief...", | |
| "Running LP optimisation...", | |
| "Computing outgassing and radiation proxies...", | |
| "Finalising blend...", | |
| ] | |
| for msg in statuses: | |
| yield f"event: status\ndata: {_json.dumps({'message': msg})}\n\n" | |
| await asyncio.sleep(0.18) | |
| loop = asyncio.get_event_loop() | |
| try: | |
| result = await loop.run_in_executor(None, lambda: _run_formulate_sync(body)) | |
| except Exception as e: | |
| yield f"event: error\ndata: {_json.dumps({'error': str(e)})}\n\n" | |
| return | |
| yield f"event: complete\ndata: {_json.dumps(result)}\n\n" | |
| return StreamingResponse( | |
| generate(), | |
| media_type="text/event-stream", | |
| headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no", "Connection": "keep-alive"}, | |
| ) | |
| def _run_formulate_sync(body: dict) -> dict: | |
| from modules.llm_parser import parse_request | |
| from modules.optimizer import run_optimization | |
| from modules.verticals import filter_db_by_vertical | |
| from modules.ecometrics import compute_ecometrics | |
| from modules.regulatory import get_blend_report | |
| db = _load_db() | |
| parsed = parse_request(body.get("input_text", ""), body.get("llm_provider")) | |
| vdb = filter_db_by_vertical(db, body.get("vertical", "space")) | |
| result = run_optimization(vdb, | |
| max_cost=parsed.max_cost, | |
| min_bio=parsed.min_bio, | |
| min_perf=parsed.min_perf, | |
| max_concentration=0.70, | |
| vertical=body.get("vertical", "space")) | |
| eco = compute_ecometrics(result.blend, db) if result.success else None | |
| reg = get_blend_report(result.blend) if result.success else None | |
| return { | |
| "success": result.success, | |
| "blend": result.blend, | |
| "cost_per_kg": result.cost_per_kg, | |
| "bio_pct": result.bio_pct, | |
| "perf_score": result.perf_score, | |
| "parsed": _serialize(parsed), | |
| "eco": _serialize(eco), | |
| "reg": _serialize(reg), | |
| } | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # MATERIAL INTELLIGENCE BRIEF β called by demo.html Module 1 | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| async def material_brief(request: Request): | |
| """ | |
| Generate a material intelligence brief via Groq (llama-3.3-70b-versatile). | |
| Body: { "raw_prompt": "full prompt string with JSON schema instructions" } | |
| Returns: { "result": { ...parsed JSON object... } } | |
| """ | |
| import json as _json | |
| body = await request.json() | |
| raw_prompt = body.get("raw_prompt", body.get("query", "")) | |
| try: | |
| import httpx | |
| key = os.getenv("GROQ_API_KEY", "") | |
| if not key: | |
| raise HTTPException(status_code=503, detail="GROQ_API_KEY not configured on server.") | |
| async with httpx.AsyncClient(timeout=45) as client: | |
| r = await client.post( | |
| "https://api.groq.com/openai/v1/chat/completions", | |
| json={ | |
| "model": "llama-3.3-70b-versatile", | |
| "messages": [{"role": "user", "content": raw_prompt}], | |
| "temperature": 0.3, | |
| "max_tokens": 1400, | |
| "response_format": {"type": "json_object"}, | |
| }, | |
| headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"}, | |
| ) | |
| data = r.json() | |
| raw = data["choices"][0]["message"]["content"] | |
| result = _json.loads(raw.replace("```json", "").replace("```", "").strip()) | |
| return {"result": result} | |
| except HTTPException: | |
| raise | |
| except Exception as e: | |
| raise HTTPException(status_code=502, detail=f"Brief generation error: {e}") | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # GROQ PROXY β keeps API key server-side; called from demo.html | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| async def groq_proxy(request: Request): | |
| """Proxy Groq API calls so the key stays server-side (never in client JS).""" | |
| try: | |
| import httpx | |
| body = await request.json() | |
| key = os.getenv("GROQ_API_KEY", "") | |
| if not key: | |
| raise HTTPException(status_code=503, detail="GROQ_API_KEY not configured on server.") | |
| async with httpx.AsyncClient(timeout=30) as client: | |
| r = await client.post( | |
| "https://api.groq.com/openai/v1/chat/completions", | |
| json=body, | |
| headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"}, | |
| ) | |
| return r.json() | |
| except HTTPException: | |
| raise | |
| except Exception as e: | |
| raise HTTPException(status_code=502, detail=f"Groq proxy error: {e}") | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # MEMORY NETWORK β accept / reject / stats (from IntelliForm Enterprise) | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def memory_stats(): | |
| from api.memory import memory | |
| return memory.get_summary_stats() | |
| async def memory_accept(request: Request): | |
| from api.memory import memory | |
| body = await request.json() | |
| memory.record("blend_accepted", body.get("blend", {}), body.get("vertical", "space"), outcome="positive") | |
| return {"recorded": True, "event": "blend_accepted"} | |
| async def memory_reject(request: Request): | |
| from api.memory import memory | |
| body = await request.json() | |
| memory.record_rejection( | |
| body.get("blend", {}), | |
| body.get("vertical", "space"), | |
| body.get("rejected_ingredients", []), | |
| body.get("reason", "User rejected"), | |
| ) | |
| return {"recorded": True, "event": "blend_rejected"} | |
| async def memory_pilot_outcome(request: Request): | |
| from api.memory import memory | |
| body = await request.json() | |
| passed = bool(body.get("passed", True)) | |
| memory.record_pilot_outcome( | |
| body.get("blend", {}), | |
| body.get("vertical", "space"), | |
| passed, | |
| failure_type=body.get("failure_type"), | |
| failure_ingredients=body.get("failure_ingredients"), | |
| ) | |
| return {"recorded": True, "event": "pilot_batch_passed" if passed else "pilot_batch_failed"} | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # AGENT SWARM β aerospace expert commentary on a blend | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| async def agent_swarm(request: Request): | |
| """ | |
| Run aerospace or green-chemistry expert commentary on a provided blend. | |
| Body: { "blend": {...}, "cost_per_kg": 85.0, "bio_pct": 0, "perf_score": 90, | |
| "application_type": "aerospace", "raw_input": "..." } | |
| """ | |
| body = await request.json() | |
| try: | |
| from modules.agents import run_agent_swarm | |
| from modules.optimizer import OptResult | |
| from modules.llm_parser import ParseResult | |
| result = OptResult( | |
| success=True, | |
| blend=body.get("blend", {}), | |
| cost_per_kg=float(body.get("cost_per_kg", 0)), | |
| bio_pct=float(body.get("bio_pct", 0)), | |
| perf_score=float(body.get("perf_score", 0)), | |
| status="Provided", | |
| ) | |
| parsed = ParseResult( | |
| max_cost=float(body.get("cost_per_kg", 0)), | |
| min_bio=0.0, | |
| min_perf=float(body.get("perf_score", 80)), | |
| application_type=body.get("application_type", "aerospace"), | |
| reasoning="", | |
| parser_backend="api", | |
| raw_input=body.get("raw_input", ""), | |
| ) | |
| comments = run_agent_swarm(result, parsed) | |
| return {"comments": comments} | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # INGREDIENTS LIST | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def list_ingredients(vertical: str = "space"): | |
| try: | |
| db = _load_db() | |
| if "Vertical" in db.columns and vertical: | |
| db = db[db["Vertical"] == vertical] | |
| cols = ["Ingredient", "Function", "Cost_USD_kg", "Bio_based_pct", | |
| "Performance_Score", "REACH_Flag", "Vertical"] | |
| cols = [c for c in cols if c in db.columns] | |
| return {"count": len(db), "ingredients": db[cols].to_dict(orient="records")} | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # BOM AUDIT | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| _FUNCTION_GROUP = { | |
| "Structural Adhesive": "adhesive", | |
| "Flexible Structural Adhesive": "adhesive", | |
| "Structural Film Adhesive": "adhesive", | |
| "Elastomeric Adhesive / Sealant": "adhesive", | |
| "Electronic Potting Compound": "potting", | |
| "Elastomeric Potting / Encapsulant":"potting", | |
| "Thermally Conductive Potting": "potting", | |
| "Optical / Low-Outgas Epoxy": "potting", | |
| "Space Mechanism Lubricant (PFPE)": "lubricant", | |
| "Space Mechanism Lubricant Oil (PFPE)": "lubricant", | |
| "Vacuum Lubricant Oil (PFPE)": "lubricant", | |
| "Dry Film Lubricant": "lubricant", | |
| "High-Temp Dry Film Lubricant": "lubricant", | |
| "Thermal Insulation Film": "film", | |
| "Multi-Layer Insulation Facing": "film", | |
| "Thermal Control Coating (White)": "coating", | |
| "Thermal Control Coating": "coating", | |
| "Optical Baffle / Black Coating": "coating", | |
| "Ablative TPS": "ablative", | |
| "Ablative Insulation": "ablative", | |
| } | |
| async def bom_audit(request: Request): | |
| """ | |
| Audit a bill of materials for space qualification compliance. | |
| Each material is screened individually at 100% weight fraction. | |
| Body: { "materials": ["Kapton HN", "Hysol EA 9394", ...] } | |
| """ | |
| body = await request.json() | |
| materials = body.get("materials", []) | |
| if not materials or not isinstance(materials, list): | |
| raise HTTPException(status_code=422, detail="'materials' must be a non-empty list of strings") | |
| try: | |
| from modules.outgassing import run_outgassing_screen, _resolve_ing | |
| db = _load_db() | |
| idx = db.set_index("Ingredient") if "Ingredient" in db.columns else db | |
| space_db = db[db["Vertical"] == "space"] if "Vertical" in db.columns else db | |
| results = [] | |
| for mat in materials[:50]: # cap at 50 per request | |
| mat = str(mat).strip() | |
| if not mat: | |
| continue | |
| report = run_outgassing_screen({mat: 100.0}, db) | |
| rec = report.records[0] if report.records else None | |
| matched = _resolve_ing(mat, idx) | |
| function = "" | |
| if matched: | |
| row = idx.loc[matched] | |
| function = str(row.get("Function", "") or "") | |
| substitutions = [] | |
| if not report.nasa_pass and matched: | |
| grp = _FUNCTION_GROUP.get(function, "") | |
| candidates = [] | |
| for _, srow in space_db.iterrows(): | |
| sname = str(srow.get("Ingredient", "")) | |
| if sname == matched: | |
| continue | |
| sfn = str(srow.get("Function", "") or "") | |
| sgrp = _FUNCTION_GROUP.get(sfn, "") | |
| # match by group first, fall back to exact function | |
| if grp and sgrp != grp: | |
| continue | |
| elif not grp and sfn != function: | |
| continue | |
| try: | |
| tml_s = float(srow.get("TML_pct", 999)) | |
| cvcm_s = float(srow.get("CVCM_pct", 999)) | |
| except (TypeError, ValueError): | |
| continue | |
| if tml_s <= 1.0 and cvcm_s <= 0.1: | |
| candidates.append({"name": sname, "tml_pct": tml_s, "cvcm_pct": cvcm_s}) | |
| substitutions = sorted(candidates, key=lambda x: x["tml_pct"])[:3] | |
| results.append({ | |
| "material": mat, | |
| "matched_name": matched, | |
| "in_db": matched is not None, | |
| "function": function, | |
| "tml_pct": rec.tml_contribution_pct if rec else None, | |
| "cvcm_pct": rec.cvcm_contribution_pct if rec else None, | |
| "nasa_pass": report.nasa_pass, | |
| "esa_pass": report.esa_pass, | |
| "risk_level": rec.risk_level if rec else "unknown", | |
| "substitutions": substitutions, | |
| }) | |
| pass_count = sum(1 for r in results if r["nasa_pass"]) | |
| fail_count = len(results) - pass_count | |
| critical_count = sum(1 for r in results if r["risk_level"] == "critical") | |
| return { | |
| "audit": results, | |
| "summary": { | |
| "total": len(results), | |
| "pass": pass_count, | |
| "fail": fail_count, | |
| "critical": critical_count, | |
| }, | |
| } | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| async def contamination_proximity(request: Request): | |
| """ | |
| Estimate molecular contamination deposited on a nearby optical surface | |
| from outgassing of a spacecraft material over the mission life. | |
| Body: { "material": "Sylgard 184", "source_area_cm2": 50, "distance_cm": 10, | |
| "T_source_C": 40, "T_optic_C": 20, "mission_years": 3 } | |
| """ | |
| body = await request.json() | |
| try: | |
| from modules.contamination import run_contamination_proximity | |
| db = _load_db() | |
| result = run_contamination_proximity( | |
| material=str(body.get("material", "")), | |
| db=db, | |
| source_area_cm2=float(body.get("source_area_cm2", 50.0)), | |
| distance_cm=float(body.get("distance_cm", 10.0)), | |
| T_source_C=float(body.get("T_source_C", 40.0)), | |
| T_optic_C=float(body.get("T_optic_C", 20.0)), | |
| mission_years=float(body.get("mission_years", 3.0)), | |
| ) | |
| return _serialize(result) | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| async def spacechem_predict(request: Request): | |
| """ | |
| Predict OPV bandgap (Eg) and AM0 absorption efficiency (Ξ·) for a SMILES | |
| string via the SpaceChem-AI ExtraTrees models (Notebook 06). Deterministic β | |
| same SMILES always returns the same Eg/Ξ·/space_score. | |
| Body: { "smiles": "...", "name": "Pentacene" } | |
| """ | |
| body = await request.json() | |
| smiles = str(body.get("smiles", "")).strip() | |
| name = str(body.get("name", "Unknown")) | |
| if not smiles: | |
| raise HTTPException(status_code=422, detail="'smiles' is required") | |
| try: | |
| from modules.space_solar import screen_molecule | |
| record = screen_molecule(smiles, name) | |
| if record is None: | |
| raise HTTPException(status_code=422, detail=f"Invalid SMILES: '{smiles}'") | |
| return _serialize(record) | |
| except HTTPException: | |
| raise | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| if __name__ == "__main__": | |
| import uvicorn | |
| port = int(os.getenv("PORT", 8003)) | |
| uvicorn.run("api.main_v2:app", host="0.0.0.0", port=port, reload=True) | |