Spaces:
Paused
Paused
encryptd commited on
Commit ·
9c97cfd
1
Parent(s): e11fc60
prog update
Browse files22 unmodified lines232425262728299 unmodified lines394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192935 unmodified lines991001011021031041051064 unmodified lines11111211311411511611711811912012112212312412512612712822 unmodified linesif "VLLM_PID" in os.environ:returnprint("🚀 Starting vLLM engine...")command = ["python3", "-m", "vllm.entrypoints.openai.api_server","--model", MODEL_ID,"--host", "127.0.0.1",9 unmodified linesstart_vllm()# --- STEP 2: DEFINE THE API PROXY (FastAPI) ---# We create the main app firstapp = FastAPI()@app.api_route("/v1/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])async def gatekeeper_proxy(path: str, request: Request):"""This intercepts external calls (like from Docling) and cleans thinking tags."""target_url = f"http://127.0.0.1:{VLLM_PORT}/v1/{path}"headers = {k: v for k, v in request.headers.items() if k.lower() not in ["host", "content-length"]}async with httpx.AsyncClient(timeout=300.0) as client:try:if path == "chat/completions" and request.method == "POST":body = await request.json()if not body.get("stream", False):resp = await client.post(target_url, headers=headers, json=body)if resp.status_code == 200:data = resp.json()content = data["choices"][0]["message"].get("content", "")# STRIP THINKING TAGS FOR EXTERNAL APIif "</think>" in content:data["choices"][0]["message"]["content"] = content.split("</think>")[-1].strip()return JSONResponse(content=data)return JSONResponse(status_code=resp.status_code, content=resp.json())proxy_req = client.build_request(request.method, target_url, headers=headers, content=await request.body())r = await client.send(proxy_req, stream=True)return StreamingResponse(r.aiter_raw(), status_code=r.status_code, headers=dict(r.headers))except Exception as e:return JSONResponse(status_code=503, content={"error": f"API Proxy Error: {str(e)}"})# --- STEP 3: DEFINE THE GRADIO UI ---def run_ui_test(image, prompt):print(f"--- UI Inference Triggered ---") # This will show in logsif image is None: return "⚠️ Please upload an image."# Internal direct call to vLLMclient = OpenAI(base_url=f"http://127.0.0.1:{VLLM_PORT}/v1", api_key="EMPTY")try:image = image.convert("RGB")buffered = BytesIO()image.save(buffered, format="JPEG")b64 = base64.b64encode(buffered.getvalue()).decode('utf-8')completion = client.chat.completions.create(model=MODEL_ID,messages=[{"role": "user", "content": [{"type": "text", "text": prompt or "Convert to markdown."},{"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b64}"}}]}],5 unmodified linesprint(f"UI Error: {e}")return f"❌ Error: {e}"with gr.Blocks(title="NuMarkdown API") as demo:gr.Markdown("# NuMarkdown L40S API Server")with gr.Row():with gr.Column():img_input = gr.Image(type="pil", label="Input Document")4 unmodified linesbtn.click(run_ui_test, inputs=[img_input, txt_input], outputs=[out])# --- STEP 4: CORRECT MOUNTING ORDER ---# 1. Enable the queue (Mandatory for button functionality in Gradio 5)demo.queue()# 2. Patch the bug in Gradio 5 that causes the AttributeErrordemo.max_file_size = 100 * 1024 * 1024# 3. Mount Gradio to the FastAPI app at the root path "/"# This must happen AFTER we define our FastAPI /v1 routes to ensure routing priorityapp = gr.mount_gradio_app(app, demo, path="/")if __name__ == "__main__":# Ensure workers=1 to prevent port conflictsuvicorn.run(app, host="0.0.0.0", port=HF_PORT, workers=1)22 unmodified lines232425262728299 unmodified lines394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121135 unmodified lines1191201211221231241251261271284 unmodified lines13313413513613713813914014122 unmodified linesif "VLLM_PID" in os.environ:returnprint("🚀 Starting vLLM engine...")command =["python3", "-m", "vllm.entrypoints.openai.api_server","--model", MODEL_ID,"--host", "127.0.0.1",9 unmodified linesstart_vllm()# --- STEP 2: FASTAPI PROXY ---app = FastAPI()@app.api_route("/v1/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])async def gatekeeper_proxy(path: str, request: Request):"""Intercepts external Docling API calls and strips reasoning tags."""target_url = f"http://127.0.0.1:{VLLM_PORT}/v1/{path}"# Strip headers that cause HTTP loops or encoding crashesexcluded_headers =["host", "content-length", "content-encoding", "transfer-encoding"]headers = {k: v for k, v in request.headers.items() if k.lower() not in excluded_headers}async with httpx.AsyncClient(timeout=300.0) as client:try:# 1. Intercept standard Chat Completionsif path == "chat/completions" and request.method == "POST":body_bytes = await request.body()try:body_json = json.loads(body_bytes)is_stream = body_json.get("stream", False)except:is_stream = Falsebody_json = {}# If non-streaming (Docling), wait for response and clean itif not is_stream and body_json:resp = await client.post(target_url, headers=headers, json=body_json)if resp.status_code == 200:data = resp.json()content = data["choices"][0]["message"].get("content", "")# SUPPRESS REASONING TAGSif "</think>" in content:data["choices"][0]["message"]["content"] = content.split("</think>")[-1].strip()return JSONResponse(content=data)return JSONResponse(status_code=resp.status_code, content=resp.json())# 2. Fallback for all other endpoints (Pass-through stream)req_body = await request.body()proxy_req = client.build_request(request.method, target_url, headers=headers, content=req_body)r = await client.send(proxy_req, stream=True)resp_headers = {k: v for k, v in r.headers.items() if k.lower() not in excluded_headers}return StreamingResponse(r.aiter_raw(), status_code=r.status_code, headers=resp_headers)except Exception as e:return JSONResponse(status_code=503, content={"error": f"API Proxy Error: {str(e)}"})# --- STEP 3: GRADIO UI ---def run_ui_test(image, prompt):print("--- UI Inference Triggered ---")if image is None: return "⚠️ Please upload an image."# Health check for vLLMtry:with httpx.Client() as check:check.get(f"http://127.0.0.1:{VLLM_PORT}/v1/models", timeout=2.0)except Exception:return "⏳ Model is still loading... wait 3 mins and try again."client = OpenAI(base_url=f"http://127.0.0.1:{VLLM_PORT}/v1", api_key="EMPTY")try:image = image.convert("RGB") # Prevents 4-channel PNG crashesbuffered = BytesIO()image.save(buffered, format="JPEG")b64 = base64.b64encode(buffered.getvalue()).decode('utf-8')completion = client.chat.completions.create(model=MODEL_ID,messages=[{"role": "user", "content":[{"type": "text", "text": prompt or "Convert to markdown."},{"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b64}"}}]}],5 unmodified linesprint(f"UI Error: {e}")return f"❌ Error: {e}"with gr.Blocks(title="NuMarkdown API Server") as demo:gr.Markdown("# NuMarkdown L40S API Server")gr.Markdown("The Markdown API endpoint is live for Docling at `/v1/chat/completions`.")with gr.Row():with gr.Column():img_input = gr.Image(type="pil", label="Input Document")4 unmodified linesbtn.click(run_ui_test, inputs=[img_input, txt_input], outputs=[out])# --- STEP 4: MOUNT AND RUN ---demo.queue()app = gr.mount_gradio_app(app, demo, path="/")if __name__ == "__main__":uvicorn.run(app, host="0.0.0.0", port=HF_PORT, workers=1)
app.py+42-29