Younes13 commited on
Commit
175598c
·
verified ·
1 Parent(s): d6dc1ff

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -35
app.py CHANGED
@@ -1,16 +1,14 @@
1
- import gradio as gr
2
- from sentence_transformers import SentenceTransformer, util
3
- from transformers import AutoTokenizer, AutoModelForCausalLM
4
  import torch
 
 
 
 
5
 
6
- # بارگذاری مدل SBERT برای تشابه معنایی
7
- embedder = SentenceTransformer("myrkur/sentence-transformer-parsbert-fa-2.0")
8
-
9
- # بارگذاری مدل زبانی GPT فارسی
10
- gpt_tokenizer = AutoTokenizer.from_pretrained("HooshvareLab/gpt2-fa")
11
- gpt_model = AutoModelForCausalLM.from_pretrained("HooshvareLab/gpt2-fa")
12
 
13
- # پایگاه داده سوالات متداول
14
  faq_dict = {
15
  "زمان انتخاب واحد": "معمولاً پایان شهریور و بهمن است.",
16
  "زمان حذف و اضافه": "حدود یک هفته پس از شروع ترم تحصیلی است.",
@@ -20,42 +18,41 @@ faq_dict = {
20
  }
21
 
22
  faq_questions = list(faq_dict.keys())
23
- faq_embeddings = embedder.encode(faq_questions, convert_to_tensor=True)
24
 
25
- # تابع پاسخ‌دهی مدل زبانی Fallback
26
- def generate_with_farsigpt(question, max_length=80):
27
- try:
28
- input_ids = gpt_tokenizer.encode(question, return_tensors="pt")
29
- output = gpt_model.generate(input_ids, max_length=max_length, pad_token_id=gpt_tokenizer.eos_token_id)
30
- response = gpt_tokenizer.decode(output[0], skip_special_tokens=True)
31
- return response[len(question):].strip()
32
- except Exception as e:
33
- return f"❗️خطا در پاسخ‌دهی با مدل زبانی: {str(e)}"
 
 
34
 
35
- # تابع کلی پاسخ‌دهی ایجنت
36
- def student_bot(question):
37
  try:
38
- question_embedding = embedder.encode(question, convert_to_tensor=True)
39
- cos_scores = util.pytorch_cos_sim(question_embedding, faq_embeddings)[0]
40
- best_score = cos_scores.max().item()
41
- best_idx = cos_scores.argmax().item()
42
-
43
- if best_score >= 0.7:
44
- best_q = faq_questions[best_idx]
45
- return faq_dict[best_q]
46
  else:
47
- response = generate_with_farsigpt(question)
48
- return f"🤖 پاسخ با مدل زبانی:\n{response}"
49
  except Exception as e:
50
  return f"❗️خطا در سیستم: {str(e)}"
51
 
52
- # رابط کاربری Gradio
53
  iface = gr.Interface(
54
  fn=student_bot,
55
  inputs=gr.Textbox(label="سؤال خود را وارد کنید"),
56
  outputs=gr.Textbox(label="پاسخ"),
57
- title="ایجنت راهنمای دانشجویان با fallback",
58
- description="اول از پایگاه دانش، در صورت نبودن، با مدل زبانی پاسخ داده می‌شود."
59
  )
60
 
61
  iface.launch()
 
 
 
 
1
  import torch
2
+ import gradio as gr
3
+ from transformers import AutoTokenizer, AutoModel
4
+ from sklearn.metrics.pairwise import cosine_similarity
5
+ import numpy as np
6
 
7
+ # بارگذاری مدل FarsiBERT
8
+ tokenizer = AutoTokenizer.from_pretrained("HooshvareLab/bert-fa-base-uncased")
9
+ model = AutoModel.from_pretrained("HooshvareLab/bert-fa-base-uncased")
 
 
 
10
 
11
+ # داده‌های پرسش و پاسخ
12
  faq_dict = {
13
  "زمان انتخاب واحد": "معمولاً پایان شهریور و بهمن است.",
14
  "زمان حذف و اضافه": "حدود یک هفته پس از شروع ترم تحصیلی است.",
 
18
  }
19
 
20
  faq_questions = list(faq_dict.keys())
 
21
 
22
+ # تابع استخراج embedding از جمله
23
+ def get_embedding(text):
24
+ inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True)
25
+ with torch.no_grad():
26
+ outputs = model(**inputs)
27
+ # میانگین‌گیری از همه توکن‌ها در آخرین لایه
28
+ embeddings = outputs.last_hidden_state.mean(dim=1)
29
+ return embeddings[0].cpu().numpy()
30
+
31
+ # پیش‌محاسبه embedding تمام سوالات FAQ
32
+ faq_embeddings = [get_embedding(q) for q in faq_questions]
33
 
34
+ # تابع اصلی ایجنت
35
+ def student_bot(user_question):
36
  try:
37
+ user_emb = get_embedding(user_question)
38
+ sims = [cosine_similarity([user_emb], [emb])[0][0] for emb in faq_embeddings]
39
+ best_idx = int(np.argmax(sims))
40
+ best_score = sims[best_idx]
41
+
42
+ if best_score > 0.75:
43
+ return faq_dict[faq_questions[best_idx]]
 
44
  else:
45
+ return "متأسفم، پاسخ این سوال در حال حاضر موجود نیست."
 
46
  except Exception as e:
47
  return f"❗️خطا در سیستم: {str(e)}"
48
 
49
+ # رابط کاربری
50
  iface = gr.Interface(
51
  fn=student_bot,
52
  inputs=gr.Textbox(label="سؤال خود را وارد کنید"),
53
  outputs=gr.Textbox(label="پاسخ"),
54
+ title="ایجنت راهنمای دانشجویان با FarsiBERT",
55
+ description="پاسخ به پرسش‌های رایج بر اساس تشابه معنایی"
56
  )
57
 
58
  iface.launch()