diginoron commited on
Commit
cb249ff
·
verified ·
1 Parent(s): 83e02af

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -53
app.py CHANGED
@@ -1,67 +1,63 @@
1
  import os
2
- import gradio as gr
3
- import pinecone
4
- from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
5
  from sentence_transformers import SentenceTransformer, util
 
 
6
 
7
- # Environment variables
8
- PINECONE_API_KEY = os.environ.get("PINECONE_API_KEY")
9
- PINECONE_INDEX_NAME = os.environ.get("PINECONE_INDEX_NAME")
10
- HF_TOKEN = os.environ.get("HF_TOKEN")
11
-
12
- assert PINECONE_API_KEY is not None, "\u274c PINECONE_API_KEY is missing!"
13
- assert PINECONE_INDEX_NAME is not None, "\u274c PINECONE_INDEX_NAME is missing!"
14
- assert HF_TOKEN is not None, "\u274c HF_TOKEN is missing!"
15
 
16
- # Load embedding model
17
  embedding_model = SentenceTransformer("sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2")
18
 
19
- # Init Pinecone
20
- pc = pinecone.Pinecone(api_key=PINECONE_API_KEY)
21
- index = pc.Index(PINECONE_INDEX_NAME)
22
-
23
- # Load language model and tokenizer
24
  tokenizer = AutoTokenizer.from_pretrained("HooshvareLab/gpt2-fa")
25
  model = AutoModelForCausalLM.from_pretrained("HooshvareLab/gpt2-fa")
26
- text_generator = pipeline(
27
- "text-generation",
28
- model=model,
29
- tokenizer=tokenizer,
30
- max_length=45,
31
- do_sample=True,
32
- top_p=0.95,
33
- temperature=0.8,
34
- return_full_text=False,
35
- )
36
 
37
- def generate_answer(question):
38
- try:
39
- # Step 1: Embed the question
40
- question_embedding = embedding_model.encode(question).tolist()
41
-
42
- # Step 2: Search similar questions in Pinecone
43
- search_result = index.query(vector=question_embedding, top_k=1, include_metadata=True)
44
-
45
- if search_result and search_result.matches:
46
- best_match = search_result.matches[0].metadata.get("answer", "")
47
-
48
- # Step 3: Rewrite with the language model
49
- prompt = f"پرسش: {question}\nپاسخ: {best_match}\nپاسخ نهایی:"
50
- output = text_generator(prompt, max_new_tokens=50)[0]["generated_text"]
51
- return output.strip()
52
- else:
53
- return "پاسخی برای این پرسش در پایگاه داده یافت نشد. لطفاً با پشتیبانی تماس بگیرید."
54
 
55
- except Exception as e:
56
- return f"خطا: {str(e)}"
57
 
58
- # Gradio Interface
59
- demo = gr.Interface(
60
- fn=generate_answer,
61
- inputs=gr.Textbox(label="question", placeholder="سوال خود را وارد کنید..."),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  outputs=gr.Textbox(label="output"),
63
- title="چت‌بات هوشمند تیام",
64
- description="سوالات خود درباره خدمات دیجیتال مارکتینگ تیام را بپرسید."
65
  )
66
 
67
- demo.launch()
 
1
  import os
2
+ import torch
3
+ from transformers import AutoTokenizer, AutoModelForCausalLM
 
4
  from sentence_transformers import SentenceTransformer, util
5
+ from pinecone import Pinecone
6
+ import gradio as gr
7
 
8
+ # انتشار متغیرها از Hugging Face secrets
9
+ HF_TOKEN = os.getenv("HF_TOKEN")
10
+ PINECONE_API_KEY = os.getenv("PINECONE_API_KEY")
11
+ PINECONE_INDEX_NAME = os.getenv("PINECONE_INDEX_NAME")
 
 
 
 
12
 
13
+ # مدل کوچک برای embedding (sentence-transformers)
14
  embedding_model = SentenceTransformer("sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2")
15
 
16
+ # مدل زبانی GPT2 فارسی
 
 
 
 
17
  tokenizer = AutoTokenizer.from_pretrained("HooshvareLab/gpt2-fa")
18
  model = AutoModelForCausalLM.from_pretrained("HooshvareLab/gpt2-fa")
 
 
 
 
 
 
 
 
 
 
19
 
20
+ # اتصال به Pinecone
21
+ pc = Pinecone(api_key=PINECONE_API_KEY)
22
+ index = pc.Index(PINECONE_INDEX_NAME)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
+ # توابع
 
25
 
26
+ def retrieve_from_pinecone(query):
27
+ query_embedding = embedding_model.encode(query).tolist()
28
+ search_result = index.query(vector=query_embedding, top_k=1, include_metadata=True)
29
+ try:
30
+ return search_result['matches'][0]['metadata']['answer']
31
+ except:
32
+ return "پاسخی برای این سوال پیدا نشد."
33
+
34
+ def generate_response(query):
35
+ base_answer = retrieve_from_pinecone(query)
36
+ prompt = f"{query}\n{base_answer}"
37
+
38
+ inputs = tokenizer(prompt, return_tensors="pt")
39
+
40
+ output = model.generate(
41
+ inputs["input_ids"],
42
+ attention_mask=inputs["attention_mask"],
43
+ max_new_tokens=30, # کمک به تسریع پاسخگویی
44
+ temperature=0.7,
45
+ do_sample=True,
46
+ pad_token_id=tokenizer.eos_token_id
47
+ )
48
+
49
+ response = tokenizer.decode(output[0], skip_special_tokens=True)
50
+
51
+ # جدا کردن پاسخ تولیدی از prompt
52
+ return response.replace(prompt, "").strip()
53
+
54
+ # رابط کاربری Gradio
55
+ iface = gr.Interface(
56
+ fn=generate_response,
57
+ inputs=gr.Textbox(label="question", placeholder="سوال خود را وارد کنید"),
58
  outputs=gr.Textbox(label="output"),
59
+ title="چتبات هوشمند تیام",
60
+ description="سوالات خود درباره خدمات دیجیتال مارکتینگ تیام را بپرسید"
61
  )
62
 
63
+ iface.launch()