File size: 2,840 Bytes
dcc00b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import gradio as gr
import logging
from datetime import datetime
from analyzers.gemini_analyzer import GeminiAnalyzer
from analyzers.ner_analyzer import NERAnalyzer
from docling.document_converter import DocumentConverter

# Configuração de logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler(f'contract_analyzer_{datetime.now().strftime("%Y%m%d")}.log'),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

class ContractAnalyzer:
    def __init__(self):
        self.gemini_analyzer = GeminiAnalyzer()
        self.ner_analyzer = NERAnalyzer()
        self.document_converter = DocumentConverter()

    def analyze_contract(self, file, analysis_type: str):
        logger.info(f"Iniciando análise do arquivo usando {analysis_type}: {file.name}")
        
        try:
            result = self.document_converter.convert(file.name)
            document_text = result.document.export_to_markdown()
            
            if analysis_type == "Gemini":
                analysis_result = self.gemini_analyzer.analyze(document_text)
                output = self.gemini_analyzer.format_output(analysis_result)
            else:  # NER
                entities = self.ner_analyzer.extract_entities(document_text)
                representatives = self.ner_analyzer.extract_representatives(entities)
                output = self.ner_analyzer.format_output(representatives)
            
            return document_text, output
        
        except Exception as e:
            logger.error(f"Erro durante análise do contrato: {str(e)}")
            return "", f"Erro ao processar o arquivo: {str(e)}"

def create_interface():
    analyzer = ContractAnalyzer()
    try:
        logger.info("Iniciando configuração da interface Gradio")
        iface = gr.Interface(
            fn=analyzer.analyze_contract,
            inputs=[
                "file",
                gr.Radio(
                    choices=["Gemini", "NER"],
                    label="Tipo de Análise",
                    value="Gemini"
                )
            ],
            outputs=[
                gr.Textbox(label="Texto do Contrato"),
                gr.Textbox(label="Resultado da Análise")
            ],
            title="Analisador de Contratos Sociais",
            description="Este aplicativo analisa contratos sociais usando Gemini ou NER para identificar representantes legais.",
        )
        logger.info("Interface Gradio configurada com sucesso")
        return iface
    except Exception as e:
        logger.error(f"Erro ao configurar interface Gradio: {str(e)}")
        raise

if __name__ == "__main__":
    logger.info("Iniciando aplicação")
    iface = create_interface()
    iface.launch()