Spaces:
Running
Running
File size: 4,344 Bytes
3bb2683 424d972 3bb2683 48f961a 3bb2683 424d972 3bb2683 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | """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()
|