Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
@@ -1,5 +1,3 @@
|
|
1 |
-
# app.py
|
2 |
-
|
3 |
import os
|
4 |
import sys
|
5 |
import time
|
@@ -7,25 +5,21 @@ import gradio as gr
|
|
7 |
import requests
|
8 |
from langchain.prompts import ChatPromptTemplate
|
9 |
from langchain_community.llms import Ollama
|
|
|
10 |
from datetime import datetime
|
11 |
|
12 |
-
from func_ai import classify_comment, retrieve_from_vdb,
|
13 |
-
from func_facebook import
|
14 |
-
get_page_id,
|
15 |
-
has_page_replied,
|
16 |
-
get_unanswered_comments,
|
17 |
-
reply_comment,
|
18 |
-
hide_negative_comments,
|
19 |
-
log_message
|
20 |
-
)
|
21 |
-
|
22 |
-
VECTOR_API_URL = os.getenv('API_URL')
|
23 |
|
24 |
-
def
|
25 |
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
26 |
print(f"[{timestamp}] {message}")
|
27 |
|
28 |
-
#
|
|
|
|
|
|
|
|
|
29 |
template = """
|
30 |
You are an assistant answering users' questions using the provided context. Your tasks:
|
31 |
|
@@ -45,96 +39,68 @@ Question: {input}
|
|
45 |
"""
|
46 |
|
47 |
def delete_faiss_index():
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
log_message_app(f"Ошибка при удалении FAISS индекса: {e}")
|
59 |
-
return {"status": "error", "message": str(e)}
|
60 |
|
61 |
def upload_file_vdb(file):
|
62 |
-
|
63 |
API_URL = f"{VECTOR_API_URL}/upload/"
|
64 |
|
65 |
-
file_path = file
|
66 |
file_name = os.path.basename(file_path)
|
67 |
|
68 |
-
#
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
# Обработка ответа от сервера
|
85 |
-
if response.status_code == 200:
|
86 |
-
log_message_app("Файл успешно загружен.")
|
87 |
-
return "Файл успешно загружен."
|
88 |
-
else:
|
89 |
-
log_message_app(f"Ошибка при загрузке файла: {response.json().get('detail')}")
|
90 |
-
return f"Ошибка: {response.json().get('detail')}"
|
91 |
-
except Exception as e:
|
92 |
-
log_message_app(f"Ошибка при загрузке файла: {e}")
|
93 |
-
return f"Ошибка: {str(e)}"
|
94 |
-
|
95 |
-
def generate_response(user_query, llm):
|
96 |
-
log_message_app(f"Генерация ответа на запрос: {user_query}")
|
97 |
prompt = ChatPromptTemplate.from_template(template)
|
98 |
|
99 |
documents = retrieve_from_vdb(user_query)
|
100 |
context = "\n".join(documents)
|
101 |
|
102 |
-
|
103 |
full_prompt = prompt.format(context=context, input=user_query)
|
104 |
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
return response
|
109 |
-
except Exception as e:
|
110 |
-
log_message_app(f"Ошибка при генерации ответа: {e}")
|
111 |
-
return "Извините, возникла ошибка при обработке вашего запроса."
|
112 |
|
113 |
def process_comments(ACCESS_TOKEN):
|
114 |
-
|
115 |
hidden_comments_data = hide_negative_comments(ACCESS_TOKEN)
|
116 |
-
|
117 |
|
118 |
-
|
119 |
posts_with_unanswered_comments = get_unanswered_comments(ACCESS_TOKEN)
|
120 |
|
121 |
page_id = get_page_id(ACCESS_TOKEN)
|
122 |
if not page_id:
|
123 |
-
|
124 |
return {"status": "failed", "reason": "Не удалось получить ID страницы."}
|
125 |
|
126 |
-
|
127 |
|
128 |
processed_posts = []
|
129 |
|
130 |
-
# Инициализируем модель Ollama
|
131 |
-
try:
|
132 |
-
llm = Ollama(model="llama3.1")
|
133 |
-
log_message_app("Модель Ollama 'llama3.1' инициализирована.")
|
134 |
-
except Exception as e:
|
135 |
-
log_message_app(f"Ошибка инициализации модели Ollama: {e}")
|
136 |
-
return {"status": "failed", "reason": "Ошибка инициализации модели AI."}
|
137 |
-
|
138 |
for post_data in posts_with_unanswered_comments:
|
139 |
post_id = post_data['post_id']
|
140 |
post_message = post_data['post_message']
|
@@ -144,12 +110,12 @@ def process_comments(ACCESS_TOKEN):
|
|
144 |
|
145 |
for comment in unanswered_comments:
|
146 |
message = comment['message']
|
147 |
-
|
148 |
classification = classify_comment(message)
|
149 |
-
|
150 |
if classification == "interrogative":
|
151 |
-
response_message = generate_response(message
|
152 |
-
|
153 |
success = reply_comment(comment_id=comment['id'], message=response_message, token=ACCESS_TOKEN)
|
154 |
if success:
|
155 |
post_replies.append({
|
@@ -170,7 +136,6 @@ def process_comments(ACCESS_TOKEN):
|
|
170 |
"posts": processed_posts
|
171 |
}
|
172 |
|
173 |
-
# Создание интерфейса Gradio
|
174 |
with gr.Blocks() as demo:
|
175 |
with gr.Tab("Главная страница"):
|
176 |
gr.Markdown("# Facebook Comment Filter")
|
@@ -180,7 +145,7 @@ with gr.Blocks() as demo:
|
|
180 |
process_btn.click(process_comments, inputs=token_input, outputs=output_main)
|
181 |
|
182 |
with gr.Tab("Загрузить данные"):
|
183 |
-
gr.Markdown("# Отправь
|
184 |
file_input = gr.File(label="Загрузите Excel файл (.xlsx)")
|
185 |
output_second = gr.Text()
|
186 |
second_page_btn = gr.Button("Отправить файл")
|
@@ -193,5 +158,4 @@ if __name__ == "__main__":
|
|
193 |
debug=True,
|
194 |
server_port=7860,
|
195 |
server_name="0.0.0.0",
|
196 |
-
|
197 |
-
)
|
|
|
|
|
|
|
1 |
import os
|
2 |
import sys
|
3 |
import time
|
|
|
5 |
import requests
|
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:
|
25 |
|
|
|
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
|
58 |
file_name = os.path.basename(file_path)
|
59 |
|
60 |
+
# Открываем файл в бинарном режиме
|
61 |
+
with open(file_path, 'rb') as f:
|
62 |
+
files = {'file': (file_name, f)}
|
63 |
+
response = requests.post(API_URL, files=files)
|
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 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
104 |
for post_data in posts_with_unanswered_comments:
|
105 |
post_id = post_data['post_id']
|
106 |
post_message = post_data['post_message']
|
|
|
110 |
|
111 |
for comment in unanswered_comments:
|
112 |
message = comment['message']
|
113 |
+
log_message(f"Обработка комментария: {message}")
|
114 |
classification = classify_comment(message)
|
115 |
+
log_message(f"Классификация комментария: {classification}")
|
116 |
if classification == "interrogative":
|
117 |
+
response_message = generate_response(message)
|
118 |
+
log_message(f"Ответ на комментарий: {response_message}")
|
119 |
success = reply_comment(comment_id=comment['id'], message=response_message, token=ACCESS_TOKEN)
|
120 |
if success:
|
121 |
post_replies.append({
|
|
|
136 |
"posts": processed_posts
|
137 |
}
|
138 |
|
|
|
139 |
with gr.Blocks() as demo:
|
140 |
with gr.Tab("Главная страница"):
|
141 |
gr.Markdown("# Facebook Comment Filter")
|
|
|
145 |
process_btn.click(process_comments, inputs=token_input, outputs=output_main)
|
146 |
|
147 |
with gr.Tab("Загрузить данные"):
|
148 |
+
gr.Markdown("# Отправь excel файл")
|
149 |
file_input = gr.File(label="Загрузите Excel файл (.xlsx)")
|
150 |
output_second = gr.Text()
|
151 |
second_page_btn = gr.Button("Отправить файл")
|
|
|
158 |
debug=True,
|
159 |
server_port=7860,
|
160 |
server_name="0.0.0.0",
|
161 |
+
)
|
|