Spaces:
Sleeping
Sleeping
File size: 2,328 Bytes
0f5d2ed d95ee14 3fbac70 281c0ae 3fbac70 0f5d2ed 012badc 74c93be 3fbac70 7279042 3fbac70 d95ee14 3fbac70 d95ee14 3fbac70 d95ee14 3fbac70 d95ee14 3fbac70 d95ee14 3fbac70 |
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 |
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()
|