File size: 6,743 Bytes
9a6a96c
 
 
 
 
26d46cd
9a6a96c
06f69c2
 
 
 
9a6a96c
 
0c0e7d0
9a6a96c
 
 
3e77e48
9a6a96c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e07547d
 
9a6a96c
 
 
 
 
 
3e77e48
9a6a96c
 
3e77e48
9a6a96c
3e77e48
9a6a96c
 
 
 
 
3e77e48
 
9a6a96c
 
 
 
3e77e48
 
9a6a96c
 
3e77e48
9a6a96c
3e77e48
9a6a96c
 
61d3a1d
 
3e77e48
7a1870f
3e77e48
9a6a96c
3e77e48
9a6a96c
3e77e48
9a6a96c
 
 
e07547d
ea23496
3e77e48
9a6a96c
 
3e77e48
7a1870f
 
3e77e48
 
9a6a96c
 
 
3e77e48
9a6a96c
 
ea23496
9a6a96c
ea23496
 
9a6a96c
ea23496
7a1870f
3e77e48
9a6a96c
 
 
 
 
 
 
7a1870f
3e77e48
9a6a96c
 
 
 
1711f27
9a6a96c
3e77e48
 
 
 
 
 
 
26d46cd
ea23496
 
26d46cd
3e77e48
9a6a96c
071ade9
7a1870f
071ade9
0c0e7d0
071ade9
7a1870f
3e77e48
 
 
7a1870f
 
e07547d
7a1870f
0c0e7d0
7a1870f
 
 
 
 
 
 
 
 
 
 
 
e07547d
 
7a1870f
e07547d
 
7a1870f
e07547d
3e77e48
160f8e3
e07547d
26d46cd
7a1870f
0c0e7d0
7a1870f
06f69c2
 
0c0e7d0
06f69c2
 
 
0c0e7d0
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
import os
import logging
import re
import io
from PIL import Image
import gradio as gr

# ✅ تعطيل SSR قبل استيراد Gradio
os.environ["GRADIO_SSR_MODE"] = "False"
os.environ["GRADIO_NODE_DISABLED"] = "True"

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

logger.info("بدء تشغيل DermaScan AI...")

try:
    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

MODEL_NAME = "llama-3.1-8b-instant"
TEMPERATURE = 0.25
TOP_K = 3
EXTERNAL_API_URL = "https://omarelrayes-api.hf.space"
SESSIONS = {}
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,
            "_image_blobs": {}, "_session_image_names": [], "_turn_count": 0
        }
    return SESSIONS[thread_id]

def initialize_system():
    global agent, api_client
    try:
        logger.info("بدء تهيئة النظام...")
        groq_key = os.environ.get("GROQ_API_KEY")
        if not groq_key:
            logger.warning("GROQ_API_KEY not set")
        else:
            logger.info("GROQ_API_KEY found")
        
        api_client = DermaScanAPIClient(EXTERNAL_API_URL)
        set_api_client(api_client)
        
        if api_client.health_check():
            logger.info("External API is healthy")
        
        vectorstore = build_default_vectorstore()
        retriever = vectorstore.as_retriever(search_kwargs={"k": TOP_K}) if vectorstore else None
        
        if retriever is None:
            logger.warning("Vectorstore not available")
        
        agent = build_agent(retriever, model_name=MODEL_NAME, temperature=TEMPERATURE)
        logger.info("✅ Agent built successfully")
        logger.info("تم تهيئة النظام بنجاح!")
    except Exception as e:
        logger.error(f"فشل التهيئة: {e}", exc_info=True)
        raise

initialize_system()

def chat_with_agent(message: str, history: list) -> str:
    if agent is None:
        return "System not initialized yet."
    
    session = get_session("default")
    set_session_storage(SESSIONS)
    set_current_thread_id("default")
    
    try:
        last_analysis = session.get("last_analysis")
        analysis_ctx = f"\n\n[Analysis: {last_analysis.get('label', 'N/A')}]" if last_analysis else ""
        full_prompt = message + analysis_ctx
        config = {"configurable": {"thread_id": "default"}, "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."
    except Exception as e:
        logger.error(f"Chat error: {e}")
        return f"Error: {str(e)}"

def analyze_image(image, thread_id: str = "default") -> str:
    if api_client is None:
        return "API client not initialized"
    
    try:
        api_client.set_role(thread_id, "patient")
        session = get_session(thread_id)
        session["current_image"] = image
        
        result = api_client.upload_and_analyze_image(image, thread_id)
        if not result.get('ok'):
            return f"Error: {result.get('error', 'Unknown error')}"
        
        session["last_analysis"] = {
            "label": result.get("label"),
            "confidence_pct": result.get("confidence_pct"),
            "infection_pct": result.get("infection_pct")
        }
        
        return (
            f"تم التحليل بنجاح!\n\n"
            f"التصنيف: {result.get('label')}\n"
            f"نسبة الثقة: {result.get('confidence_pct')}%\n"
            f"المساحة المصابة: {result.get('infection_pct')}%"
        )
    except Exception as e:
        logger.error(f"Image analysis error: {e}")
        return f"Error: {str(e)}"

logger.info("جاري بناء واجهة Gradio...")

with gr.Blocks(title="DermaScan AI") as demo:
    gr.Markdown("# 🏥 DermaScan AI - مساعد أمراض الجلدية")
    
    with gr.Tab("📤 رفع الصورة"):
        image_input = gr.Image(type="pil", label="ارفع صورة الجلد")
        analyze_btn = gr.Button("🔍 تحليل الصورة", variant="primary")
        analysis_output = gr.Textbox(label="نتيجة التحليل", lines=6)
        analyze_btn.click(fn=analyze_image, inputs=[image_input], outputs=[analysis_output])
    
    with gr.Tab("💬 الدردشة"):
        chatbot = gr.Chatbot(label="المحادثة", height=400)
        msg_input = gr.Textbox(label="رسالتك", placeholder="اسأل عن حالتك الجلدية...", lines=2)
        send_btn = gr.Button("🚀 إرسال", variant="primary")
        clear_btn = gr.Button("🗑️ مسح")
        
        def user_message(user_msg, history):
            return "", history + [[user_msg, None]]
        
        def bot_response(history):
            if not history:
                return history
            user_msg = history[-1][0]
            response = chat_with_agent(user_msg, history[:-1])
            history[-1][1] = response
            return history
        
        send_btn.click(user_message, [msg_input, chatbot], [msg_input, chatbot]).then(
            bot_response, chatbot, chatbot
        )
        msg_input.submit(user_message, [msg_input, chatbot], [msg_input, chatbot]).then(
            bot_response, chatbot, chatbot
        )
        clear_btn.click(lambda: None, None, chatbot)
    
    with gr.Tab("📚 API Info"):
        gr.Markdown("## API شغالة! استخدم Gradio Client للاتصال.")

logger.info("✅ تم بناء واجهة Gradio")
logger.info("🎉 DermaScan AI جاهز!")

# ✅ الحل الحقيقي: ssr_mode=False في launch()
demo.launch(
    server_name="0.0.0.0",
    server_port=7860,
    ssr_mode=False,  # ← ده اللي هيمنع Node.js SSR
    share=False
)