Spaces:
Sleeping
Sleeping
Initial code upload
Browse files- api_server.py +96 -0
- requirements.txt +7 -0
api_server.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
from torchvision import models, transforms
|
| 5 |
+
from fastapi import FastAPI, Request
|
| 6 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 7 |
+
from PIL import Image
|
| 8 |
+
import io
|
| 9 |
+
import base64
|
| 10 |
+
import requests # هنستخدم دي عشان نكلم جوجل مباشرة
|
| 11 |
+
|
| 12 |
+
app = FastAPI()
|
| 13 |
+
|
| 14 |
+
app.add_middleware(
|
| 15 |
+
CORSMiddleware,
|
| 16 |
+
allow_origins=["*"],
|
| 17 |
+
allow_methods=["*"],
|
| 18 |
+
allow_headers=["*"],
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
# --- الموديل المحلي (DenseNet) ---
|
| 22 |
+
device = torch.device("cpu")
|
| 23 |
+
def load_medical_model():
|
| 24 |
+
model = models.densenet121(weights=None)
|
| 25 |
+
model.classifier = nn.Sequential(nn.Dropout(0.2), nn.Linear(model.classifier.in_features, 14))
|
| 26 |
+
if os.path.exists('best_densenet121.pth'):
|
| 27 |
+
try:
|
| 28 |
+
checkpoint = torch.load('best_densenet121.pth', map_location=device)
|
| 29 |
+
model.load_state_dict(checkpoint)
|
| 30 |
+
model.eval()
|
| 31 |
+
return model
|
| 32 |
+
except: return None
|
| 33 |
+
return None
|
| 34 |
+
|
| 35 |
+
medical_model = load_medical_model()
|
| 36 |
+
transform = transforms.Compose([
|
| 37 |
+
transforms.Resize((224, 224)),
|
| 38 |
+
transforms.ToTensor(),
|
| 39 |
+
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
|
| 40 |
+
])
|
| 41 |
+
class_names = ["Atelectasis", "Cardiomegaly", "Effusion", "Infiltration", "Mass", "Nodule", "Pneumonia", "Pneumothorax", "Consolidation", "Edema", "Emphysema", "Fibrosis", "Pleural_Thickening", "Hernia"]
|
| 42 |
+
|
| 43 |
+
# دالة ذكية لإرسال النص لجوجل بدون مكتبة (عشان نتفادى الـ 404)
|
| 44 |
+
def ask_gemini_direct(prompt, api_key):
|
| 45 |
+
url = f"https://generativelanguage.googleapis.com/v1/models/gemini-1.5-flash:generateContent?key={api_key}"
|
| 46 |
+
payload = {
|
| 47 |
+
"contents": [{"parts": [{"text": prompt}]}]
|
| 48 |
+
}
|
| 49 |
+
headers = {'Content-Type': 'application/json'}
|
| 50 |
+
response = requests.post(url, json=payload, headers=headers)
|
| 51 |
+
|
| 52 |
+
if response.status_code == 200:
|
| 53 |
+
return response.json()['candidates'][0]['content']['parts'][0]['text']
|
| 54 |
+
else:
|
| 55 |
+
return f"Error from Google API: {response.status_code} - {response.text}"
|
| 56 |
+
|
| 57 |
+
@app.post("/chat")
|
| 58 |
+
async def chat_endpoint(request: Request):
|
| 59 |
+
try:
|
| 60 |
+
data = await request.json()
|
| 61 |
+
api_key = os.getenv("GEMINI_API_KEY")
|
| 62 |
+
|
| 63 |
+
# التقاط الرسالة من Lovable
|
| 64 |
+
user_message = ""
|
| 65 |
+
if "messages" in data and len(data["messages"]) > 0:
|
| 66 |
+
user_message = data["messages"][-1].get("content", "")
|
| 67 |
+
elif "message" in data:
|
| 68 |
+
user_message = data["message"]
|
| 69 |
+
|
| 70 |
+
image_data = data.get("image")
|
| 71 |
+
|
| 72 |
+
# 1. لو فيه صورة
|
| 73 |
+
if image_data and medical_model:
|
| 74 |
+
encoded = image_data.split(",", 1)[1] if "," in image_data else image_data
|
| 75 |
+
image = Image.open(io.BytesIO(base64.b64decode(encoded))).convert('RGB')
|
| 76 |
+
input_tensor = transform(image).unsqueeze(0).to(device)
|
| 77 |
+
with torch.no_grad():
|
| 78 |
+
outputs = medical_model(input_tensor)
|
| 79 |
+
probs = torch.sigmoid(outputs)
|
| 80 |
+
preds = (probs > 0.5).nonzero(as_tuple=True)[1]
|
| 81 |
+
diseases = [class_names[i] for i in preds]
|
| 82 |
+
|
| 83 |
+
res_text = ", ".join(diseases) if diseases else "نتائج سليمة"
|
| 84 |
+
prompt = f"المريض رفع أشعة والتحليل الأولي: {res_text}. اشرح ده بالعربي باختصار وبأسلوب طبي."
|
| 85 |
+
ai_response = ask_gemini_direct(prompt, api_key)
|
| 86 |
+
return {"response": ai_response, "analysis": diseases}
|
| 87 |
+
|
| 88 |
+
# 2. لو نص بس (زي كلمة كحة)
|
| 89 |
+
if user_message:
|
| 90 |
+
ai_response = ask_gemini_direct(f"أنت مساعد طبي في Healytics. رد بالعربي على: {user_message}", api_key)
|
| 91 |
+
return {"response": ai_response}
|
| 92 |
+
|
| 93 |
+
return {"response": "أهلاً بك في Healytics! كيف يمكنني مساعدتك؟"}
|
| 94 |
+
|
| 95 |
+
except Exception as e:
|
| 96 |
+
return {"response": f"حدث خطأ في النظام: {str(e)}"}
|
requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi
|
| 2 |
+
uvicorn
|
| 3 |
+
requests
|
| 4 |
+
torch
|
| 5 |
+
torchvision
|
| 6 |
+
pillow
|
| 7 |
+
python-multipart
|