romana8888 commited on
Commit
97ea390
·
verified ·
1 Parent(s): bc5629b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -5
app.py CHANGED
@@ -1,20 +1,76 @@
1
  from fastapi import FastAPI, HTTPException
2
  from pydantic import BaseModel
 
 
 
3
 
4
  app = FastAPI()
5
 
 
6
  @app.get("/")
7
  def home():
8
- return {"message": "✅ Essay Grading API is running on Hugging Face!"}
9
 
 
 
 
 
 
 
10
  class GradeInput(BaseModel):
11
  question: str
12
  model_answer: str
13
  student_answer: str
14
 
 
15
  @app.post("/evaluate")
16
  def evaluate_answer(data: GradeInput):
17
- return {
18
- "score": 9,
19
- "feedback": "👍 Great structure and clear explanation!"
20
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from fastapi import FastAPI, HTTPException
2
  from pydantic import BaseModel
3
+ import requests
4
+ import os
5
+ import re
6
 
7
  app = FastAPI()
8
 
9
+ # ✅ رسالة ترحيب للتأكد إن السيرفر شغال
10
  @app.get("/")
11
  def home():
12
+ return {"message": "✅ Essay Grading API using Bloomz-560m is running!"}
13
 
14
+ # ✅ جلب Hugging Face API Token من المتغيرات البيئية
15
+ HF_API_KEY = os.environ.get("HF_API_KEY", "fake_key")
16
+ API_URL = "https://api-inference.huggingface.co/models/bigscience/bloomz-560m"
17
+ headers = {"Authorization": f"Bearer {HF_API_KEY}"}
18
+
19
+ # ✅ شكل البيانات المطلوبة في POST
20
  class GradeInput(BaseModel):
21
  question: str
22
  model_answer: str
23
  student_answer: str
24
 
25
+ # ✅ نقطة التقييم
26
  @app.post("/evaluate")
27
  def evaluate_answer(data: GradeInput):
28
+ if HF_API_KEY == "fake_key":
29
+ raise HTTPException(status_code=403, detail="❌ HF_API_KEY is not set in environment variables.")
30
+
31
+ # إنشاء الـ prompt
32
+ prompt = f"""
33
+ قيّم إجابة الطالب مقارنة بالإجابة النموذجية.
34
+
35
+ السؤال: {data.question}
36
+ الإجابة النموذجية: {data.model_answer}
37
+ إجابة الطالب: {data.student_answer}
38
+
39
+ أعط درجة من 10 وفسر لماذا، بصيغة JSON فقط:
40
+ {{"score": X, "feedback": "..."}}"""
41
+
42
+ try:
43
+ response = requests.post(
44
+ API_URL,
45
+ headers=headers,
46
+ json={"inputs": prompt},
47
+ timeout=60
48
+ )
49
+
50
+ if response.status_code != 200:
51
+ raise HTTPException(status_code=500, detail=f"Model Error: {response.text}")
52
+
53
+ result = response.json()
54
+
55
+ # التحقق من وجود نص التوليد
56
+ if isinstance(result, dict) and "generated_text" in result:
57
+ full_text = result["generated_text"]
58
+ elif isinstance(result, list) and "generated_text" in result[0]:
59
+ full_text = result[0]["generated_text"]
60
+ else:
61
+ full_text = str(result)
62
+
63
+ # استخراج البيانات من النص الناتج
64
+ score_match = re.search(r'"score"\s*:\s*(\d+)', full_text)
65
+ feedback_match = re.search(r'"feedback"\s*:\s*"([^"]+)"', full_text)
66
+
67
+ score = int(score_match.group(1)) if score_match else 0
68
+ feedback = feedback_match.group(1) if feedback_match else "⚠️ لم يتم استخراج التغذية الراجعة."
69
+
70
+ return {
71
+ "score": score,
72
+ "feedback": feedback
73
+ }
74
+
75
+ except Exception as e:
76
+ raise HTTPException(status_code=500, detail=str(e))