File size: 3,567 Bytes
f5eb34f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
"""
Processamento e extração de texto de documentos
"""
import io
import os
from typing import Union, Optional, Tuple
from pypdf import PdfReader


def extract_text_from_pdf(pdf_data: Union[bytes, io.BytesIO]) -> str:
    """
    Extrai texto de arquivo PDF

    Args:
        pdf_data: Dados do PDF em bytes ou BytesIO

    Returns:
        Texto extraído
    """
    try:
        if isinstance(pdf_data, bytes):
            pdf_data = io.BytesIO(pdf_data)

        reader = PdfReader(pdf_data)
        text = ""

        for page in reader.pages:
            page_text = page.extract_text()
            if page_text:
                text += page_text + "\n"

        return text.strip()
    except Exception as e:
        return f"Erro ao extrair PDF: {str(e)}"


def extract_text_from_txt(txt_data: Union[bytes, str]) -> str:
    """
    Extrai texto de arquivo TXT

    Args:
        txt_data: Dados do TXT em bytes ou string

    Returns:
        Texto extraído
    """
    try:
        if isinstance(txt_data, bytes):
            return txt_data.decode("utf-8", errors="ignore")
        return txt_data
    except Exception as e:
        return f"Erro ao extrair TXT: {str(e)}"


def process_uploaded_file(file_obj) -> Tuple[str, str]:
    """
    Processa arquivo enviado via Gradio

    Args:
        file_obj: Objeto de arquivo do Gradio

    Returns:
        Tupla (nome_arquivo, texto_extraído)
    """
    # Extrai nome do arquivo
    name = "arquivo_desconhecido"
    if hasattr(file_obj, "name"):
        name = os.path.basename(file_obj.name)
    elif isinstance(file_obj, dict) and "name" in file_obj:
        name = os.path.basename(file_obj["name"])
    elif isinstance(file_obj, str):
        name = os.path.basename(file_obj)

    # Extrai dados
    data = None
    path = None

    if hasattr(file_obj, "read"):
        # Objeto file-like
        try:
            data = file_obj.read()
        except Exception:
            data = None
    elif isinstance(file_obj, dict):
        # Dicionário com caminho ou dados
        path = file_obj.get("path") or file_obj.get("name")
        if path and os.path.exists(path):
            with open(path, "rb") as f:
                data = f.read()
        elif "data" in file_obj:
            data = file_obj["data"]
    elif isinstance(file_obj, str):
        # Caminho de arquivo
        path = file_obj
        if os.path.exists(path):
            with open(path, "rb") as f:
                data = f.read()

    # Processa baseado no tipo
    if data is None:
        return name, "Erro: não foi possível ler o arquivo"

    is_pdf = name.lower().endswith(".pdf")

    if is_pdf:
        text = extract_text_from_pdf(data)
    else:
        text = extract_text_from_txt(data)

    return name, text


def get_document_preview(text: str, max_chars: int = 500) -> str:
    """
    Retorna preview do documento

    Args:
        text: Texto completo
        max_chars: Quantidade máxima de caracteres

    Returns:
        Preview do texto
    """
    if len(text) <= max_chars:
        return text

    return text[:max_chars] + "..."


def get_document_stats(text: str) -> dict:
    """
    Calcula estatísticas do documento

    Args:
        text: Texto do documento

    Returns:
        Dicionário com estatísticas
    """
    words = text.split()
    lines = text.split("\n")

    return {
        "total_chars": len(text),
        "total_words": len(words),
        "total_lines": len(lines),
        "avg_word_length": sum(len(w) for w in words) / len(words) if words else 0
    }