Spaces:
Paused
Paused
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import sys
|
3 |
+
|
4 |
+
import gradio as gr
|
5 |
+
import requests
|
6 |
+
from langchain.prompts import ChatPromptTemplate
|
7 |
+
from langchain_community.llms import Ollama
|
8 |
+
|
9 |
+
from func_ai import classify_comment, retrieve_from_vdb, VECTOR_API_URL
|
10 |
+
from func_facebook import get_page_id, has_page_replied, get_unanswered_comments, reply_comment, hide_negative_comments
|
11 |
+
|
12 |
+
os.system('curl -o- https://ollama.com/download.sh | bash')
|
13 |
+
os.system('ollama pull llama3.1')
|
14 |
+
|
15 |
+
llm = Ollama(model="llama3.1")
|
16 |
+
print("Модель Ollama 'llama3.1' инициализирована.")
|
17 |
+
|
18 |
+
template = """
|
19 |
+
You are an assistant answering users' questions using the provided context. Your tasks:
|
20 |
+
|
21 |
+
1. **Brevity**: Respond concisely, using only relevant information from the context.
|
22 |
+
2. **Politeness**: Start your response with a greeting and maintain a respectful tone.
|
23 |
+
3. **Clarity**: Avoid unnecessary explanations and use simple language.
|
24 |
+
4. **Language of the response**: Detect the language of the user's comment and reply in the same language.
|
25 |
+
5. **Safety**: Do not use phrases like "according to the context" and remove any warnings.
|
26 |
+
6. **Accuracy**: Provide the user with only important and verified purchase links.
|
27 |
+
|
28 |
+
|
29 |
+
<context>
|
30 |
+
{context}
|
31 |
+
</context>
|
32 |
+
|
33 |
+
Question: {input}
|
34 |
+
"""
|
35 |
+
|
36 |
+
|
37 |
+
def upload_file_vdb(file):
|
38 |
+
print(f"Загружаем файл")
|
39 |
+
API_URL = f"{VECTOR_API_URL}/upload/"
|
40 |
+
|
41 |
+
file_path = file
|
42 |
+
file_name = os.path.basename(file_path)
|
43 |
+
|
44 |
+
# Открываем файл в бинарном режиме
|
45 |
+
with open(file_path, 'rb') as f:
|
46 |
+
files = {'file': (file_name, f)}
|
47 |
+
response = requests.post(API_URL, files=files)
|
48 |
+
|
49 |
+
# Обработка ответа от сервера
|
50 |
+
if response.status_code == 200:
|
51 |
+
print(f"Файл успешно загружен.")
|
52 |
+
return f"Файл успешно загружен."
|
53 |
+
else:
|
54 |
+
print(f"Ошибка при загрузке файла: {response.json().get('detail')}")
|
55 |
+
return f"Ошибка: {response.json().get('detail')}"
|
56 |
+
|
57 |
+
|
58 |
+
def generate_response(user_query):
|
59 |
+
print(f"Генерация ответа на запрос: {user_query}")
|
60 |
+
prompt = ChatPromptTemplate.from_template(template)
|
61 |
+
|
62 |
+
documents = retrieve_from_vdb(user_query)
|
63 |
+
context = "\n".join(documents)
|
64 |
+
|
65 |
+
print(f"Контекст из базы данных: {context[:100]}...")
|
66 |
+
full_prompt = prompt.format(context=context, input=user_query)
|
67 |
+
|
68 |
+
response = llm.invoke(full_prompt)
|
69 |
+
print(f"Сгенерированный ответ: {response}")
|
70 |
+
return response
|
71 |
+
|
72 |
+
|
73 |
+
def process_comments(ACCESS_TOKEN):
|
74 |
+
print("Начинаем процесс скрытия отрицательных комментариев.")
|
75 |
+
result_hide_comments = hide_negative_comments(ACCESS_TOKEN)
|
76 |
+
print(f"Количество скрытых комментариев: {result_hide_comments}")
|
77 |
+
|
78 |
+
print("Получение неотвеченных комментариев.")
|
79 |
+
comments = get_unanswered_comments(ACCESS_TOKEN)
|
80 |
+
unanswered_comments = []
|
81 |
+
page_id = get_page_id(ACCESS_TOKEN)
|
82 |
+
|
83 |
+
if not page_id:
|
84 |
+
print("Не удалось получить ID страницы.")
|
85 |
+
return {"status": "failed", "reason": "Не удалось получить ID страницы."}
|
86 |
+
|
87 |
+
print(f"ID страницы: {page_id}")
|
88 |
+
|
89 |
+
for comment in comments:
|
90 |
+
if comment.get('is_hidden', False):
|
91 |
+
print(f"Комментарий скрыт: {comment['id']}")
|
92 |
+
continue
|
93 |
+
comment_id = comment['id']
|
94 |
+
if not has_page_replied(comment_id, page_id, ACCESS_TOKEN):
|
95 |
+
unanswered_comments.append(comment)
|
96 |
+
|
97 |
+
print(f"Найдено {len(unanswered_comments)} неотвеченных комментариев.")
|
98 |
+
|
99 |
+
for comment in unanswered_comments:
|
100 |
+
message = comment['message']
|
101 |
+
print(f"Обработка комментария: {message}")
|
102 |
+
classification = classify_comment(message)
|
103 |
+
print(f"Классификация комментария: {classification}")
|
104 |
+
if classification == "interrogative":
|
105 |
+
response_message = generate_response(message)
|
106 |
+
print(f"Ответ на комментарий: {response_message}")
|
107 |
+
reply_comment(message=response_message, comment_id=comment['id'], token=ACCESS_TOKEN)
|
108 |
+
|
109 |
+
return {
|
110 |
+
"status": "completed",
|
111 |
+
"processed_comments": len(unanswered_comments),
|
112 |
+
"hidden_comments": result_hide_comments
|
113 |
+
}
|
114 |
+
|
115 |
+
|
116 |
+
with gr.Blocks() as demo:
|
117 |
+
with gr.Tab("Главная страница"):
|
118 |
+
gr.Markdown("# Facebook Comment Filter")
|
119 |
+
token_input = gr.Textbox(label="Access Token")
|
120 |
+
output_main = gr.JSON()
|
121 |
+
process_btn = gr.Button("Процессировать комментарии")
|
122 |
+
process_btn.click(process_comments, inputs=token_input, outputs=output_main)
|
123 |
+
|
124 |
+
with gr.Tab("Загрузить данные"):
|
125 |
+
gr.Markdown("# Отправь excel файл")
|
126 |
+
file_input = gr.File(label="Загрузите Excel файл (.xlsx)")
|
127 |
+
output_second = gr.Text()
|
128 |
+
second_page_btn = gr.Button("Отправить файл")
|
129 |
+
second_page_btn.click(upload_file_vdb, inputs=file_input, outputs=output_second)
|
130 |
+
|
131 |
+
if __name__ == "__main__":
|
132 |
+
demo.launch(
|
133 |
+
debug=True
|
134 |
+
# share=True if "True" in sys.argv else False,
|
135 |
+
# inbrowser=True if "--open" in sys.argv else False,
|
136 |
+
# server_port=24000,
|
137 |
+
# server_name="0.0.0.0",
|
138 |
+
)
|