File size: 2,896 Bytes
135eb38 fd806cc 135eb38 fd806cc 135eb38 fd806cc 135eb38 fd806cc 135eb38 fd806cc 135eb38 fd806cc 135eb38 fd806cc 135eb38 fd806cc 135eb38 fd806cc 135eb38 | 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 | import os
import zipfile
import gdown
import torch
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from transformers import AutoTokenizer, MT5ForConditionalGeneration
import uvicorn
from fastapi.middleware.cors import CORSMiddleware
ZIP_PATH = "./model.zip"
MODEL_PATH = "./saved_openie_model"
def download_and_extract_model():
if not os.path.exists(MODEL_PATH) or not os.listdir(MODEL_PATH):
print("جاري تحميل النموذج من Google Drive...")
url = f"https://drive.google.com/uc?id=1MZHAeCaQAyyfi6b2Dh3V_JCdTe8fTVmP"
gdown.download(url, ZIP_PATH, quiet=False)
print("جاري فك ضغط النموذج...")
with zipfile.ZipFile(ZIP_PATH, 'r') as zip_ref:
zip_ref.extractall(".")
if os.path.exists(ZIP_PATH):
os.remove(ZIP_PATH)
print(" تم تجهيز النموذج محلياً بنجاح!")
else:
print(" النموذج موجود مسبقاً، تخطي مرحلة التحميل.")
download_and_extract_model()
app = FastAPI(title="mT5 Relation Extraction API", version="1.0")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
device = torch.device("cpu")
print(" جاري تحميل النموذج والمُرمّز في الذاكرة...")
try:
tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)
model = MT5ForConditionalGeneration.from_pretrained(MODEL_PATH)
model.to(device)
model.eval() # وضع الاستنتاج
print("تم تحميل النموذج بنجاح! الخادم جاهز لاستقبال الطلبات.")
except Exception as e:
print(f" حدث خطأ أثناء تحميل النموذج: {e}")
class RelationRequest(BaseModel):
text: str
@app.post("/extract_relation")
async def extract_relation_api(request: RelationRequest):
try:
prompt = "استخراج العلاقة: " + request.text
inputs = tokenizer(
prompt,
return_tensors="pt",
max_length=64,
padding="max_length",
truncation=True
)
with torch.no_grad():
outputs = model.generate(
input_ids=inputs["input_ids"].to(device),
attention_mask=inputs["attention_mask"].to(device),
max_new_tokens=15,
num_beams=3,
early_stopping=True
)
predicted_relation = tokenizer.decode(outputs[0], skip_special_tokens=True).strip()
return {"relation": predicted_relation}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=7860) |