-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
287 lines (234 loc) · 9.17 KB
/
Copy pathapp.py
File metadata and controls
287 lines (234 loc) · 9.17 KB
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
import os
import threading
import time
import uuid
from pathlib import Path
from typing import Optional
import uvicorn
from chainlit.utils import mount_chainlit
from fastapi import Cookie, FastAPI, File, Form, HTTPException, Response, UploadFile
from fastapi.responses import JSONResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
from werkzeug.utils import secure_filename
from agents.agent_decision_multi_agent import process_query, resume_review
from config import Config
config = Config()
os.environ.setdefault("CHAINLIT_AUTH_SECRET", config.auth.auth_secret)
app = FastAPI(title="SkinVL Dermoscopy Assistant Demo", version="1.0")
UPLOAD_FOLDER = Path("uploads/backend")
UPLOAD_FOLDER.mkdir(parents=True, exist_ok=True)
app.mount(
"/uploads/backend",
StaticFiles(directory=UPLOAD_FOLDER),
name="dermoscopy_uploads",
)
ALLOWED_EXTENSIONS = {"png", "jpg", "jpeg"}
class QueryRequest(BaseModel):
query: str
def allowed_file(filename: str) -> bool:
return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS
def _has_valid_image_signature(filename: str, content: bytes) -> bool:
extension = filename.rsplit(".", 1)[-1].lower()
if extension == "png":
return content.startswith(b"\x89PNG\r\n\x1a\n")
return content.startswith(b"\xff\xd8\xff")
async def _read_upload_with_limit(image: UploadFile, limit_bytes: int) -> bytes:
return await image.read(limit_bytes + 1)
def _default_backend_metadata() -> dict:
demo_mode = bool(config.medical_cv.demo_mode)
return {
"mode": "demo" if demo_mode else "runtime",
"scenario": config.medical_cv.demo_scenario,
"image_router": "mock_image_router" if demo_mode else "image_router",
"skinvl": "mock_skinvl" if demo_mode else "transformers_skinvl",
"rag": "demo_rag" if demo_mode else "qdrant_rag",
"web_search": "enabled" if config.web_search.enabled else "disabled",
"simulated_stages": ["image_routing", "skinvl", "rag"]
if demo_mode
else [],
}
def cleanup_expired_uploads(now: Optional[float] = None) -> int:
"""Delete backend uploads only after the configured review retention window."""
cutoff = (now if now is not None else time.time()) - (
config.api.upload_retention_minutes * 60
)
deleted = 0
for file_path in UPLOAD_FOLDER.iterdir():
try:
if file_path.is_file() and file_path.stat().st_mtime < cutoff:
file_path.unlink()
deleted += 1
except OSError as exc: # pragma: no cover - cleanup best effort
print(f"Failed to remove expired upload {file_path}: {exc}")
return deleted
def cleanup_old_uploads() -> None:
"""Periodically expire uploads while preserving files needed by HITL review."""
interval_seconds = min(
300,
max(60, config.api.upload_retention_minutes * 30),
)
while True:
try:
cleanup_expired_uploads()
except Exception as exc: # pragma: no cover - background maintenance
print(f"Error during upload cleanup: {exc}")
time.sleep(interval_seconds)
upload_cleanup_thread = threading.Thread(target=cleanup_old_uploads, daemon=True)
upload_cleanup_thread.start()
def _build_http_result(result: dict, session_id: str) -> dict:
payload = {
"status": result["status"],
"response": result["response"],
"agent_outputs": result.get("agent_outputs", []),
"confidence": result.get("confidence", 1.0),
"needs_validation": result.get("needs_validation", False),
"review_payload": result.get("review_payload"),
"attachments": result.get("attachments", []),
"session_id": session_id,
"simulation": result.get("simulation", config.medical_cv.demo_mode),
"backend_metadata": result.get(
"backend_metadata", _default_backend_metadata()
),
"image_routing": result.get("image_routing"),
"image_findings": result.get("image_findings"),
"retrieval_bundle": result.get("retrieval_bundle"),
"sources": result.get("sources", []),
"review_state": result.get("review_state"),
}
image_attachments = [
attachment
for attachment in result.get("attachments", [])
if attachment.get("type") == "image" and attachment.get("url")
]
if image_attachments:
payload["result_image"] = image_attachments[0]["url"]
return payload
@app.get("/")
async def index():
return RedirectResponse(url=f"{config.ui.chainlit_path}/")
@app.get("/health")
def health_check():
return {
"status": "healthy",
"service": "SkinVL Dermoscopy Assistant Demo",
"simulation": bool(config.medical_cv.demo_mode),
"demo_mode": bool(config.medical_cv.demo_mode),
"demo_scenario": config.medical_cv.demo_scenario,
"web_search_enabled": bool(config.web_search.enabled),
"backend_metadata": _default_backend_metadata(),
"upload_retention_minutes": config.api.upload_retention_minutes,
}
@app.post("/chat")
def chat(
request: QueryRequest,
response: Response,
session_id: Optional[str] = Cookie(None),
):
thread_id = session_id or str(uuid.uuid4())
response.set_cookie(key="session_id", value=thread_id)
try:
result = process_query(request.query, thread_id=thread_id)
return _build_http_result(result, thread_id)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
except Exception as exc:
raise HTTPException(
status_code=500,
detail="SkinVL demo could not complete the request.",
) from exc
@app.post("/upload")
async def upload_image(
response: Response,
image: UploadFile = File(...),
text: str = Form(""),
session_id: Optional[str] = Cookie(None),
):
if not image.filename or not allowed_file(image.filename):
return JSONResponse(
status_code=400,
content={
"status": "error",
"response": "Unsupported file type. Allowed formats: PNG, JPG, JPEG",
},
)
limit_bytes = config.api.max_image_upload_size * 1024 * 1024
file_content = await _read_upload_with_limit(image, limit_bytes)
if len(file_content) > limit_bytes:
return JSONResponse(
status_code=413,
content={
"status": "error",
"response": (
f"File too large. Maximum size allowed: {config.api.max_image_upload_size}MB"
),
},
)
if not _has_valid_image_signature(image.filename, file_content):
return JSONResponse(
status_code=400,
content={
"status": "error",
"response": "The uploaded file content is not a valid PNG or JPEG image.",
},
)
thread_id = session_id or str(uuid.uuid4())
response.set_cookie(key="session_id", value=thread_id)
filename = secure_filename(f"{uuid.uuid4()}_{image.filename}")
file_path = UPLOAD_FOLDER / filename
file_path.write_bytes(file_content)
try:
result = process_query({"text": text, "image": str(file_path)}, thread_id=thread_id)
return _build_http_result(result, thread_id)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
except Exception as exc:
raise HTTPException(
status_code=500,
detail="SkinVL demo could not process the uploaded image.",
) from exc
@app.post("/validate")
def validate_medical_output(
response: Response,
validation_result: str = Form(...),
comments: Optional[str] = Form(None),
edited_response: Optional[str] = Form(None),
session_id: Optional[str] = Cookie(None),
):
thread_id = session_id or str(uuid.uuid4())
response.set_cookie(key="session_id", value=thread_id)
decision_type = validation_result.strip().lower()
if decision_type == "yes":
decision_type = "approve"
elif decision_type == "no":
decision_type = "reject"
decision = {"type": decision_type}
if comments:
decision["comment"] = comments
if edited_response:
decision["edited_response"] = edited_response
try:
result = resume_review(thread_id=thread_id, decision=decision)
return _build_http_result(result, thread_id)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
except Exception as exc:
raise HTTPException(
status_code=500,
detail="The review could not be resumed. The draft remains unapproved.",
) from exc
@app.exception_handler(413)
async def request_entity_too_large(_, exc):
del exc
return JSONResponse(
status_code=413,
content={
"status": "error",
"response": (
f"File too large. Maximum size allowed: {config.api.max_image_upload_size}MB"
),
},
)
mount_chainlit(app=app, target="chainlit_app.py", path=config.ui.chainlit_path)
if __name__ == "__main__":
uvicorn.run(app, host=config.api.host, port=config.api.port)