Spaces:
Running
Running
Download app.py from minjiechen/ThinkPower: direct link, hf CLI and curl.
- Browser
- Download file 4.34 kB
-
https://huggingface.co/spaces/minjiechen/ThinkPower/resolve/main/app.py
- Command line
-
hf download hf://spaces/minjiechen/ThinkPower/app.py
-
curl -L -o app.py https://huggingface.co/spaces/minjiechen/ThinkPower/resolve/main/app.py
4.34 kB
| """ThinkPower: analytical dashboard + preserved NGSpice workspace.""" | |
| import json,os,mimetypes,re,subprocess,sys,threading,urllib.request,urllib.error,signal | |
| from http.server import BaseHTTPRequestHandler,ThreadingHTTPServer | |
| from pathlib import Path | |
| from urllib.parse import unquote | |
| from models import CATALOG,analyze,state_model,control,analyze_pu,state_model_pu | |
| from agent import inspect_image | |
| ROOT=Path(__file__).resolve().parent | |
| LEGACY=ROOT/'library/ngspice/studies/xfly6s_xfly8s_c3l_scaled_comparison/gui/xfly_compare_gui.py' | |
| MAX_BODY=12_000_000 | |
| class Handler(BaseHTTPRequestHandler): | |
| def log_message(self,fmt,*args):pass # Uploaded data and credentials never go to logs. | |
| def send(self,body,kind='application/json',status=200): | |
| if isinstance(body,(dict,list)):body=json.dumps(body,allow_nan=False).encode() | |
| elif isinstance(body,str):body=body.encode() | |
| self.send_response(status);self.send_header('Content-Type',kind);self.send_header('Content-Length',str(len(body))) | |
| self.send_header('X-Content-Type-Options','nosniff');self.send_header('Referrer-Policy','same-origin');self.send_header('Cache-Control','no-store' if kind=='application/json' else 'no-cache');self.end_headers();self.wfile.write(body) | |
| def proxy(self): | |
| tail=self.path[len('/simulation'):] | |
| if not tail:tail='/' | |
| data=None | |
| if self.command=='POST': | |
| length=int(self.headers.get('Content-Length','0')) | |
| if length>MAX_BODY:raise ValueError('Request too large') | |
| data=self.rfile.read(length) | |
| req=urllib.request.Request('http://127.0.0.1:8081'+tail,data=data,headers={'Content-Type':'application/json'}) | |
| try: | |
| with urllib.request.urlopen(req,timeout=150) as r:b=r.read();kind=r.headers.get('Content-Type','text/html');status=r.status | |
| if 'text/html' in kind: | |
| t=b.decode();t=t.replace('/api/','/simulation/api/').replace('/assets/','/simulation/assets/').replace('/runs/','/simulation/runs/') | |
| b=t.encode() | |
| elif 'application/json' in kind:b=b.replace(b'"/runs/',b'"/simulation/runs/') | |
| self.send(b,kind,status) | |
| except (OSError,urllib.error.URLError):self.send({'error':'The NGSpice workspace is starting or unavailable. The analytical workspace remains available.'},status=503) | |
| def do_GET(self): | |
| if self.path.startswith('/simulation'): | |
| self.proxy();return | |
| path=unquote(self.path.split('?')[0]) | |
| if path in ['/healthz','/api/health']: | |
| self.send(dict(ok=True,vision_configured=bool(os.environ.get('HF_TOKEN')),version='1.0'));return | |
| if path=='/api/catalog':self.send(CATALOG);return | |
| if path=='/':path='/static/index.html' | |
| elif path in ['/style.css','/app.js','/engine.js','/models-data.json'] or path.startswith('/assets/'):path='/static'+path | |
| if not path.startswith('/static/'):self.send({'error':'Not found'},status=404);return | |
| target=(ROOT/path.lstrip('/')).resolve() | |
| if not target.is_relative_to(ROOT/'static') or not target.is_file():self.send({'error':'Not found'},status=404);return | |
| self.send(target.read_bytes(),mimetypes.guess_type(target)[0] or 'application/octet-stream') | |
| def do_POST(self): | |
| if self.path.startswith('/simulation/'): | |
| self.proxy();return | |
| routes={'/api/analyze-pu':analyze_pu,'/api/state-model-pu':state_model_pu,'/api/analyze':analyze,'/api/inspect':inspect_image,'/api/state-model':state_model,'/api/control':control} | |
| if self.path not in routes:self.send({'error':'Not found'},status=404);return | |
| try: | |
| n=int(self.headers.get('Content-Length','0')) | |
| if not 0<n<=MAX_BODY:raise ValueError('Request is empty or too large') | |
| p=json.loads(self.rfile.read(n)) | |
| if not isinstance(p,dict):raise ValueError('Expected a JSON object') | |
| self.send(routes[self.path](p)) | |
| except (ValueError,KeyError,TypeError,OverflowError) as e:self.send({'error':str(e)[:500]},status=400) | |
| except Exception:self.send({'error':'Analysis could not complete. Check the circuit description and provider settings.'},status=500) | |
| if __name__=='__main__': | |
| legacy=None | |
| if LEGACY.exists() and os.environ.get('ENABLE_NGSPICE','1')=='1': | |
| legacy=subprocess.Popen([sys.executable,str(LEGACY),'--host','127.0.0.1','--port','8081','--no-open'],cwd=ROOT,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL) | |
| signal.signal(signal.SIGTERM,lambda *_: sys.exit(0)) | |
| try:ThreadingHTTPServer(('0.0.0.0',int(os.environ.get('PORT','8080'))),Handler).serve_forever() | |
| finally: | |
| if legacy:legacy.terminate() | |