Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
@@ -1,14 +1,11 @@
|
|
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
|
11 |
-
|
12 |
|
13 |
|
14 |
def log_message(message):
|
@@ -16,8 +13,6 @@ def log_message(message):
|
|
16 |
print(f"[{timestamp}] {message}")
|
17 |
|
18 |
|
19 |
-
# Wait for the server to start
|
20 |
-
time.sleep(10)
|
21 |
llm = Ollama(model="llama3.1")
|
22 |
log_message("Модель Ollama 'llama3.1' инициализирована.")
|
23 |
|
@@ -42,57 +37,72 @@ Question: {input}
|
|
42 |
"""
|
43 |
|
44 |
|
45 |
-
def
|
46 |
-
log_message("
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
#
|
57 |
-
# def upload_file_vdb(file):
|
58 |
-
# log_message("Загружаем файл")
|
59 |
-
# API_URL = f"{VECTOR_API_URL}/upload/"
|
60 |
-
#
|
61 |
-
# file_path = file
|
62 |
-
# file_name = os.path.basename(file_path)
|
63 |
-
#
|
64 |
-
# # Открываем файл в бинарном режиме
|
65 |
-
# with open(file_path, 'rb') as f:
|
66 |
-
# files = {'file': (file_name, f)}
|
67 |
-
# response = requests.post(API_URL, files=files)
|
68 |
-
#
|
69 |
-
# # Обработка ответа от сервера
|
70 |
-
# if response.status_code == 200:
|
71 |
-
# log_message("Файл успешно загружен.")
|
72 |
-
# return "Файл успешно загружен."
|
73 |
-
# else:
|
74 |
-
# log_message(f"Ошибка при загрузке файла: {response.json().get('detail')}")
|
75 |
-
# return f"Ошибка: {response.json().get('detail')}"
|
76 |
|
77 |
|
78 |
def generate_responses(user_queries, context):
|
79 |
log_message(f"Генерация ответов на {len(user_queries)} запросов")
|
80 |
prompt = ChatPromptTemplate.from_template(template)
|
81 |
-
|
82 |
# Формируем список полных промптов для каждого запроса
|
83 |
full_prompts = [prompt.format(context=context, input=query) for query in user_queries]
|
84 |
-
|
85 |
# Используем llm.batch для получения ответов на все промпты
|
86 |
responses = llm.batch(full_prompts)
|
87 |
log_message("Ответы сгенерированы.")
|
88 |
return responses
|
89 |
|
90 |
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
96 |
log_message(f"Количество постов с скрытыми комментариями: {len(hidden_comments_data)}")
|
97 |
|
98 |
log_message("Получение неотвеченных комментариев.")
|
@@ -105,8 +115,7 @@ def process_comments(ACCESS_TOKEN, user_context):
|
|
105 |
|
106 |
log_message(f"ID страницы: {page_id}")
|
107 |
|
108 |
-
|
109 |
-
processed_comment_ids = set()
|
110 |
|
111 |
all_comments = []
|
112 |
all_comment_ids = []
|
@@ -115,7 +124,7 @@ def process_comments(ACCESS_TOKEN, user_context):
|
|
115 |
|
116 |
for post_data in posts_with_unanswered_comments:
|
117 |
post_id = post_data['post_id']
|
118 |
-
post_message = post_data['post_message']
|
119 |
unanswered_comments = post_data['unanswered_comments']
|
120 |
|
121 |
for comment in unanswered_comments:
|
@@ -159,33 +168,29 @@ def process_comments(ACCESS_TOKEN, user_context):
|
|
159 |
return result_data
|
160 |
|
161 |
|
162 |
-
|
163 |
with gr.Blocks() as demo:
|
|
|
|
|
|
|
|
|
|
|
164 |
with gr.Tab("Главная страница"):
|
165 |
-
gr.Markdown("# Facebook Comment Filter")
|
166 |
-
token_input = gr.Textbox(label="Access Token")
|
167 |
-
context_input = gr.Textbox(label="Контекст") # Добавлено текстовое поле для ввода контекста
|
168 |
output_main = gr.JSON()
|
169 |
process_btn = gr.Button("Процессировать комментарии")
|
170 |
-
process_btn.click(
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
# second_page_btn = gr.Button("Отправить файл")
|
181 |
-
# second_page_btn.click(upload_file_vdb, inputs=file_input, outputs=output_second)
|
182 |
-
# delete_btn = gr.Button("Удалить FAISS индекс")
|
183 |
-
# delete_btn.click(delete_faiss_index, outputs=output_second)
|
184 |
|
185 |
if __name__ == "__main__":
|
186 |
demo.launch(
|
187 |
debug=True,
|
188 |
server_port=7860,
|
189 |
-
server_name="0.0.0.0"
|
190 |
-
|
191 |
)
|
|
|
|
|
|
|
1 |
from datetime import datetime
|
2 |
+
|
3 |
import gradio as gr
|
|
|
4 |
from langchain.prompts import ChatPromptTemplate
|
5 |
from langchain_community.llms import Ollama
|
6 |
|
7 |
+
from func_facebook import get_page_id, get_unanswered_comments, reply_comment, \
|
8 |
+
process_negative_comments, process_negative_comments_in_post, get_comments, has_page_replied
|
9 |
|
10 |
|
11 |
def log_message(message):
|
|
|
13 |
print(f"[{timestamp}] {message}")
|
14 |
|
15 |
|
|
|
|
|
16 |
llm = Ollama(model="llama3.1")
|
17 |
log_message("Модель Ollama 'llama3.1' инициализирована.")
|
18 |
|
|
|
37 |
"""
|
38 |
|
39 |
|
40 |
+
def generate_response(user_query, context):
|
41 |
+
log_message(f"Генерация ответа на запрос: {user_query}")
|
42 |
+
prompt = ChatPromptTemplate.from_template(template)
|
43 |
+
|
44 |
+
log_message(f"Контекст из базы данных: {context[:100]}...")
|
45 |
+
full_prompt = prompt.format(context=context, input=user_query)
|
46 |
+
|
47 |
+
response = llm.invoke(full_prompt)
|
48 |
+
log_message(f"Сгенерированный ответ: {response}")
|
49 |
+
return response
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
50 |
|
51 |
|
52 |
def generate_responses(user_queries, context):
|
53 |
log_message(f"Генерация ответов на {len(user_queries)} запросов")
|
54 |
prompt = ChatPromptTemplate.from_template(template)
|
55 |
+
|
56 |
# Формируем список полных промптов для каждого запроса
|
57 |
full_prompts = [prompt.format(context=context, input=query) for query in user_queries]
|
58 |
+
|
59 |
# Используем llm.batch для получения ответов на все промпты
|
60 |
responses = llm.batch(full_prompts)
|
61 |
log_message("Ответы сгенерированы.")
|
62 |
return responses
|
63 |
|
64 |
|
65 |
+
def process_single_post(post_id, token, action, user_context):
|
66 |
+
log_message(f"Начинаем обработку поста {post_id}")
|
67 |
+
page_id = get_page_id(token)
|
68 |
+
full_post_id = page_id + "_" + post_id
|
69 |
+
# Шаг 1: Скрытие негативных комментариев
|
70 |
+
processed_comments = process_negative_comments_in_post(full_post_id, token, action)
|
71 |
+
|
72 |
+
# Шаг 2: Получение неотвеченных комментариев
|
73 |
+
comments = get_comments(full_post_id, token)
|
74 |
+
unanswered_comments = []
|
75 |
+
for comment in comments:
|
76 |
+
comment_id = comment['id']
|
77 |
+
if not comment.get('is_hidden', False) and not has_page_replied(comment_id, get_page_id(token), token):
|
78 |
+
unanswered_comments.append(comment)
|
79 |
+
|
80 |
+
log_message(f"Найдено {len(unanswered_comments)} неотвеченных комментариев.")
|
81 |
+
|
82 |
+
# Шаг 3: Ответ на неотвеченные комментарии
|
83 |
+
replies = []
|
84 |
+
for comment in unanswered_comments:
|
85 |
+
message = comment['message']
|
86 |
+
response_message = generate_response(message, context=user_context)
|
87 |
+
if reply_comment(comment_id=comment['id'], message=response_message, token=token):
|
88 |
+
replies.append({
|
89 |
+
'comment_id': comment['id'],
|
90 |
+
'comment_message': comment['message'],
|
91 |
+
'reply_message': response_message
|
92 |
+
})
|
93 |
+
|
94 |
+
return [{
|
95 |
+
"status": "completed",
|
96 |
+
"post_id": full_post_id,
|
97 |
+
"hidden_or_deleted_comments": processed_comments,
|
98 |
+
"replies": replies
|
99 |
+
}]
|
100 |
+
|
101 |
+
|
102 |
+
def process_comments(ACCESS_TOKEN, action, user_context):
|
103 |
+
log_message(f"Selected action: {action}")
|
104 |
+
|
105 |
+
hidden_comments_data = process_negative_comments(ACCESS_TOKEN, action)
|
106 |
log_message(f"Количество постов с скрытыми комментариями: {len(hidden_comments_data)}")
|
107 |
|
108 |
log_message("Получение неотвеченных комментариев.")
|
|
|
115 |
|
116 |
log_message(f"ID страницы: {page_id}")
|
117 |
|
118 |
+
processed_comment_ids = set() # Отслеживание обработанных комментариев
|
|
|
119 |
|
120 |
all_comments = []
|
121 |
all_comment_ids = []
|
|
|
124 |
|
125 |
for post_data in posts_with_unanswered_comments:
|
126 |
post_id = post_data['post_id']
|
127 |
+
# post_message = post_data['post_message']
|
128 |
unanswered_comments = post_data['unanswered_comments']
|
129 |
|
130 |
for comment in unanswered_comments:
|
|
|
168 |
return result_data
|
169 |
|
170 |
|
|
|
171 |
with gr.Blocks() as demo:
|
172 |
+
gr.Markdown("# Facebook Comment Filter")
|
173 |
+
token_input = gr.Textbox(label="Access Token")
|
174 |
+
context_input = gr.Textbox(label="Контекст")
|
175 |
+
radio = gr.Radio(["Hide", "Delete"], info="Choose hide or delete comments", show_label=False)
|
176 |
+
|
177 |
with gr.Tab("Главная страница"):
|
|
|
|
|
|
|
178 |
output_main = gr.JSON()
|
179 |
process_btn = gr.Button("Процессировать комментарии")
|
180 |
+
process_btn.click(process_comments, inputs=[token_input, radio, context_input],
|
181 |
+
# Обновлено: добавлен context_input
|
182 |
+
outputs=output_main)
|
183 |
+
|
184 |
+
with gr.Tab("Обработать пост"):
|
185 |
+
post_id = gr.Textbox(label="Post ID")
|
186 |
+
output = gr.JSON()
|
187 |
+
process_post_btn = gr.Button("Обработать пост")
|
188 |
+
process_post_btn.click(process_single_post, inputs=[post_id, token_input, radio, context_input],
|
189 |
+
outputs=output)
|
|
|
|
|
|
|
|
|
190 |
|
191 |
if __name__ == "__main__":
|
192 |
demo.launch(
|
193 |
debug=True,
|
194 |
server_port=7860,
|
195 |
+
server_name="0.0.0.0"
|
|
|
196 |
)
|