Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
@@ -6,14 +6,19 @@ import requests
|
|
6 |
from langchain.prompts import ChatPromptTemplate
|
7 |
from langchain_community.llms import Ollama
|
8 |
import subprocess
|
|
|
9 |
|
10 |
from func_ai import classify_comment, retrieve_from_vdb, VECTOR_API_URL
|
11 |
from func_facebook import get_page_id, has_page_replied, get_unanswered_comments, reply_comment, hide_negative_comments
|
12 |
|
|
|
|
|
|
|
|
|
13 |
# Wait for the server to start
|
14 |
time.sleep(10)
|
15 |
llm = Ollama(model="llama3.1")
|
16 |
-
|
17 |
|
18 |
template = """
|
19 |
You are an assistant answering users' questions using the provided context. Your tasks:
|
@@ -33,9 +38,20 @@ You are an assistant answering users' questions using the provided context. Your
|
|
33 |
Question: {input}
|
34 |
"""
|
35 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
36 |
|
37 |
def upload_file_vdb(file):
|
38 |
-
|
39 |
API_URL = f"{VECTOR_API_URL}/upload/"
|
40 |
|
41 |
file_path = file
|
@@ -48,44 +64,43 @@ def upload_file_vdb(file):
|
|
48 |
|
49 |
# Обработка ответа от сервера
|
50 |
if response.status_code == 200:
|
51 |
-
|
52 |
-
return
|
53 |
else:
|
54 |
-
|
55 |
return f"Ошибка: {response.json().get('detail')}"
|
56 |
|
57 |
-
|
58 |
def generate_response(user_query):
|
59 |
-
|
60 |
prompt = ChatPromptTemplate.from_template(template)
|
61 |
|
62 |
documents = retrieve_from_vdb(user_query)
|
63 |
context = "\n".join(documents)
|
64 |
|
65 |
-
|
66 |
full_prompt = prompt.format(context=context, input=user_query)
|
67 |
|
68 |
response = llm.invoke(full_prompt)
|
69 |
-
|
70 |
return response
|
71 |
|
72 |
-
|
73 |
def process_comments(ACCESS_TOKEN):
|
74 |
-
|
75 |
hidden_comments_data = hide_negative_comments(ACCESS_TOKEN)
|
76 |
-
|
77 |
|
78 |
-
|
79 |
posts_with_unanswered_comments = get_unanswered_comments(ACCESS_TOKEN)
|
80 |
|
81 |
page_id = get_page_id(ACCESS_TOKEN)
|
82 |
if not page_id:
|
83 |
-
|
84 |
return {"status": "failed", "reason": "Не удалось получить ID страницы."}
|
85 |
|
86 |
-
|
87 |
|
88 |
processed_posts = []
|
|
|
89 |
|
90 |
for post_data in posts_with_unanswered_comments:
|
91 |
post_id = post_data['post_id']
|
@@ -95,13 +110,19 @@ def process_comments(ACCESS_TOKEN):
|
|
95 |
post_replies = []
|
96 |
|
97 |
for comment in unanswered_comments:
|
|
|
|
|
|
|
|
|
|
|
|
|
98 |
message = comment['message']
|
99 |
-
|
100 |
classification = classify_comment(message)
|
101 |
-
|
102 |
if classification == "interrogative":
|
103 |
response_message = generate_response(message)
|
104 |
-
|
105 |
success = reply_comment(comment_id=comment['id'], message=response_message, token=ACCESS_TOKEN)
|
106 |
if success:
|
107 |
post_replies.append({
|
@@ -137,10 +158,12 @@ with gr.Blocks() as demo:
|
|
137 |
output_second = gr.Text()
|
138 |
second_page_btn = gr.Button("Отправить файл")
|
139 |
second_page_btn.click(upload_file_vdb, inputs=file_input, outputs=output_second)
|
|
|
|
|
140 |
|
141 |
if __name__ == "__main__":
|
142 |
demo.launch(
|
143 |
debug=True,
|
144 |
server_port=7860,
|
145 |
server_name="0.0.0.0",
|
146 |
-
)
|
|
|
6 |
from langchain.prompts import ChatPromptTemplate
|
7 |
from langchain_community.llms import Ollama
|
8 |
import subprocess
|
9 |
+
from datetime import datetime
|
10 |
|
11 |
from func_ai import classify_comment, retrieve_from_vdb, VECTOR_API_URL
|
12 |
from func_facebook import get_page_id, has_page_replied, get_unanswered_comments, reply_comment, hide_negative_comments
|
13 |
|
14 |
+
def log_message(message):
|
15 |
+
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
16 |
+
print(f"[{timestamp}] {message}")
|
17 |
+
|
18 |
# Wait for the server to start
|
19 |
time.sleep(10)
|
20 |
llm = Ollama(model="llama3.1")
|
21 |
+
log_message("Модель Ollama 'llama3.1' инициализирована.")
|
22 |
|
23 |
template = """
|
24 |
You are an assistant answering users' questions using the provided context. Your tasks:
|
|
|
38 |
Question: {input}
|
39 |
"""
|
40 |
|
41 |
+
def delete_faiss_index():
|
42 |
+
log_message("Удаляем FAISS индекс.")
|
43 |
+
response = requests.delete(f"{VECTOR_API_URL}/delete_index/")
|
44 |
+
|
45 |
+
if response.status_code == 200:
|
46 |
+
log_message("FAISS индекс успешно удален.")
|
47 |
+
return "Faiss успешно удален."
|
48 |
+
else:
|
49 |
+
log_message(f"Ошибка при удалении FAISS индекса: {response.json().get('detail')}")
|
50 |
+
return {"status": "error", "message": response.json().get("detail", "Ошибка при удалении FAISS индекса.")}
|
51 |
+
|
52 |
|
53 |
def upload_file_vdb(file):
|
54 |
+
log_message("Загружаем файл")
|
55 |
API_URL = f"{VECTOR_API_URL}/upload/"
|
56 |
|
57 |
file_path = file
|
|
|
64 |
|
65 |
# Обработка ответа от сервера
|
66 |
if response.status_code == 200:
|
67 |
+
log_message("Файл успешно загружен.")
|
68 |
+
return "Файл успешно загружен."
|
69 |
else:
|
70 |
+
log_message(f"Ошибка при загрузке файла: {response.json().get('detail')}")
|
71 |
return f"Ошибка: {response.json().get('detail')}"
|
72 |
|
|
|
73 |
def generate_response(user_query):
|
74 |
+
log_message(f"Генерация ответа на запрос: {user_query}")
|
75 |
prompt = ChatPromptTemplate.from_template(template)
|
76 |
|
77 |
documents = retrieve_from_vdb(user_query)
|
78 |
context = "\n".join(documents)
|
79 |
|
80 |
+
log_message(f"Контекст из базы данных: {context[:100]}...")
|
81 |
full_prompt = prompt.format(context=context, input=user_query)
|
82 |
|
83 |
response = llm.invoke(full_prompt)
|
84 |
+
log_message(f"Сгенерированный ответ: {response}")
|
85 |
return response
|
86 |
|
|
|
87 |
def process_comments(ACCESS_TOKEN):
|
88 |
+
log_message("Начинаем процесс скрытия отрицательных комментариев.")
|
89 |
hidden_comments_data = hide_negative_comments(ACCESS_TOKEN)
|
90 |
+
log_message(f"Количество постов с скрытыми комментариями: {len(hidden_comments_data)}")
|
91 |
|
92 |
+
log_message("Получение неотвеченных комментариев.")
|
93 |
posts_with_unanswered_comments = get_unanswered_comments(ACCESS_TOKEN)
|
94 |
|
95 |
page_id = get_page_id(ACCESS_TOKEN)
|
96 |
if not page_id:
|
97 |
+
log_message("Не удалось получить ID страницы.")
|
98 |
return {"status": "failed", "reason": "Не удалось получить ID страницы."}
|
99 |
|
100 |
+
log_message(f"ID страницы: {page_id}")
|
101 |
|
102 |
processed_posts = []
|
103 |
+
processed_comment_ids = set() # Отслеживание обработанных комментариев
|
104 |
|
105 |
for post_data in posts_with_unanswered_comments:
|
106 |
post_id = post_data['post_id']
|
|
|
110 |
post_replies = []
|
111 |
|
112 |
for comment in unanswered_comments:
|
113 |
+
comment_id = comment['id']
|
114 |
+
if comment_id in processed_comment_ids:
|
115 |
+
log_message(f"Комментарий {comment_id} уже обработан. Пропуск.")
|
116 |
+
continue
|
117 |
+
processed_comment_ids.add(comment_id)
|
118 |
+
|
119 |
message = comment['message']
|
120 |
+
log_message(f"Обработка комментария: {message}")
|
121 |
classification = classify_comment(message)
|
122 |
+
log_message(f"Классификация комментария: {classification}")
|
123 |
if classification == "interrogative":
|
124 |
response_message = generate_response(message)
|
125 |
+
log_message(f"Ответ на комментарий: {response_message}")
|
126 |
success = reply_comment(comment_id=comment['id'], message=response_message, token=ACCESS_TOKEN)
|
127 |
if success:
|
128 |
post_replies.append({
|
|
|
158 |
output_second = gr.Text()
|
159 |
second_page_btn = gr.Button("Отправить файл")
|
160 |
second_page_btn.click(upload_file_vdb, inputs=file_input, outputs=output_second)
|
161 |
+
delete_btn = gr.Button("Удалить FAISS индекс")
|
162 |
+
delete_btn.click(delete_faiss_index, outputs=output_second)
|
163 |
|
164 |
if __name__ == "__main__":
|
165 |
demo.launch(
|
166 |
debug=True,
|
167 |
server_port=7860,
|
168 |
server_name="0.0.0.0",
|
169 |
+
)
|