student-agent / app.py
Younes13's picture
Update app.py
6aa5690 verified
raw
history blame
2.8 kB
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()