Spaces:
Runtime error
Runtime error
File size: 14,505 Bytes
80c4f3a 67c352a 80c4f3a b262682 67c352a 80c4f3a 67c352a 80c4f3a 67c352a b262682 67c352a b262682 80c4f3a 67c352a b262682 67c352a b262682 67c352a b262682 67c352a b262682 80c4f3a 67c352a 80c4f3a 67c352a 80c4f3a 67c352a 80c4f3a 67c352a 80c4f3a 67c352a 80c4f3a b262682 67c352a b262682 67c352a b262682 67c352a b262682 67c352a b262682 67c352a b262682 67c352a b262682 67c352a b262682 67c352a b262682 67c352a b262682 80c4f3a 67c352a 80c4f3a 43dfaa2 80c4f3a 67c352a 80c4f3a 67c352a 80c4f3a 67c352a 80c4f3a 67c352a 80c4f3a 67c352a 80c4f3a 67c352a 80c4f3a 67c352a 43dfaa2 80c4f3a 43dfaa2 67c352a 80c4f3a 43dfaa2 80c4f3a 67c352a 80c4f3a 67c352a 80c4f3a 67c352a 80c4f3a 67c352a d4f0116 67c352a f336f6c 67c352a | 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 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 | import os
import io
import base64
import time
import logging
import re
import sys
from pathlib import Path
from PIL import Image
import gradio as gr
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from contextlib import asynccontextmanager
# إعداد Logging شامل
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(sys.stdout)
]
)
logger = logging.getLogger(__name__)
logger.info("🚀 بدء تشغيل DermaScan AI...")
try:
logger.info("📦 جاري استيراد الوحدات...")
from rag import build_default_vectorstore
from agent import (
build_agent,
set_session_storage,
set_current_thread_id,
set_api_client,
)
from api_client import DermaScanAPIClient
logger.info("✅ تم استيراد جميع الوحدات بنجاح")
except Exception as e:
logger.error(f"❌ فشل استيراد الوحدات: {e}", exc_info=True)
raise
# Configuration
MODEL_NAME = "llama-3.1-8b-instant"
FALLBACK_MODEL_NAME = "llama-3.3-70b-versatile"
TEMPERATURE = 0.25
TOP_K = 3
EXTERNAL_API_URL = "https://omarelrayes-api.hf.space"
# Global variables
SESSIONS = {}
agent = None
fallback_agent = None
api_client = None
def get_session(thread_id: str) -> dict:
if thread_id not in SESSIONS:
SESSIONS[thread_id] = {
"role": "patient",
"last_analysis": None,
"current_image": None,
"matched_patient_id": None,
"matched_patient_report": None,
"_image_blobs": {},
"_session_image_names": [],
"_turn_count": 0,
"_summary": "",
}
return SESSIONS[thread_id]
def initialize_system():
"""Initialize agent and API client"""
global agent, fallback_agent, api_client
try:
logger.info("🔧 بدء تهيئة النظام...")
# Check Groq API Key
groq_key = os.environ.get("GROQ_API_KEY")
if not groq_key:
logger.warning("⚠️ GROQ_API_KEY not set in environment")
else:
logger.info("✅ GROQ_API_KEY found")
# Initialize API client
logger.info("🌐 جاري تهيئة API Client...")
api_client = DermaScanAPIClient(EXTERNAL_API_URL)
set_api_client(api_client)
# Check external API health
try:
if api_client.health_check():
logger.info("✅ External API is healthy")
else:
logger.warning("⚠️ External API not reachable")
except Exception as e:
logger.error(f"❌ External API health check failed: {e}")
# Build vectorstore and agent
logger.info("🗄️ جاري بناء Vectorstore...")
try:
vectorstore = build_default_vectorstore()
if vectorstore:
logger.info("✅ Vectorstore loaded successfully")
retriever = vectorstore.as_retriever(search_kwargs={"k": TOP_K})
else:
logger.warning("⚠️ Vectorstore not available")
retriever = None
except Exception as e:
logger.error(f"❌ Failed to build vectorstore: {e}", exc_info=True)
retriever = None
# Build agents
logger.info("🤖 جاري بناء Agent...")
try:
agent = build_agent(retriever, model_name=MODEL_NAME, temperature=TEMPERATURE)
logger.info("✅ Primary agent built successfully")
except Exception as e:
logger.error(f"❌ Failed to build primary agent: {e}", exc_info=True)
agent = None
try:
fallback_agent = build_agent(retriever, model_name=FALLBACK_MODEL_NAME, temperature=TEMPERATURE)
logger.info("✅ Fallback agent built successfully")
except Exception as e:
logger.error(f"❌ Failed to build fallback agent: {e}", exc_info=True)
fallback_agent = None
logger.info("🎉 تم تهيئة النظام بنجاح!")
except Exception as e:
logger.error(f"❌ فشل تهيئة النظام: {e}", exc_info=True)
raise
# FastAPI app with lifespan
@asynccontextmanager
async def lifespan(app: FastAPI):
logger.info("🚀 FastAPI startup...")
initialize_system()
yield
logger.info("🛑 FastAPI shutdown...")
app = FastAPI(title="DermaScan AI - RAG System", lifespan=lifespan)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
# Pydantic models
class ChatRequest(BaseModel):
thread_id: str
message: str
class BookingRequest(BaseModel):
thread_id: str
city: str = ""
# FastAPI endpoints
@app.get("/health")
def health():
return {
"agent_ready": agent is not None,
"api_client_ready": api_client is not None,
"external_api_healthy": api_client.health_check() if api_client else False,
}
@app.post("/chat")
def chat(req: ChatRequest):
"""Chat endpoint"""
global agent
if agent is None:
return {"ok": False, "error": "Agent not initialized yet"}
session = get_session(req.thread_id)
set_session_storage(SESSIONS)
set_current_thread_id(req.thread_id)
try:
last_analysis = session.get("last_analysis")
analysis_ctx = ""
if last_analysis:
analysis_ctx = (
f"\n\n[CURRENT IMAGE ANALYSIS — Classification: {last_analysis.get('label', 'N/A')}, "
f"Confidence: {last_analysis.get('confidence_pct', 0):.1f}%, "
f"Affected Area: {last_analysis.get('infection_pct', 0):.1f}%]"
)
full_prompt = req.message + analysis_ctx
config = {"configurable": {"thread_id": req.thread_id}, "recursion_limit": 14}
final_text = ""
tool_calls = []
for event in agent.stream(
{"messages": [("user", full_prompt)]},
config=config,
stream_mode="values"
):
last_msg = event["messages"][-1]
if hasattr(last_msg, "tool_calls") and last_msg.tool_calls:
for tc in last_msg.tool_calls:
tool_calls.append({"name": tc["name"], "args": tc["args"]})
if last_msg.type == "ai" and last_msg.content:
final_text = last_msg.content
cleaned_text = re.sub(r'\[ANALYSIS_RESULT:\{.*?\}\]', '', final_text).strip()
session["_turn_count"] = session.get("_turn_count", 0) + 1
return {
"ok": True,
"reply": cleaned_text,
"tool_calls": tool_calls,
}
except Exception as e:
logger.error(f"Chat error: {e}", exc_info=True)
return {"ok": False, "error": str(e)}
@app.post("/book-appointment")
def book_appointment(req: BookingRequest):
"""Book appointment via external API"""
if api_client is None:
return {"ok": False, "error": "API client not initialized"}
result = api_client.book_appointment(req.thread_id, req.city)
return result
@app.get("/image")
def get_image(name: str = "", thread_id: str = ""):
"""Get image from session"""
try:
session = get_session(thread_id) if thread_id else {}
blobs = session.get("_image_blobs", {})
if name not in blobs:
return {"ok": False, "error": "Image not found"}
return {"ok": True, "base64": blobs[name], "media_type": "image/png"}
except Exception as e:
return {"ok": False, "error": str(e)}
# Gradio Functions
def gradio_chat(message: str, history: list, thread_id: str = "default") -> str:
"""Gradio chat function"""
if agent is None:
return "System is not initialized yet. Please wait..."
session = get_session(thread_id)
set_session_storage(SESSIONS)
set_current_thread_id(thread_id)
try:
last_analysis = session.get("last_analysis")
analysis_ctx = ""
if last_analysis:
analysis_ctx = (
f"\n\n[CURRENT IMAGE ANALYSIS — Classification: {last_analysis.get('label', 'N/A')}, "
f"Confidence: {last_analysis.get('confidence_pct', 0):.1f}%, "
f"Affected Area: {last_analysis.get('infection_pct', 0):.1f}%]"
)
full_prompt = message + analysis_ctx
config = {"configurable": {"thread_id": thread_id}, "recursion_limit": 14}
final_text = ""
for event in agent.stream(
{"messages": [("user", full_prompt)]},
config=config,
stream_mode="values"
):
last_msg = event["messages"][-1]
if last_msg.type == "ai" and last_msg.content:
final_text = last_msg.content
cleaned_text = re.sub(r'\[ANALYSIS_RESULT:\{.*?\}\]', '', final_text).strip()
session["_turn_count"] = session.get("_turn_count", 0) + 1
return cleaned_text if cleaned_text else "No response generated."
except Exception as e:
logger.error(f"Gradio chat error: {e}", exc_info=True)
return f"Error: {str(e)}"
def gradio_upload_image(image: Image.Image, thread_id: str = "default") -> tuple:
"""Handle image upload"""
if api_client is None:
return "API client not initialized", None, None, None
try:
result = api_client.upload_and_analyze_image(image, thread_id)
if 'error' in result:
return f"Error: {result['error']}", None, None, None
session = get_session(thread_id)
session["last_analysis"] = {
"label": result.get("label"),
"confidence_pct": result.get("confidence_pct"),
"infection_pct": result.get("infection_pct"),
}
if 'images' in result:
session["_image_blobs"].update(result['images'])
analysis_text = f"""
✅ **تم تحليل الصورة بنجاح!**
**النتائج:**
- التصنيف: {result.get('label')}
- نسبة الثقة: {result.get('confidence_pct')}%
- المساحة المصابة: {result.get('infection_pct')}%
يمكنك الآن طرح أسئلة عن هذه الصورة.
"""
orig_b64 = result.get('images', {}).get('original', '')
mask_b64 = result.get('images', {}).get('mask', '')
overlay_b64 = result.get('images', {}).get('overlay', '')
orig_img = Image.open(io.BytesIO(base64.b64decode(orig_b64))) if orig_b64 else None
mask_img = Image.open(io.BytesIO(base64.b64decode(mask_b64))) if mask_b64 else None
overlay_img = Image.open(io.BytesIO(base64.b64decode(overlay_b64))) if overlay_b64 else None
return analysis_text, orig_img, mask_img, overlay_img
except Exception as e:
logger.error(f"Upload error: {e}", exc_info=True)
return f"Error: {str(e)}", None, None, None
# Build Gradio UI - ✅ الحل: ssr_mode=False لتعطيل Node.js
logger.info("🎨 جاري بناء واجهة Gradio...")
try:
with gr.Blocks(title="DermaScan AI - Patient Portal", ssr_mode=False) as demo:
gr.Markdown("""
# 🏥 DermaScan AI - مساعد أمراض الجلدية
ارفع صورة الجلد واحصل على تحليل بالذكاء الاصطناعي + اسأل أي أسئلة.
""")
thread_id_state = gr.State(value="default")
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### 📤 رفع الصورة")
image_input = gr.Image(type="pil", label="ارفع صورة الجلد")
upload_btn = gr.Button("📎 ارفع وحلّل", variant="primary")
analysis_output = gr.Markdown(label="نتيجة التحليل")
with gr.Column(scale=2):
gr.Markdown("### 💬 الدردشة مع DermaScan AI")
chatbot = gr.Chatbot(label="المحادثة", height=400)
msg_input = gr.Textbox(
label="رسالتك",
placeholder="اسأل عن حالتك الجلدية...",
lines=2
)
send_btn = gr.Button("🚀 إرسال", variant="primary")
with gr.Row():
with gr.Column():
gr.Markdown("### 🖼️ الصور المحللة")
orig_display = gr.Image(label="الصورة الأصلية", type="pil")
with gr.Column():
mask_display = gr.Image(label="قناع التجزئة", type="pil")
with gr.Column():
overlay_display = gr.Image(label="الصورة مع التغطية", type="pil")
def user_message(user_msg, history):
return "", history + [[user_msg, None]]
def bot_response(history, thread_id):
if not history:
return history
user_msg = history[-1][0]
response = gradio_chat(user_msg, history[:-1], thread_id)
history[-1][1] = response
return history
upload_btn.click(
fn=gradio_upload_image,
inputs=[image_input, thread_id_state],
outputs=[analysis_output, orig_display, mask_display, overlay_display]
)
send_btn.click(
fn=user_message,
inputs=[msg_input, chatbot],
outputs=[msg_input, chatbot]
).then(
fn=bot_response,
inputs=[chatbot, thread_id_state],
outputs=[chatbot]
)
logger.info("✅ تم بناء واجهة Gradio بنجاح")
except Exception as e:
logger.error(f"❌ فشل بناء واجهة Gradio: {e}", exc_info=True)
raise
logger.info("🎉 التطبيق جاهز للتشغيل!")
# ✅ Mount Gradio to FastAPI
app = gr.mount_gradio_app(app, demo, path="/")
logger.info("✅ تم ربط Gradio بـ FastAPI")
# ✅ تشغيل التطبيق - HF Spaces بيشغل تلقائياً
# لا حاجة لـ demo.launch() أو uvicorn.run() |