tiyam-chatbot / app.py
diginoron's picture
Update app.py
3fbac70 verified
raw
history blame
2.33 kB
import os
import gradio as gr
from pinecone import Pinecone, ServerlessSpec
from sentence_transformers import SentenceTransformer
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
# بارگیری توکن‌ها از محیط
HF_TOKEN = os.environ.get("HF_TOKEN")
PINECONE_API_KEY = os.environ.get("PINECONE_API_KEY")
PINECONE_INDEX_NAME = os.environ.get("PINECONE_INDEX_NAME")
# بررسی متغیرها
assert HF_TOKEN is not None, "❌ Hugging Face token missing!"
assert PINECONE_API_KEY is not None, "❌ Pinecone API key missing!"
assert PINECONE_INDEX_NAME is not None, "❌ Pinecone index name is missing!"
# بارگذاری مدل‌های مورد نیاز
embedding_model = SentenceTransformer("sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2", token=HF_TOKEN)
tokenizer = AutoTokenizer.from_pretrained("google/mt5-small", token=HF_TOKEN)
language_model = AutoModelForSeq2SeqLM.from_pretrained("google/mt5-small", token=HF_TOKEN)
# اتصال به Pinecone (نسخه جدید)
pc = Pinecone(api_key=PINECONE_API_KEY)
index = pc.Index(PINECONE_INDEX_NAME)
def get_similar_context(question, top_k=1):
question_embedding = embedding_model.encode(question).tolist()
results = index.query(vector=question_embedding, top_k=top_k, include_metadata=True)
if results and results['matches']:
return results['matches'][0]['metadata']['text']
return ""
def generate_answer(question):
context = get_similar_context(question)
if context:
prompt = f"پرسش: {question}\nاطلاعات مرتبط: {context}\nپاسخ:"
else:
prompt = f"پرسش: {question}\nپاسخ:"
inputs = tokenizer(prompt, return_tensors="pt", padding=True, truncation=True)
outputs = language_model.generate(**inputs, max_new_tokens=100)
return tokenizer.decode(outputs[0], skip_special_tokens=True)
# رابط گرافیکی
gr.Interface(
fn=generate_answer,
inputs=gr.Textbox(label="سؤال خود را وارد کنید", placeholder="مثلاً خدمات سئو تیام شامل چیست؟"),
outputs=gr.Textbox(label="پاسخ هوشمند"),
title="🤖 چت‌بات هوشمند تیام",
description="با استفاده از داده‌های اختصاصی، پاسخ هوشمندانه دریافت کنید."
).launch()