sgt444pepper commited on
Commit
6258aee
·
verified ·
1 Parent(s): 1d40253
Files changed (1) hide show
  1. app.py +113 -60
app.py CHANGED
@@ -1,64 +1,117 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
 
 
 
 
 
 
 
 
62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  if __name__ == "__main__":
64
- demo.launch()
 
1
  import gradio as gr
2
+ import faiss
3
+ import numpy as np
4
+ from rank_bm25 import BM25Okapi
5
+ from transformers import AutoTokenizer, AutoModel
6
+ from litellm import completion
7
+ import os
8
+ import torch
9
+ from sentence_transformers import CrossEncoder
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
+ # --- 1. Завантаження документів ---
12
+ def load_documents(file_paths):
13
+ documents = []
14
+ for path in file_paths:
15
+ with open(path, 'r', encoding='utf-8') as file:
16
+ documents.append(file.read().strip())
17
+ return documents
18
 
19
+ # --- 2. Індексування документів ---
20
+ class DocumentIndexer:
21
+ def __init__(self, documents):
22
+ self.documents = documents
23
+ self.bm25 = BM25Okapi([doc.split() for doc in documents])
24
+ self.tokenizer = AutoTokenizer.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")
25
+ self.model = AutoModel.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")
26
+ self.index = self.create_faiss_index()
27
+
28
+ def create_faiss_index(self):
29
+ embeddings = self.embed_documents(self.documents)
30
+ dimension = embeddings.shape[1]
31
+ index = faiss.IndexFlatL2(dimension)
32
+ index.add(embeddings)
33
+ return index
34
+
35
+ def embed_documents(self, docs):
36
+ tokens = self.tokenizer(docs, padding=True, truncation=True, return_tensors="pt")
37
+ with torch.no_grad():
38
+ embeddings = self.model(**tokens).last_hidden_state.mean(dim=1).numpy()
39
+ return embeddings
40
+
41
+ def search_bm25(self, query, top_k=5):
42
+ query_terms = query.split()
43
+ scores = self.bm25.get_scores(query_terms)
44
+ top_indices = np.argsort(scores)[::-1][:top_k]
45
+ return [self.documents[i] for i in top_indices]
46
+
47
+ def search_semantic(self, query, top_k=5):
48
+ query_embedding = self.embed_documents([query])
49
+ distances, indices = self.index.search(query_embedding, top_k)
50
+ return [self.documents[i] for i in indices[0]]
51
+
52
+ # --- 3. Ререйкер ---
53
+ class Reranker:
54
+ def __init__(self, model_name="cross-encoder/ms-marco-TinyBERT-L-6"):
55
+ self.tokenizer = AutoTokenizer.from_pretrained(model_name)
56
+ self.model = CrossEncoder(model_name)
57
+
58
+ def rank(self, query, documents):
59
+ pairs = [(query, doc) for doc in documents]
60
+ scores = self.model.predict(pairs)
61
+ ranked_docs = [documents[i] for i in np.argsort(scores)[::-1]]
62
+ return ranked_docs
63
+
64
+ # --- 4. Генерація відповіді ---
65
+ class QAChatbot:
66
+ def __init__(self, indexer, reranker):
67
+ self.indexer = indexer
68
+ self.reranker = reranker
69
+
70
+ def generate_answer(self, query):
71
+ # 1. Шукаємо релевантні документи
72
+ bm25_results = self.indexer.search_bm25(query)
73
+ semantic_results = self.indexer.search_semantic(query)
74
+ combined_results = list(set(bm25_results + semantic_results))
75
+
76
+ # 2. Ранжуємо документи
77
+ ranked_docs = self.reranker.rank(query, combined_results)
78
+
79
+ # 3. Генеруємо відповідь
80
+ context = "\n".join(ranked_docs[:3]) # Використовуємо топ-3 документи
81
+ response = completion(
82
+ model="groq/llama3-8b-8192",
83
+ messages=[
84
+ {
85
+ "role": "system",
86
+ "content": PROMPT
87
+ },
88
+ {
89
+ "role": "user",
90
+ "content": f"Context: {context}\n\nQuestion: {query}\nAnswer:",
91
+ }
92
+ ],
93
+ )
94
+ return response
95
+
96
+ # --- 5. Створення Gradio інтерфейсу ---
97
+ def chatbot_interface(query):
98
+ file_paths = ["company.txt", "Base.txt"] # Вкажіть ваші файли
99
+ documents = load_documents(file_paths)
100
+
101
+ # Налаштовуємо індексер та ререйкер
102
+ indexer = DocumentIndexer(documents)
103
+ reranker = Reranker()
104
+
105
+ # Запускаємо чат-бота
106
+ chatbot = QAChatbot(indexer, reranker)
107
+ answer = chatbot.generate_answer(query)
108
+ return answer["choices"][0]["message"]["content"]
109
+
110
+ # Створення інтерфейсу Gradio
111
+ iface = gr.Interface(fn=chatbot_interface, inputs="text", outputs="text",
112
+ live=True, title="Чат-бот для ритейл-компанії",
113
+ description="Запитуйте мене про товари і я допоможу вам вибрати найкраще!")
114
+
115
+ # Запуск інтерфейсу
116
  if __name__ == "__main__":
117
+ iface.launch()