app.services.file_service

Módulo responsável por salvar arquivos recebidos e extrair seu conteúdo, suportando arquivos .txt e .pdf.

Funções:

  • save_file: salva o arquivo enviado no diretório UPLOAD_FOLDER.
  • read_txt_file: lê o conteúdo de um arquivo .txt.
  • extract_pdf_content: extrai texto de um arquivo .pdf usando pdfminer.
  • extract_file_content: determina o tipo do arquivo e extrai seu conteúdo.
 1"""
 2Módulo responsável por salvar arquivos recebidos e extrair seu conteúdo,
 3suportando arquivos .txt e .pdf.
 4
 5Funções:
 6- save_file: salva o arquivo enviado no diretório UPLOAD_FOLDER.
 7- read_txt_file: lê o conteúdo de um arquivo .txt.
 8- extract_pdf_content: extrai texto de um arquivo .pdf usando pdfminer.
 9- extract_file_content: determina o tipo do arquivo e extrai seu conteúdo.
10"""
11
12import os
13from werkzeug.utils import secure_filename
14from pdfminer.high_level import extract_text
15
16UPLOAD_FOLDER = "./uploads"
17
18def save_file(file):
19    """
20    Salva o arquivo enviado no diretório UPLOAD_FOLDER.
21
22    Args:
23        file (werkzeug.datastructures.FileStorage): Arquivo recebido via request.
24
25    Returns:
26        tuple: (filename, filepath) com o nome seguro e caminho completo do arquivo salvo.
27    """
28    filename = secure_filename(file.filename)
29    filepath = os.path.join(UPLOAD_FOLDER, filename)
30    file.save(filepath)
31    return filename, filepath
32
33def read_txt_file(filepath):
34    """
35    Lê o conteúdo de um arquivo .txt.
36
37    Args:
38        filepath (str): Caminho do arquivo.
39
40    Returns:
41        str: Conteúdo do arquivo como string.
42    """
43    with open(filepath, "r", encoding="utf-8") as f:
44        return f.read()
45
46def extract_pdf_content(filepath):
47    """
48    Extrai o texto de um arquivo PDF usando pdfminer.
49
50    Args:
51        filepath (str): Caminho do arquivo PDF.
52
53    Returns:
54        str: Texto extraído do PDF.
55    """
56    return extract_text(filepath)
57
58def extract_file_content(filename, filepath):
59    """
60    Determina o tipo do arquivo (txt ou pdf) e extrai seu conteúdo.
61
62    Args:
63        filename (str): Nome do arquivo.
64        filepath (str): Caminho do arquivo.
65
66    Returns:
67        str: Conteúdo textual extraído do arquivo.
68
69    Raises:
70        ValueError: Caso o tipo do arquivo não seja suportado.
71    """
72    if filename.lower().endswith(".txt"):
73        return read_txt_file(filepath)
74    elif filename.lower().endswith(".pdf"):
75        return extract_pdf_content(filepath)
76    else:
77        raise ValueError("Unsupported file type")
UPLOAD_FOLDER = './uploads'
def save_file(file):
19def save_file(file):
20    """
21    Salva o arquivo enviado no diretório UPLOAD_FOLDER.
22
23    Args:
24        file (werkzeug.datastructures.FileStorage): Arquivo recebido via request.
25
26    Returns:
27        tuple: (filename, filepath) com o nome seguro e caminho completo do arquivo salvo.
28    """
29    filename = secure_filename(file.filename)
30    filepath = os.path.join(UPLOAD_FOLDER, filename)
31    file.save(filepath)
32    return filename, filepath

Salva o arquivo enviado no diretório UPLOAD_FOLDER.

Args: file (werkzeug.datastructures.FileStorage): Arquivo recebido via request.

Returns: tuple: (filename, filepath) com o nome seguro e caminho completo do arquivo salvo.

def read_txt_file(filepath):
34def read_txt_file(filepath):
35    """
36    Lê o conteúdo de um arquivo .txt.
37
38    Args:
39        filepath (str): Caminho do arquivo.
40
41    Returns:
42        str: Conteúdo do arquivo como string.
43    """
44    with open(filepath, "r", encoding="utf-8") as f:
45        return f.read()

Lê o conteúdo de um arquivo .txt.

Args: filepath (str): Caminho do arquivo.

Returns: str: Conteúdo do arquivo como string.

def extract_pdf_content(filepath):
47def extract_pdf_content(filepath):
48    """
49    Extrai o texto de um arquivo PDF usando pdfminer.
50
51    Args:
52        filepath (str): Caminho do arquivo PDF.
53
54    Returns:
55        str: Texto extraído do PDF.
56    """
57    return extract_text(filepath)

Extrai o texto de um arquivo PDF usando pdfminer.

Args: filepath (str): Caminho do arquivo PDF.

Returns: str: Texto extraído do PDF.

def extract_file_content(filename, filepath):
59def extract_file_content(filename, filepath):
60    """
61    Determina o tipo do arquivo (txt ou pdf) e extrai seu conteúdo.
62
63    Args:
64        filename (str): Nome do arquivo.
65        filepath (str): Caminho do arquivo.
66
67    Returns:
68        str: Conteúdo textual extraído do arquivo.
69
70    Raises:
71        ValueError: Caso o tipo do arquivo não seja suportado.
72    """
73    if filename.lower().endswith(".txt"):
74        return read_txt_file(filepath)
75    elif filename.lower().endswith(".pdf"):
76        return extract_pdf_content(filepath)
77    else:
78        raise ValueError("Unsupported file type")

Determina o tipo do arquivo (txt ou pdf) e extrai seu conteúdo.

Args: filename (str): Nome do arquivo. filepath (str): Caminho do arquivo.

Returns: str: Conteúdo textual extraído do arquivo.

Raises: ValueError: Caso o tipo do arquivo não seja suportado.