File size: 4,048 Bytes
911f7e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
110
111
112
"""Gradio Space entry point. The original browser UI calls four queued model events."""
import os
from pathlib import Path
from urllib.parse import unquote

# Activate ZeroGPU before anything imports a CUDA-aware library. On a local CPU
# the UI and the rule-based practice flow work without downloading the model.
ON_ZEROGPU = os.getenv("SPACES_ZERO_GPU", "").lower() in {"true", "1", "yes"}
if ON_ZEROGPU:
    import spaces
    from backend.model_runtime import generate, MODEL_ID
else:
    generate = None
    MODEL_ID = None

import gradio as gr
from fastapi import HTTPException, Request
from fastapi.concurrency import run_in_threadpool
from fastapi.responses import FileResponse, JSONResponse
from pydantic import ValidationError

from backend.cv import MAX_CV_BYTES, read_cv
from backend.provider import InterviewProvider
from backend.schemas import AnswerRequest, CoachRequest, QuestionRequest


FRONTEND = Path(__file__).resolve().parent / "frontend"
app = gr.Server(title="NextStep Interview Practice")
provider = InterviewProvider(generate)


@app.get("/")
def home():
    return FileResponse(FRONTEND / "index.html")


async def static_asset(request: Request):
    # Only exact routes for the shipped assets are registered below.
    return FileResponse(FRONTEND / request.url.path.rsplit("/", 1)[-1])


for asset in FRONTEND.iterdir():
    if asset.is_file() and asset.suffix in {".js", ".mjs", ".css", ".svg"}:
        app.add_route("/" + asset.name, static_asset, methods=["GET"])


@app.get("/api/config")
def configuration():
    return {"aiAvailable": provider.generate is not None, "aiModel": MODEL_ID,
            "storage": "browser", "defaultMode": "ai"}


@app.post("/api/cv")
async def upload_cv(request: Request):
    if request.headers.get("content-type", "").split(";")[0].strip().lower() != "application/pdf":
        raise HTTPException(415, "只能上传 PDF 格式的简历。")
    content = bytearray()
    async for chunk in request.stream():
        if len(content) + len(chunk) > MAX_CV_BYTES:
            raise HTTPException(413, "简历不能超过 5 MB。")
        content.extend(chunk)
    filename = unquote(request.headers.get("x-filename", ""))
    result = await run_in_threadpool(read_cv, bytes(content), filename)
    return JSONResponse(result, headers={"Cache-Control": "no-store"})


def run_task(schema, task, payload, field=None):
    try:
        request = schema.model_validate(payload)
    except ValidationError:
        return {"detail": "练习内容未通过检查,请核对岗位、题数和回答长度。"}
    try:
        result = task(request)
    except ValueError as exc:
        return {"detail": str(exc)}
    return {field: result} if field else result


def questions(payload: dict) -> dict:
    return run_task(QuestionRequest, provider.questions, payload, "questions")


def follow_up(payload: dict) -> dict:
    return run_task(AnswerRequest, provider.follow_up, payload, "followUp")


def feedback(payload: dict) -> dict:
    return run_task(AnswerRequest, provider.feedback, payload)


def coach(payload: dict) -> dict:
    return run_task(CoachRequest, provider.coach, payload, "reply")


def question_duration(payload):
    count = payload.get("count", 1) if isinstance(payload, dict) else 1
    return {1: 45, 2: 62, 3: 82}.get(count, 45) if isinstance(count, int) else 45


# Bind the GPU-decorated functions themselves so the Spaces startup scan and
# Gradio's per-visitor queue see the same handlers. All four share one model.
for handler, duration in ((questions, question_duration), (follow_up, 30),
                          (feedback, 80), (coach, 35)):
    callback = spaces.GPU(duration=duration)(handler) if ON_ZEROGPU else handler
    app.api(callback, name=handler.__name__, concurrency_limit=1, concurrency_id="interview-model")


if __name__ == "__main__":
    app.launch(server_name=os.getenv("GRADIO_SERVER_NAME", "0.0.0.0"),
               server_port=int(os.getenv("GRADIO_SERVER_PORT", "7860")),
               run_history=False, footer_links=[])