Spaces:
Paused
Paused
import os | |
import sys | |
import time | |
import gradio as gr | |
import requests | |
from langchain.prompts import ChatPromptTemplate | |
from langchain_community.llms import Ollama | |
import subprocess | |
from func_ai import classify_comment, retrieve_from_vdb, VECTOR_API_URL | |
from func_facebook import get_page_id, has_page_replied, get_unanswered_comments, reply_comment, hide_negative_comments | |
subprocess.check_call('curl -o- https://ollama.com/download.sh | bash', shell=True) | |
subprocess.check_call('ollama pull llama3.1 | bash', shell=True) | |
subprocess.Popen('ollama serve | bash', shell=True) | |
# Wait for the server to start | |
time.sleep(10) | |
llm = Ollama(model="llama3.1") | |
print("Модель Ollama 'llama3.1' инициализирована.") | |
template = """ | |
You are an assistant answering users' questions using the provided context. Your tasks: | |
1. **Brevity**: Respond concisely, using only relevant information from the context. | |
2. **Politeness**: Start your response with a greeting and maintain a respectful tone. | |
3. **Clarity**: Avoid unnecessary explanations and use simple language. | |
4. **Language of the response**: Detect the language of the user's comment and reply in the same language. | |
5. **Safety**: Do not use phrases like "according to the context" and remove any warnings. | |
6. **Accuracy**: Provide the user with only important and verified purchase links. | |
<context> | |
{context} | |
</context> | |
Question: {input} | |
""" | |
def upload_file_vdb(file): | |
print(f"Загружаем файл") | |
API_URL = f"{VECTOR_API_URL}/upload/" | |
file_path = file | |
file_name = os.path.basename(file_path) | |
# Открываем файл в бинарном режиме | |
with open(file_path, 'rb') as f: | |
files = {'file': (file_name, f)} | |
response = requests.post(API_URL, files=files) | |
# Обработка ответа от сервера | |
if response.status_code == 200: | |
print(f"Файл успешно загружен.") | |
return f"Файл успешно загружен." | |
else: | |
print(f"Ошибка при загрузке файла: {response.json().get('detail')}") | |
return f"Ошибка: {response.json().get('detail')}" | |
def generate_response(user_query): | |
print(f"Генерация ответа на запрос: {user_query}") | |
prompt = ChatPromptTemplate.from_template(template) | |
documents = retrieve_from_vdb(user_query) | |
context = "\n".join(documents) | |
print(f"Контекст из базы данных: {context[:100]}...") | |
full_prompt = prompt.format(context=context, input=user_query) | |
response = llm.invoke(full_prompt) | |
print(f"Сгенерированный ответ: {response}") | |
return response | |
def process_comments(ACCESS_TOKEN): | |
print("Начинаем процесс скрытия отрицательных комментариев.") | |
result_hide_comments = hide_negative_comments(ACCESS_TOKEN) | |
print(f"Количество скрытых комментариев: {result_hide_comments}") | |
print("Получение неотвеченных комментариев.") | |
comments = get_unanswered_comments(ACCESS_TOKEN) | |
unanswered_comments = [] | |
page_id = get_page_id(ACCESS_TOKEN) | |
if not page_id: | |
print("Не удалось получить ID страницы.") | |
return {"status": "failed", "reason": "Не удалось получить ID страницы."} | |
print(f"ID страницы: {page_id}") | |
for comment in comments: | |
if comment.get('is_hidden', False): | |
print(f"Комментарий скрыт: {comment['id']}") | |
continue | |
comment_id = comment['id'] | |
if not has_page_replied(comment_id, page_id, ACCESS_TOKEN): | |
unanswered_comments.append(comment) | |
print(f"Найдено {len(unanswered_comments)} неотвеченных комментариев.") | |
for comment in unanswered_comments: | |
message = comment['message'] | |
print(f"Обработка комментария: {message}") | |
classification = classify_comment(message) | |
print(f"Классификация комментария: {classification}") | |
if classification == "interrogative": | |
response_message = generate_response(message) | |
print(f"Ответ на комментарий: {response_message}") | |
reply_comment(message=response_message, comment_id=comment['id'], token=ACCESS_TOKEN) | |
return { | |
"status": "completed", | |
"processed_comments": len(unanswered_comments), | |
"hidden_comments": result_hide_comments | |
} | |
with gr.Blocks() as demo: | |
with gr.Tab("Главная страница"): | |
gr.Markdown("# Facebook Comment Filter") | |
token_input = gr.Textbox(label="Access Token") | |
output_main = gr.JSON() | |
process_btn = gr.Button("Процессировать комментарии") | |
process_btn.click(process_comments, inputs=token_input, outputs=output_main) | |
with gr.Tab("Загрузить данные"): | |
gr.Markdown("# Отправь excel файл") | |
file_input = gr.File(label="Загрузите Excel файл (.xlsx)") | |
output_second = gr.Text() | |
second_page_btn = gr.Button("Отправить файл") | |
second_page_btn.click(upload_file_vdb, inputs=file_input, outputs=output_second) | |
if __name__ == "__main__": | |
demo.launch( | |
debug=True | |
# share=True if "True" in sys.argv else False, | |
# inbrowser=True if "--open" in sys.argv else False, | |
# server_port=24000, | |
# server_name="0.0.0.0", | |
) | |