Younes13 commited on
Commit
bb769c0
·
verified ·
1 Parent(s): c2c2689

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -0
app.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from transformers import AutoTokenizer, AutoModel
3
+ import numpy as np
4
+ from sklearn.metrics.pairwise import cosine_similarity
5
+ import gradio as gr
6
+
7
+ # 📌 مدل و توکنایزر
8
+ model_name = "HooshvareLab/bert-fa-base-uncased"
9
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
10
+ model = AutoModel.from_pretrained(model_name)
11
+
12
+ # 📄 دیتاست اولیه (FAQ)
13
+ faq_data = {
14
+ "پایتخت ایران کجاست؟": "تهران",
15
+ "زبان رسمی ایران چیست؟": "فارسی",
16
+ "واحد پول ایران چیست؟": "ریال",
17
+ "چه زمانی انتخاب واحد شروع می‌شود؟": "معمولاً پایان شهریور یا بهمن.",
18
+ "چه معدلی برای گرفتن 24 واحد لازم است؟": "حداقل معدل 17.",
19
+ }
20
+
21
+ questions = list(faq_data.keys())
22
+ answers = list(faq_data.values())
23
+
24
+ # 📄 تولید embedding
25
+ def get_embedding(text):
26
+ inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True, max_length=64)
27
+ with torch.no_grad():
28
+ outputs = model(**inputs)
29
+ emb = outputs.last_hidden_state.mean(dim=1).squeeze().cpu().numpy()
30
+ return emb
31
+
32
+ faq_embeddings = [get_embedding(q) for q in questions]
33
+
34
+ # 📄 تابع پاسخ
35
+ def answer_question(user_question):
36
+ user_emb = get_embedding(user_question)
37
+ sims = [cosine_similarity([user_emb], [emb])[0][0] for emb in faq_embeddings]
38
+ best_idx = int(np.argmax(sims))
39
+ best_score = sims[best_idx]
40
+
41
+ if best_score > 0.7:
42
+ return answers[best_idx]
43
+ else:
44
+ return "متأسفم، جواب دقیقی در دیتاست پیدا نکردم."
45
+
46
+ # 📄 رابط Gradio
47
+ with gr.Blocks() as demo:
48
+ gr.Markdown("## 🤖 دستیار فارسی (پایه بر اساس semantic search با BERT)")
49
+ inp = gr.Textbox(label="سؤال خود را بنویسید")
50
+ out = gr.Textbox(label="پاسخ")
51
+ btn = gr.Button("پاسخ بده")
52
+ btn.click(fn=answer_question, inputs=inp, outputs=out)
53
+
54
+ demo.launch()