Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
@@ -1,20 +1,21 @@
|
|
1 |
import os
|
2 |
-
import sys
|
3 |
import time
|
|
|
|
|
4 |
import gradio as gr
|
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,
|
12 |
-
from func_facebook import get_page_id,
|
|
|
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")
|
@@ -40,10 +41,11 @@ Question: {input}
|
|
40 |
|
41 |
"""
|
42 |
|
|
|
43 |
def delete_faiss_index():
|
44 |
log_message("Удаляем FAISS индекс.")
|
45 |
response = requests.delete(f"{VECTOR_API_URL}/delete_index/")
|
46 |
-
|
47 |
if response.status_code == 200:
|
48 |
log_message("FAISS индекс успешно удален.")
|
49 |
return "Faiss успешно удален."
|
@@ -72,13 +74,11 @@ def upload_file_vdb(file):
|
|
72 |
log_message(f"Ошибка при загрузке файла: {response.json().get('detail')}")
|
73 |
return f"Ошибка: {response.json().get('detail')}"
|
74 |
|
75 |
-
|
|
|
76 |
log_message(f"Генерация ответа на запрос: {user_query}")
|
77 |
prompt = ChatPromptTemplate.from_template(template)
|
78 |
|
79 |
-
documents = retrieve_from_vdb(user_query)
|
80 |
-
context = "\n".join(documents)
|
81 |
-
|
82 |
log_message(f"Контекст из базы данных: {context[:100]}...")
|
83 |
full_prompt = prompt.format(context=context, input=user_query)
|
84 |
|
@@ -86,7 +86,8 @@ def generate_response(user_query):
|
|
86 |
log_message(f"Сгенерированный ответ: {response}")
|
87 |
return response
|
88 |
|
89 |
-
|
|
|
90 |
log_message("Начинаем процесс скрытия отрицательных комментариев.")
|
91 |
hidden_comments_data = hide_negative_comments(ACCESS_TOKEN)
|
92 |
log_message(f"Количество постов с скрытыми комментариями: {len(hidden_comments_data)}")
|
@@ -123,7 +124,7 @@ def process_comments(ACCESS_TOKEN):
|
|
123 |
classification = classify_comment(message)
|
124 |
log_message(f"Классификация комментария: {classification}")
|
125 |
if classification == "interrogative":
|
126 |
-
response_message = generate_response(message)
|
127 |
log_message(f"Ответ на комментарий: {response_message}")
|
128 |
success = reply_comment(comment_id=comment['id'], message=response_message, token=ACCESS_TOKEN)
|
129 |
if success:
|
@@ -136,7 +137,8 @@ def process_comments(ACCESS_TOKEN):
|
|
136 |
processed_posts.append({
|
137 |
'post_id': post_id,
|
138 |
'post_message': post_message,
|
139 |
-
'hidden_comments': next(
|
|
|
140 |
'replies': post_replies
|
141 |
})
|
142 |
|
@@ -150,22 +152,27 @@ with gr.Blocks() as demo:
|
|
150 |
with gr.Tab("Главная страница"):
|
151 |
gr.Markdown("# Facebook Comment Filter")
|
152 |
token_input = gr.Textbox(label="Access Token")
|
|
|
153 |
output_main = gr.JSON()
|
154 |
process_btn = gr.Button("Процессировать комментарии")
|
155 |
-
process_btn.click(
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
|
|
|
|
|
|
|
|
165 |
|
166 |
if __name__ == "__main__":
|
167 |
demo.launch(
|
168 |
debug=True,
|
169 |
server_port=7860,
|
170 |
server_name="0.0.0.0",
|
171 |
-
)
|
|
|
1 |
import os
|
|
|
2 |
import time
|
3 |
+
from datetime import datetime
|
4 |
+
|
5 |
import gradio as gr
|
6 |
import requests
|
7 |
from langchain.prompts import ChatPromptTemplate
|
8 |
from langchain_community.llms import Ollama
|
|
|
|
|
9 |
|
10 |
+
from func_ai import classify_comment, VECTOR_API_URL
|
11 |
+
from func_facebook import get_page_id, get_unanswered_comments, reply_comment, hide_negative_comments
|
12 |
+
|
13 |
|
14 |
def log_message(message):
|
15 |
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
16 |
print(f"[{timestamp}] {message}")
|
17 |
|
18 |
+
|
19 |
# Wait for the server to start
|
20 |
time.sleep(10)
|
21 |
llm = Ollama(model="llama3.1")
|
|
|
41 |
|
42 |
"""
|
43 |
|
44 |
+
|
45 |
def delete_faiss_index():
|
46 |
log_message("Удаляем FAISS индекс.")
|
47 |
response = requests.delete(f"{VECTOR_API_URL}/delete_index/")
|
48 |
+
|
49 |
if response.status_code == 200:
|
50 |
log_message("FAISS индекс успешно удален.")
|
51 |
return "Faiss успешно удален."
|
|
|
74 |
log_message(f"Ошибка при загрузке файла: {response.json().get('detail')}")
|
75 |
return f"Ошибка: {response.json().get('detail')}"
|
76 |
|
77 |
+
|
78 |
+
def generate_response(user_query, context):
|
79 |
log_message(f"Генерация ответа на запрос: {user_query}")
|
80 |
prompt = ChatPromptTemplate.from_template(template)
|
81 |
|
|
|
|
|
|
|
82 |
log_message(f"Контекст из базы данных: {context[:100]}...")
|
83 |
full_prompt = prompt.format(context=context, input=user_query)
|
84 |
|
|
|
86 |
log_message(f"Сгенерированный ответ: {response}")
|
87 |
return response
|
88 |
|
89 |
+
|
90 |
+
def process_comments(ACCESS_TOKEN, user_context):
|
91 |
log_message("Начинаем процесс скрытия отрицательных комментариев.")
|
92 |
hidden_comments_data = hide_negative_comments(ACCESS_TOKEN)
|
93 |
log_message(f"Количество постов с скрытыми комментариями: {len(hidden_comments_data)}")
|
|
|
124 |
classification = classify_comment(message)
|
125 |
log_message(f"Классификация комментария: {classification}")
|
126 |
if classification == "interrogative":
|
127 |
+
response_message = generate_response(message, context=user_context)
|
128 |
log_message(f"Ответ на комментарий: {response_message}")
|
129 |
success = reply_comment(comment_id=comment['id'], message=response_message, token=ACCESS_TOKEN)
|
130 |
if success:
|
|
|
137 |
processed_posts.append({
|
138 |
'post_id': post_id,
|
139 |
'post_message': post_message,
|
140 |
+
'hidden_comments': next(
|
141 |
+
(item['hidden_comments'] for item in hidden_comments_data if item['post_id'] == post_id), []),
|
142 |
'replies': post_replies
|
143 |
})
|
144 |
|
|
|
152 |
with gr.Tab("Главная страница"):
|
153 |
gr.Markdown("# Facebook Comment Filter")
|
154 |
token_input = gr.Textbox(label="Access Token")
|
155 |
+
context_input = gr.Textbox(label="Контекст") # Добавлено текстовое поле для ввода контекста
|
156 |
output_main = gr.JSON()
|
157 |
process_btn = gr.Button("Процессировать комментарии")
|
158 |
+
process_btn.click(
|
159 |
+
process_comments,
|
160 |
+
inputs=[token_input, context_input], # Обновлено: добавлен context_input
|
161 |
+
outputs=output_main
|
162 |
+
)
|
163 |
+
|
164 |
+
# with gr.Tab("Загрузить данные"):
|
165 |
+
# gr.Markdown("# Отправь excel файл")
|
166 |
+
# file_input = gr.File(label="Загрузите Excel файл (.xlsx)")
|
167 |
+
# output_second = gr.Text()
|
168 |
+
# second_page_btn = gr.Button("Отправить файл")
|
169 |
+
# second_page_btn.click(upload_file_vdb, inputs=file_input, outputs=output_second)
|
170 |
+
# delete_btn = gr.Button("Удалить FAISS индекс")
|
171 |
+
# delete_btn.click(delete_faiss_index, outputs=output_second)
|
172 |
|
173 |
if __name__ == "__main__":
|
174 |
demo.launch(
|
175 |
debug=True,
|
176 |
server_port=7860,
|
177 |
server_name="0.0.0.0",
|
178 |
+
)
|