SuperSl6 commited on
Commit
3b513ce
·
verified ·
1 Parent(s): d225600

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +170 -0
app.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # app.py – Arabic Questions Summarization in Mental Healthcare with ALLaM
3
+ # Based 1-to-1 on the original Colab notebook (no changes to instructions).
4
+
5
+ import torch
6
+ from transformers import AutoTokenizer, AutoModelForCausalLM
7
+ import gradio as gr
8
+
9
+ # ------------------------------------------------------------------
10
+ # 1. Device setup
11
+ # ------------------------------------------------------------------
12
+ device = "cuda" if torch.cuda.is_available() else "cpu"
13
+ print(f"Using device: {device}")
14
+
15
+ # ------------------------------------------------------------------
16
+ # 2. Load ALLaM
17
+ # ------------------------------------------------------------------
18
+ model_id = "ALLaM-AI/ALLaM-7B-Instruct-preview"
19
+
20
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
21
+
22
+ model = AutoModelForCausalLM.from_pretrained(
23
+ model_id,
24
+ device_map="auto" if device == "cuda" else None,
25
+ torch_dtype=torch.float16 if device == "cuda" else torch.float32,
26
+ load_in_8bit=True if device == "cuda" else False,
27
+ )
28
+
29
+ # ------------------------------------------------------------------
30
+ # 3. Generation helpers (verbatim logic from the notebook)
31
+ # ------------------------------------------------------------------
32
+ def generate_chat_response(
33
+ system_text: str,
34
+ user_text: str,
35
+ max_new_tokens: int = 40,
36
+ temperature: float = 0.2,
37
+ ):
38
+ messages = []
39
+ if system_text.strip():
40
+ messages.append({"role": "system", "content": system_text})
41
+ messages.append({"role": "user", "content": user_text})
42
+
43
+ chat_input_text = tokenizer.apply_chat_template(messages, tokenize=False)
44
+ inputs = tokenizer(
45
+ chat_input_text,
46
+ return_tensors="pt",
47
+ return_token_type_ids=False,
48
+ )
49
+ inputs = {k: v.to(model.device) for k, v in inputs.items()}
50
+
51
+ with torch.inference_mode():
52
+ output_tokens = model.generate(
53
+ **inputs,
54
+ max_new_tokens=max_new_tokens,
55
+ do_sample=False,
56
+ pad_token_id=tokenizer.eos_token_id,
57
+ )
58
+
59
+ output_text = tokenizer.decode(output_tokens[0], skip_special_tokens=True)
60
+ output_text = output_text.replace("[/INST]", "")
61
+ return output_text.strip()
62
+
63
+
64
+ def generate_text(prompt: str, max_new_tokens: int = 60):
65
+ system_text = "" # keep system empty exactly as in notebook
66
+ return generate_chat_response(
67
+ system_text=system_text,
68
+ user_text=prompt,
69
+ max_new_tokens=max_new_tokens,
70
+ )
71
+
72
+ # ------------------------------------------------------------------
73
+ # 4. Prompt construction (instructions unchanged)
74
+ # ------------------------------------------------------------------
75
+ def prompt_short_question_cot_few_shots(question_text: str) -> str:
76
+ examples = """
77
+ أمثلة على كيفية التفكير خطوة بخطوة ثم إعطاء السؤال المختصر:
78
+
79
+ السؤال الأصلي:
80
+ انا فيني اكتئاب وقلق ووصف لي دكتور citalopram استخدمتها ثلاث شهور ولا نفع احتاج وصفه Ativan
81
+
82
+ فكر خطوة بخطوة:
83
+ 1. المستخدم يعاني من اكتئاب وقلق.
84
+ 2. تناول دواء citalopram لثلاثة أشهر من دون تحسّن.
85
+ 3. يسأل عن الحصول على وصفة Ativan كبديل أو إضافة للعلاج.
86
+
87
+ السؤال المختصر:
88
+ استفسار حول عدم فعالية citalopram والحاجة الى Ativan
89
+
90
+
91
+ السؤال الأصلي:
92
+ كنت اعاني من قلق وأخذت دواء سبرالكس لمدة 4 شهور وتوقفت عنه في 2014. سأذهب لتحليل بول للعمل، هل سيظهر أثر الدواء؟
93
+
94
+ فكر خطوة بخطوة:
95
+ 1. المستخدم كان يعاني من قلق وتناول سبرالكس قبل عدة سنوات.
96
+ 2. يخشى أن يظهر الدواء القديم في فحص البول المطلوب للعمل.
97
+ 3. يريد معرفة إن كان ما زال موجوداً في جسمه.
98
+
99
+ السؤال المختصر:
100
+ سؤال حول بقاء أثر الدواء في تحليل البول بعد مدة؟
101
+
102
+
103
+ السؤال الأصلي:
104
+ أصبت بالاضطراب الوجداني منذ 2008، تكررت النوبات عدة مرات. أتناول تيجرتول وأرايبرزول وأولابكس. أرغب بالعلاج النفسي دون أدوية.
105
+
106
+ فكر خطوة بخطوة:
107
+ 1. المستخدم لديه اضطراب وجداني منذ سنوات طويلة.
108
+ 2. لديه نوبات متكررة أعوام 2008، 2009، 2013، 2017، و2018.
109
+ 3. يأخذ عدة أدوية (تيجرتول وأرايبرزول وأولابكس).
110
+ 4. يريد الآن علاجاً غير دوائي، ربما علاجاً نفسياً بديلاً.
111
+
112
+ السؤال المختصر:
113
+ استفسار حول علاج الاضطراب الوجداني بدون دواء
114
+ """.strip()
115
+
116
+ new_question_segment = f"""
117
+ الآن لديك سؤال جديد، فكر خطوة بخطوة بشكل مشابه ثم أعطني السؤال المختصر:
118
+ تأكد من عدم ��ضافة ملاحظات أو اضافة معلومة غير موجودة في السؤال
119
+ السؤال الأصلي:
120
+ {question_text}
121
+
122
+ السؤال المختصر:
123
+ """
124
+
125
+ prompt = f"""
126
+ أنت مساعد لغوي مختص بأسئلة الصحة النفسية.
127
+ هدفك هو إعادة كتابة الأسئلة المطوّلة في شكل مختصر ومباشر، يركّز على النقطة الأساسية.
128
+ {examples}
129
+ {new_question_segment}
130
+ """.strip()
131
+ return prompt
132
+
133
+
134
+ def summarize_question_cot_few_shots(question_text: str) -> str:
135
+ prompt = prompt_short_question_cot_few_shots(question_text)
136
+ raw_output = generate_text(prompt, max_new_tokens=60)
137
+
138
+ if "السؤال المختصر:" in raw_output:
139
+ short_summary = raw_output.split("السؤال المختصر:")[-1].strip()
140
+ else:
141
+ short_summary = raw_output.strip()
142
+
143
+ return short_summary
144
+
145
+ # ------------------------------------------------------------------
146
+ # 5. Gradio interface
147
+ # ------------------------------------------------------------------
148
+ def gradio_predict(question: str) -> str:
149
+ return summarize_question_cot_few_shots(question)
150
+
151
+
152
+ demo = gr.Interface(
153
+ fn=gradio_predict,
154
+ inputs=gr.Textbox(
155
+ lines=7,
156
+ label="السؤال الأصلي",
157
+ placeholder="اكتب سؤالك المطوّل هنا...",
158
+ ),
159
+ outputs=gr.Textbox(label="السؤال المختصر"),
160
+ title="🧠 Arabic Mental-Health Question Summarizer (ALLaM-7B)",
161
+ description=(
162
+ "يعيد هذا التطبيق صياغة الأسئلة العربية الطويلة حول الصحة النفسية إلى سؤال مختصر ومباشر."
163
+ ),
164
+ examples=[
165
+ "كنت أعاني من قلق وأخذت دواء سبرالكس لمدة 4 شهور وتوقفت عنه عام 2014..."
166
+ ],
167
+ )
168
+
169
+ if __name__ == "__main__":
170
+ demo.launch()