Spaces:
Runtime error
Runtime error
File size: 2,797 Bytes
337f19e d173465 6aa5690 d173465 6aa5690 7e7a410 d173465 6aa5690 df561c7 d173465 df561c7 6aa5690 d173465 6aa5690 53ee217 6aa5690 f51748e 6aa5690 7e7a410 6aa5690 7e7a410 6aa5690 8796cef 6aa5690 |
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 |
import gradio as gr
from sentence_transformers import SentenceTransformer, util
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch
# بارگذاری مدل SBERT برای تشابه معنایی
embedder = SentenceTransformer("myrkur/sentence-transformer-parsbert-fa-2.0")
# بارگذاری مدل زبانی GPT فارسی
gpt_tokenizer = AutoTokenizer.from_pretrained("HooshvareLab/gpt2-fa")
gpt_model = AutoModelForCausalLM.from_pretrained("HooshvareLab/gpt2-fa")
# پایگاه داده سوالات متداول
faq_dict = {
"زمان انتخاب واحد": "معمولاً پایان شهریور و بهمن است.",
"زمان حذف و اضافه": "حدود یک هفته پس از شروع ترم تحصیلی است.",
"معدل لازم برای 24 واحد": "حداقل معدل 17 نیاز است.",
"حذف اضطراری": "تا هفته هشتم ترم مجاز است.",
"شرایط مهمان شدن": "با موافقت دانشگاه مبدا و مقصد انجام میشود.",
}
faq_questions = list(faq_dict.keys())
faq_embeddings = embedder.encode(faq_questions, convert_to_tensor=True)
# تابع پاسخدهی مدل زبانی Fallback
def generate_with_farsigpt(question, max_length=80):
try:
input_ids = gpt_tokenizer.encode(question, return_tensors="pt")
output = gpt_model.generate(input_ids, max_length=max_length, pad_token_id=gpt_tokenizer.eos_token_id)
response = gpt_tokenizer.decode(output[0], skip_special_tokens=True)
return response[len(question):].strip()
except Exception as e:
return f"❗️خطا در پاسخدهی با مدل زبانی: {str(e)}"
# تابع کلی پاسخدهی ایجنت
def student_bot(question):
try:
question_embedding = embedder.encode(question, convert_to_tensor=True)
cos_scores = util.pytorch_cos_sim(question_embedding, faq_embeddings)[0]
best_score = cos_scores.max().item()
best_idx = cos_scores.argmax().item()
if best_score >= 0.7:
best_q = faq_questions[best_idx]
return faq_dict[best_q]
else:
response = generate_with_farsigpt(question)
return f"🤖 پاسخ با مدل زبانی:\n{response}"
except Exception as e:
return f"❗️خطا در سیستم: {str(e)}"
# رابط کاربری Gradio
iface = gr.Interface(
fn=student_bot,
inputs=gr.Textbox(label="سؤال خود را وارد کنید"),
outputs=gr.Textbox(label="پاسخ"),
title="ایجنت راهنمای دانشجویان با fallback",
description="اول از پایگاه دانش، در صورت نبودن، با مدل زبانی پاسخ داده میشود."
)
iface.launch()
|