File size: 4,627 Bytes
43309f8
 
154a09c
43309f8
 
 
 
 
 
 
7fdbdaa
 
f302ce8
7fdbdaa
 
f302ce8
 
 
 
7fdbdaa
 
98cec4b
 
 
 
 
 
 
 
 
 
154a09c
43309f8
 
 
 
 
 
 
 
98cec4b
154a09c
 
 
 
 
 
 
 
 
 
98cec4b
43309f8
 
 
 
 
 
 
 
 
154a09c
 
 
 
 
 
43309f8
 
 
 
 
f302ce8
98cec4b
154a09c
 
 
 
 
 
43309f8
bae171d
 
43309f8
 
 
 
 
 
 
 
 
bae171d
9c6fca0
7fdbdaa
bae171d
9c6fca0
bae171d
9c6fca0
5a3a2fd
 
 
bae171d
5a3a2fd
43309f8
 
 
 
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
"""Serve V16 unchanged at / with queued Gradio callbacks on ZeroGPU."""
import os
import json
from pathlib import Path
import sys

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))


def gpu_duration(payload):
    if not isinstance(payload, dict):
        return 60
    length = len(str(payload.get("message", ""))) + len(str(payload.get("goal", "")))
    length += len(str(payload.get("history", "")))
    # A grounded JSON review has a larger budget than the old one-line review.
    # Reserve enough time for the plan, routing, two drafts and two reviews;
    # this is a reservation, not a measured latency or a paid resource change.
    return 60 if length <= 800 else 90


def execute_reply(engine,request):
    """An explicit backend wrapper may prepare context before the V16 stages."""
    from LABEQ_V16_Coaching_Engine import reply_v16
    arguments=(request.message,request.relation,request.goal,request.style,
        request.speaker_gender,request.recipient_gender,
        [turn.model_dump() for turn in request.history],request.generation_mode)
    configured=getattr(engine,'configured_reply',None)
    return configured(*arguments) if callable(configured) else reply_v16(engine,*arguments)


def create_app(engine, gpu_decorator, *, gpu_engine=None, max_queue_size=8):
    import gradio as gr

    from app import app
    from labeq_api import ReplyRequest

    @gpu_decorator
    def generate(payload):
        request = ReplyRequest.model_validate(payload)
        result = execute_reply(engine,request)
        if os.getenv('LABEQ_RETURN_GENERATION_TRACE')=='1':
            result['generation_trace']=getattr(engine,'generation_trace',[])
        return result

    accelerated=None
    if gpu_engine is not None:
        import spaces
        @spaces.GPU(duration=gpu_duration)
        def accelerated(payload):
            request=ReplyRequest.model_validate(payload)
            return execute_reply(gpu_engine,request)

    with gr.Blocks(title="LABEQ model API") as model_api:
        request = gr.JSON(visible=False)
        response = gr.JSON(visible=False)
        trigger = gr.Button("Generate", visible=False)
        trigger.click(
            generate, inputs=request, outputs=response, api_name="reply",
            concurrency_limit=1,
        )
        if accelerated is not None:
            gr.Button('Accelerated model API',visible=False).click(accelerated,inputs=request,outputs=response,
                api_name='reply_gpu',concurrency_limit=1)
    model_api.queue(max_size=max_queue_size, default_concurrency_limit=1)
    manifest_path=ROOT/'source-manifest.json'
    manifest=json.loads(manifest_path.read_text()) if manifest_path.exists() else {}
    app.state.gradio_model = {
        "model_loaded": engine.model is not None,
        "faisal_loaded": engine.faisal_ready,
        "generator": engine.generator,
        "adapter_revision": engine.adapter_revision,
        "base_revision": getattr(engine,"base_revision",None),
        "faisal_revision":getattr(engine,'faisal_revision',None),
        "compute_backend":getattr(engine,"compute_backend",None),
        "adapter_sha256":getattr(engine,"adapter_sha256",None),
        "environment_versions":getattr(engine,"environment_versions",None),
        "source_commit":manifest.get('source_commit'),
        "writer_policy_sha256":getattr(engine,'writer_policy_sha256',None),
        "repetition_penalty":getattr(engine,'repetition_penalty',None),
    }
    # The existing FastAPI HTML is the frontend; Gradio only supplies its queue.
    return gr.mount_gradio_app(app, model_api, path="/model", ssr_mode=False)


def main():
    # Import spaces before torch so ZeroGPU installs its CUDA emulation.
    import spaces
    import uvicorn
    from cloud.torch_engine import SpaceEngine

    os.environ["LABEQ_MODEL_MODE"] = "real"
    print("LABEQ: preparing adapter and queued callback", flush=True)
    engine = SpaceEngine()
    app = create_app(engine, spaces.GPU(duration=gpu_duration))
    print("LABEQ: loading Qwen and both adapters", flush=True)
    engine.load()
    print("LABEQ: model loaded; starting FastAPI", flush=True)
    app.state.gradio_model.update(model_loaded=True, faisal_loaded=engine.faisal_ready)
    # Gradio Spaces reserve their frontend port for the platform's Node proxy.
    # The Python application must use the assigned Gradio backend port.
    port = int(os.getenv("GRADIO_SERVER_PORT", os.getenv("PORT", "7860")))
    print(f"LABEQ: serving Python backend on {port}", flush=True)
    uvicorn.run(app, host="0.0.0.0", port=port)


if __name__ == "__main__":
    main()