Update app.py
Browse files
app.py
CHANGED
|
@@ -2,100 +2,75 @@ import gradio as gr
|
|
| 2 |
import torch
|
| 3 |
import json
|
| 4 |
import torch.nn.functional as F
|
| 5 |
-
from huggingface_hub import hf_hub_download
|
| 6 |
-
from model import MedicalMasterAI
|
| 7 |
|
| 8 |
-
# تحديد الجهاز
|
| 9 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 10 |
|
| 11 |
-
# 1. تحميل التوكنايزر المخصص الخاص بك
|
| 12 |
-
# نفترض أن هذا الملف موجود محلياً في المساحة
|
| 13 |
with open("tokenizer_config.json", "r", encoding="utf-8") as f:
|
| 14 |
vocab = json.load(f)
|
| 15 |
|
| 16 |
stoi = vocab["stoi"]
|
| 17 |
itos = vocab["itos"]
|
| 18 |
|
| 19 |
-
# دوال التشفير وفك التشفير
|
| 20 |
def encode(text):
|
| 21 |
return [stoi.get(c, 0) for c in text]
|
| 22 |
|
| 23 |
def decode(ids):
|
| 24 |
return "".join([itos.get(str(i), "") for i in ids])
|
| 25 |
|
| 26 |
-
# 2. بناء وتحميل النموذج
|
| 27 |
try:
|
| 28 |
-
# تهيئة النموذج بنفس الأبعاد الموجودة في كودك
|
| 29 |
model = MedicalMasterAI(vocab_size=115, n_layer=48, n_head=8, n_embd=768)
|
| 30 |
|
| 31 |
-
print("جاري سحب ملف الأوزان من المستودع...
|
| 32 |
-
# سحب الملف الضخم من مستودعك مباشرة
|
| 33 |
-
# تأكد أن "gijl/Medical-Master-1.5B" هو المسار الصحيح لمستودعك
|
| 34 |
model_path = hf_hub_download(repo_id="gijl/Medical-Master-1.5B", filename="pytorch_model.bin")
|
| 35 |
print("تم التحميل بنجاح. جاري قراءة الأوزان...")
|
| 36 |
|
| 37 |
-
# تحميل الأوزان باستخدام المسار الذي أرجعته دالة التحميل
|
| 38 |
state_dict = torch.load(model_path, map_location=device, weights_only=True)
|
| 39 |
-
|
|
|
|
|
|
|
| 40 |
|
| 41 |
model.to(device)
|
| 42 |
-
model.eval()
|
| 43 |
model_loaded = True
|
| 44 |
print("النموذج جاهز للعمل!")
|
| 45 |
except Exception as e:
|
| 46 |
print(f"Error loading model: {e}")
|
| 47 |
model_loaded = False
|
| 48 |
|
| 49 |
-
# 3. دالة المحادثة (التوليد التلقائي)
|
| 50 |
def medical_chat(message, history):
|
| 51 |
if not model_loaded:
|
| 52 |
-
return "حدث خطأ أثناء تحميل أوزان النموذج. يرجى مراجعة سجلات
|
| 53 |
|
| 54 |
prompt = f"Question: {message} Answer:"
|
| 55 |
-
|
| 56 |
-
# تحويل النص إلى أرقام (Tensors)
|
| 57 |
idx = torch.tensor([encode(prompt)], dtype=torch.long).to(device)
|
| 58 |
|
| 59 |
-
# عدد الأحرف التي سيولدها النموذج
|
| 60 |
max_new_chars = 200
|
| 61 |
-
|
| 62 |
generated_ids = []
|
| 63 |
|
| 64 |
with torch.no_grad():
|
| 65 |
for _ in range(max_new_chars):
|
| 66 |
-
#
|
| 67 |
-
idx_cond = idx[:, -
|
| 68 |
|
| 69 |
-
# تمرير البيانات للنموذج
|
| 70 |
logits = model(idx_cond)
|
| 71 |
-
|
| 72 |
-
# التركيز على الحرف الأخير فقط
|
| 73 |
logits = logits[:, -1, :]
|
| 74 |
-
|
| 75 |
-
# تطبيق الحرارة (Temperature)
|
| 76 |
temperature = 0.8
|
| 77 |
logits = logits / temperature
|
| 78 |
-
|
| 79 |
-
# تحويل القيم إلى احتمالات
|
| 80 |
probs = F.softmax(logits, dim=-1)
|
| 81 |
-
|
| 82 |
-
# اختيار الحرف التالي
|
| 83 |
idx_next = torch.multinomial(probs, num_samples=1)
|
| 84 |
|
| 85 |
-
# إضافة الحرف الجديد للسياق
|
| 86 |
idx = torch.cat((idx, idx_next), dim=1)
|
| 87 |
generated_ids.append(idx_next.item())
|
| 88 |
|
| 89 |
-
# فك تشفير الأحرف المولدة فقط
|
| 90 |
answer = decode(generated_ids)
|
| 91 |
-
|
| 92 |
return answer
|
| 93 |
|
| 94 |
-
# 4. بناء واجهة Gradio
|
| 95 |
demo = gr.ChatInterface(
|
| 96 |
fn=medical_chat,
|
| 97 |
title="Medical Master (Custom PyTorch AI)",
|
| 98 |
-
description="نموذج مبني من الصفر
|
| 99 |
)
|
| 100 |
|
| 101 |
if __name__ == "__main__":
|
|
|
|
| 2 |
import torch
|
| 3 |
import json
|
| 4 |
import torch.nn.functional as F
|
| 5 |
+
from huggingface_hub import hf_hub_download
|
| 6 |
+
from model import MedicalMasterAI
|
| 7 |
|
|
|
|
| 8 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 9 |
|
|
|
|
|
|
|
| 10 |
with open("tokenizer_config.json", "r", encoding="utf-8") as f:
|
| 11 |
vocab = json.load(f)
|
| 12 |
|
| 13 |
stoi = vocab["stoi"]
|
| 14 |
itos = vocab["itos"]
|
| 15 |
|
|
|
|
| 16 |
def encode(text):
|
| 17 |
return [stoi.get(c, 0) for c in text]
|
| 18 |
|
| 19 |
def decode(ids):
|
| 20 |
return "".join([itos.get(str(i), "") for i in ids])
|
| 21 |
|
|
|
|
| 22 |
try:
|
|
|
|
| 23 |
model = MedicalMasterAI(vocab_size=115, n_layer=48, n_head=8, n_embd=768)
|
| 24 |
|
| 25 |
+
print("جاري سحب ملف الأوزان من المستودع...")
|
|
|
|
|
|
|
| 26 |
model_path = hf_hub_download(repo_id="gijl/Medical-Master-1.5B", filename="pytorch_model.bin")
|
| 27 |
print("تم التحميل بنجاح. جاري قراءة الأوزان...")
|
| 28 |
|
|
|
|
| 29 |
state_dict = torch.load(model_path, map_location=device, weights_only=True)
|
| 30 |
+
|
| 31 |
+
# إضافة strict=False لتجاهل طبقات الصور (image_projection) بأمان
|
| 32 |
+
model.load_state_dict(state_dict, strict=False)
|
| 33 |
|
| 34 |
model.to(device)
|
| 35 |
+
model.eval()
|
| 36 |
model_loaded = True
|
| 37 |
print("النموذج جاهز للعمل!")
|
| 38 |
except Exception as e:
|
| 39 |
print(f"Error loading model: {e}")
|
| 40 |
model_loaded = False
|
| 41 |
|
|
|
|
| 42 |
def medical_chat(message, history):
|
| 43 |
if not model_loaded:
|
| 44 |
+
return "حدث خطأ أثناء تحميل أوزان النموذج. يرجى مراجعة السجلات."
|
| 45 |
|
| 46 |
prompt = f"Question: {message} Answer:"
|
|
|
|
|
|
|
| 47 |
idx = torch.tensor([encode(prompt)], dtype=torch.long).to(device)
|
| 48 |
|
|
|
|
| 49 |
max_new_chars = 200
|
|
|
|
| 50 |
generated_ids = []
|
| 51 |
|
| 52 |
with torch.no_grad():
|
| 53 |
for _ in range(max_new_chars):
|
| 54 |
+
# تغيير 1024 إلى 256 ليتطابق مع حجم أوزان التدريب
|
| 55 |
+
idx_cond = idx[:, -256:]
|
| 56 |
|
|
|
|
| 57 |
logits = model(idx_cond)
|
|
|
|
|
|
|
| 58 |
logits = logits[:, -1, :]
|
|
|
|
|
|
|
| 59 |
temperature = 0.8
|
| 60 |
logits = logits / temperature
|
|
|
|
|
|
|
| 61 |
probs = F.softmax(logits, dim=-1)
|
|
|
|
|
|
|
| 62 |
idx_next = torch.multinomial(probs, num_samples=1)
|
| 63 |
|
|
|
|
| 64 |
idx = torch.cat((idx, idx_next), dim=1)
|
| 65 |
generated_ids.append(idx_next.item())
|
| 66 |
|
|
|
|
| 67 |
answer = decode(generated_ids)
|
|
|
|
| 68 |
return answer
|
| 69 |
|
|
|
|
| 70 |
demo = gr.ChatInterface(
|
| 71 |
fn=medical_chat,
|
| 72 |
title="Medical Master (Custom PyTorch AI)",
|
| 73 |
+
description="نموذج مبني من الصفر للإجابة على الاستفسارات (يعمل بالوضع النصي حالياً).",
|
| 74 |
)
|
| 75 |
|
| 76 |
if __name__ == "__main__":
|