File size: 2,635 Bytes
b66d045 6382a0d 5201445 b66d045 5201445 4ce8159 5201445 6382a0d 024a042 5201445 6382a0d 5201445 6382a0d 5201445 f5c5361 6382a0d 5201445 6382a0d 5201445 6382a0d b66d045 5201445 b66d045 6382a0d 5201445 f5c5361 5201445 6382a0d f5c5361 6382a0d 5201445 6382a0d 5201445 f5c5361 5201445 6382a0d 5201445 f5c5361 5201445 f5c5361 b66d045 5201445 b66d045 5201445 b66d045 | 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 | import gradio as gr
import torch
import json
from transformers import AutoModelForCausalLM
device = torch.device("cpu")
# 1. تحميل التوكنايزر المخصص الخاص بك (بدون تعديل الملف)
with open("tokenizer_config.json", "r", encoding="utf-8") as f:
vocab = json.load(f)
stoi = vocab["stoi"]
itos = vocab["itos"]
def encode(text): return [stoi.get(c, 0) for c in text]
def decode(ids): return "".join([itos.get(str(i), "") for i in ids])
# 2. تحميل النموذج باستخدام مكتبة Transformers مباشرة
try:
print("جاري تحميل النموذج من Hugging Face...")
# هذا السطر سيقرأ config.json و pytorch_model.bin بشكل صحيح ومطابق 100%
model = AutoModelForCausalLM.from_pretrained(
"gijl/Medical-Master-1.5B",
torch_dtype=torch.float32,
low_cpu_mem_usage=True
)
model.to(device)
model.eval()
model_loaded = True
print("تم التحميل بنجاح وتم مطابقة الأوزان!")
except Exception as e:
print(f"Error: {e}")
model_loaded = False
# 3. دالة المحادثة (Streaming)
def medical_chat(message, history):
if not model_loaded:
yield "حدث خطأ في تحميل النموذج."
return
prompt = f"Question: {message} Answer:"
input_ids = torch.tensor([encode(prompt)], dtype=torch.long).to(device)
generated_text = ""
with torch.no_grad():
for _ in range(150): # توليد 150 حرف
# الحد الأقصى للسياق هو 256 كما هو في config.json
idx_cond = input_ids[:, -256:]
# تمرير البيانات لنموذج HF
outputs = model(input_ids=idx_cond)
logits = outputs.logits[:, -1, :] / 0.7 # حرارة 0.7 لتقليل العشوائية
probs = torch.nn.functional.softmax(logits, dim=-1)
idx_next = torch.multinomial(probs, num_samples=1)
input_ids = torch.cat((input_ids, idx_next), dim=1)
char = decode([idx_next.item()])
generated_text += char
yield generated_text
# التوقف إذا وصل لنقطة
if idx_next.item() == stoi.get(".", -1):
break
# 4. بناء الواجهة
demo = gr.ChatInterface(
fn=medical_chat,
title="Medical Master 1.5B",
description="مساعد طبي ذكي يعمل بحروف اللغة العربية والإنجليزية.",
)
if __name__ == "__main__":
demo.launch() |