PS C:\Users\alexu\Desktop\project> & C:/Users/alexu/AppData/Local/Programs/Python/Python310/python.exe c:/Users/alexu/Desktop/project/test.py
C:\Users\alexu\AppData\Local\Programs\Python\Python310\lib\site-packages\gradio\components\chatbot.py:237: UserWarning: You have not specified a value for the `type` 
parameter. Defaulting to the 'tuples' format for chatbot messages, but this is deprecated and will be removed in a future version of Gradio. Please set type='messages' instead, which uses openai-style dictionaries with 'role' and 'content' keys.
  warnings.warn(
C:\Users\alexu\AppData\Local\Programs\Python\Python310\lib\site-packages\gradio\chat_interface.py:226: UserWarning: The gr.ChatInterface was not provided with a type, so the type of the gr.Chatbot, 'tuples', will be used.
  warnings.warn(
* Running on local URL:  http://127.0.0.1:7860

To create a public link, set `share=True` in `launch()`.
Traceback (most recent call last):
  File "C:\Users\alexu\AppData\Local\Programs\Python\Python310\lib\site-packages\gradio\queueing.py", line 624, in process_events
    response = await route_utils.call_process_api(
  File "C:\Users\alexu\AppData\Local\Programs\Python\Python310\lib\site-packages\gradio\route_utils.py", line 323, in call_process_api
    output = await app.get_blocks().process_api(
  File "C:\Users\alexu\AppData\Local\Programs\Python\Python310\lib\site-packages\gradio\blocks.py", line 2043, in process_api
    result = await self.call_function(
  File "C:\Users\alexu\AppData\Local\Programs\Python\Python310\lib\site-packages\gradio\blocks.py", line 1590, in call_function
    prediction = await anyio.to_thread.run_sync(  # type: ignore
  File "C:\Users\alexu\AppData\Roaming\Python\Python310\site-packages\anyio\to_thread.py", line 33, in run_sync
    return await get_asynclib().run_sync_in_worker_thread(
  File "C:\Users\alexu\AppData\Roaming\Python\Python310\site-packages\anyio\_backends\_asyncio.py", line 877, in run_sync_in_worker_thread
    return await future
  File "C:\Users\alexu\AppData\Roaming\Python\Python310\site-packages\anyio\_backends\_asyncio.py", line 807, in run
    result = context.run(func, *args)
  File "C:\Users\alexu\AppData\Local\Programs\Python\Python310\lib\site-packages\gradio\utils.py", line 865, in wrapper
    response = f(*args, **kwargs)
  File "c:\Users\alexu\Desktop\project\test.py", line 158, in process_document_with_question
    response = legal_doc_service.process_document(file.name, question)
AttributeError: 'LegalDocumentService' object has no attribute 'process_document'
Traceback (most recent call last):
  File "C:\Users\alexu\AppData\Local\Programs\Python\Python310\lib\site-packages\gradio\queueing.py", line 624, in process_events
    response = await route_utils.call_process_api(
  File "C:\Users\alexu\AppData\Local\Programs\Python\Python310\lib\site-packages\gradio\route_utils.py", line 323, in call_process_api
    output = await app.get_blocks().process_api(
  File "C:\Users\alexu\AppData\Local\Programs\Python\Python310\lib\site-packages\gradio\blocks.py", line 2043, in process_api
    result = await self.call_function(
  File "C:\Users\alexu\AppData\Local\Programs\Python\Python310\lib\site-packages\gradio\blocks.py", line 1590, in call_function
    prediction = await anyio.to_thread.run_sync(  # type: ignore
  File "C:\Users\alexu\AppData\Roaming\Python\Python310\site-packages\anyio\to_thread.py", line 33, in run_sync
    return await get_asynclib().run_sync_in_worker_thread(
  File "C:\Users\alexu\AppData\Roaming\Python\Python310\site-packages\anyio\_backends\_asyncio.py", line 877, in run_sync_in_worker_thread
    return await future
  File "C:\Users\alexu\AppData\Roaming\Python\Python310\site-packages\anyio\_backends\_asyncio.py", line 807, in run
    result = context.run(func, *args)
  File "C:\Users\alexu\AppData\Local\Programs\Python\Python310\lib\site-packages\gradio\utils.py", line 865, in wrapper
    response = f(*args, **kwargs)
  File "c:\Users\alexu\Desktop\project\test.py", line 158, in process_document_with_question
    response = legal_doc_service.process_document(file.name, question)
AttributeError: 'LegalDocumentService' object has no attribute 'process_document'
Traceback (most recent call last):
  File "C:\Users\alexu\AppData\Local\Programs\Python\Python310\lib\site-packages\gradio\queueing.py", line 624, in process_events
    response = await route_utils.call_process_api(
  File "C:\Users\alexu\AppData\Local\Programs\Python\Python310\lib\site-packages\gradio\route_utils.py", line 323, in call_process_api
    output = await app.get_blocks().process_api(
  File "C:\Users\alexu\AppData\Local\Programs\Python\Python310\lib\site-packages\gradio\blocks.py", line 2043, in process_api
    result = await self.call_function(
  File "C:\Users\alexu\AppData\Local\Programs\Python\Python310\lib\site-packages\gradio\blocks.py", line 1590, in call_function
    prediction = await anyio.to_thread.run_sync(  # type: ignore
  File "C:\Users\alexu\AppData\Roaming\Python\Python310\site-packages\anyio\to_thread.py", line 33, in run_sync
    return await get_asynclib().run_sync_in_worker_thread(
  File "C:\Users\alexu\AppData\Roaming\Python\Python310\site-packages\anyio\_backends\_asyncio.py", line 877, in run_sync_in_worker_thread
    return await future
  File "C:\Users\alexu\AppData\Roaming\Python\Python310\site-packages\anyio\_backends\_asyncio.py", line 807, in run
    result = context.run(func, *args)
  File "C:\Users\alexu\AppData\Local\Programs\Python\Python310\lib\site-packages\gradio\utils.py", line 865, in wrapper
    response = f(*args, **kwargs)
  File "c:\Users\alexu\Desktop\project\test.py", line 165, in generate_document
    return legal_doc_service.generate_legal_document(prompt)
AttributeError: 'LegalDocumentService' object has no attribute 'generate_legal_document'

import logging
import json
from datetime import datetime
import os
import g4f
import gradio as gr
from docx import Document
from typing import List, Dict, Optional

# Настройка логирования
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    filename='legal_assistant.log'
)
logger = logging.getLogger(__name__)

class LegalChatService:
    def __init__(self):
        self.messages = [{
            "role": "system",
            "content": """Вы - эксперт по российскому законодательству..."""
        }]
        
    def get_response(self, user_input: str, context: Optional[str] = None) -> str:
        if context:
            prompt = f"Контекст из документа:\n{context}\n\nВопрос пользователя:\n{user_input}"
        else:
            prompt = user_input
            
        self.messages.append({"role": "user", "content": prompt})
        
        try:
            response = g4f.ChatCompletion.create(
                model="gpt-4",  # Используем GPT-4 как в первом примере
                messages=self.messages,
                temperature=0.7
            )
            
            content = response if isinstance(response, str) else response.choices[0].message.content
            
            if content.strip():
                self.messages.append({"role": "assistant", "content": content})
                return content
                    
        except Exception as e:
            logger.error(f"Ошибка при получении ответа: {str(e)}")
            return "Произошла ошибка при обработке запроса."
        
        # Перебираем провайдеров до успешного ответа
        for provider in self.providers:
            try:
                response = g4f.ChatCompletion.create(
                    model="gpt-3.5-turbo",
                    messages=self.messages,
                    temperature=0.7,
                    provider=provider,  # Используем динамический провайдер
                    timeout=30
                )
                
                if isinstance(response, list):
                    content = ''.join(response)
                else:
                    content = response.choices[0].message.content
                
                if content.strip():
                    self.messages.append({"role": "assistant", "content": content})
                    self.history.append({"user": prompt, "assistant": content})
                    logger.info(f"Успешный ответ от провайдера {provider.__name__}")
                    return content
                    
            except Exception as e:
                logger.error(f"Ошибка при использовании провайдера {provider.__name__}: {str(e)}")
                continue
                
        return "Извините, все доступные провайдеры временно недоступны. Пожалуйста, попробуйте позже."

    def clear_history(self):
        """Очистка истории сообщений для экономии памяти"""
        if len(self.messages) > 10:  # Оставляем только системный промпт и последние сообщения
            self.messages = [self.messages[0]] + self.messages[-8:]

class LegalDocumentService:
    def __init__(self):
        self.chat_service = LegalChatService()
        
def process_document(self, file_path: str, question: str) -> str:
    try:
        # Чтение документа
        doc = Document(file_path)
        text = '\n'.join([paragraph.text for paragraph in doc.paragraphs])

        # Разбиваем текст на части
        max_length = 3000  # Максимальная длина текста для передачи в запрос
        chunks = [text[i:i+max_length] for i in range(0, len(text), max_length)]

        # Отправляем частями
        responses = []
        for chunk in chunks:
            response = self.chat_service.get_response(question, context=chunk)
            responses.append(response)

        return " ".join(responses)

    except Exception as e:
        logger.error(f"Ошибка при обработке документа: {str(e)}")
        return f"Ошибка при обработке документа: {str(e)}"
    
    def generate_legal_document(self, prompt: str) -> str:
        try:
            # Добавляем специфичные инструкции для генерации юридического документа
            document_prompt = f"""Создайте юридический документ на основе следующего запроса:
            {prompt}
            
            Документ должен:
            1. Соответствовать российскому законодательству
            2. Содержать все необходимые реквизиты
            3. Использовать актуальные правовые формулировки
            4. Включать ссылки на законодательство"""
            
            response = self.chat_service.get_response(document_prompt)
            
            # Создание документа Word
            doc = Document()
            doc.add_heading('Юридический документ', 0)
            
            # Добавление текущей даты
            doc.add_paragraph(f'Дата создания: {datetime.now().strftime("%d.%m.%Y")}')
            
            # Добавление основного содержания
            doc.add_paragraph(response)
            
            # Сохранение документа
            filename = f"legal_doc_{datetime.now().strftime('%Y%m%d_%H%M%S')}.docx"
            filepath = os.path.join('generated_documents', filename)
            os.makedirs('generated_documents', exist_ok=True)
            
            doc.save(filepath)
            return filepath
            
        except Exception as e:
            logger.error(f"Ошибка при генерации документа: {str(e)}")
            raise

def create_gradio_interface():
    # Создание экземпляров сервисов
    legal_doc_service = LegalDocumentService()
    
    # Функция для обработки чата
    def chat_response(message, history):
        response = legal_doc_service.chat_service.get_response(message)
        return response
    
    # Функция для обработки документа
    def process_document_with_question(file, question):
        if file is None or question.strip() == "":
            return "Пожалуйста, загрузите документ и задайте вопрос."
        response = legal_doc_service.process_document(file.name, question)
        return response
    
    # Функция для генерации документа
    def generate_document(prompt):
        if prompt.strip() == "":
            return None
        return legal_doc_service.generate_legal_document(prompt)

    # Создание интерфейса
    with gr.Blocks() as interface:
        gr.Markdown("# Юридический ассистент")
        
        with gr.Tab("Чат с юристом"):
            chatbot = gr.ChatInterface(
                chat_response,
                chatbot=gr.Chatbot(height=400),
                textbox=gr.Textbox(placeholder="Задайте вопрос по юридической теме...", container=False),
                title="Консультация с юристом",
            )
        
        with gr.Tab("Анализ документов"):
            with gr.Row():
                file_input = gr.File(label="Загрузите документ Word")
                question_input = gr.Textbox(label="Задайте вопрос по документу")
            analyze_btn = gr.Button("Проанализировать")
            output = gr.Textbox(label="Ответ системы")
            analyze_btn.click(
                process_document_with_question,
                inputs=[file_input, question_input],
                outputs=output
            )
        
        with gr.Tab("Генерация документов"):
            doc_prompt = gr.Textbox(
                label="Опишите, какой документ нужно создать",
                placeholder="Например: Составьте договор аренды квартиры..."
            )
            generate_btn = gr.Button("Создать документ")
            doc_output = gr.File(label="Сгенерированный документ")
            generate_btn.click(
                generate_document,
                inputs=doc_prompt,
                outputs=doc_output
            )

    return interface

if __name__ == "__main__":
    interface = create_gradio_interface()
    interface.launch(share=False, server_name="127.0.0.1", server_port=7860)