-
-
Notifications
You must be signed in to change notification settings - Fork 17
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Versão erro no 'gazette_themed_excerpts_extraction' tratado (#59)
RP para ajudar a sincronizar os avanços da trilha de segmentadores. @Jefersonalves @ogecece
- Loading branch information
Showing
11 changed files
with
346 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
from .diario_ama import extrair_diarios_municipais |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
import re | ||
|
||
from .diario_municipal import Diario, Municipio | ||
|
||
# No final do regex, existe uma estrutura condicional que verifica se o próximo match é um \s ou SECRETARIA. Isso foi feito para resolver um problema no diário de 2018-10-02, em que o município de Coité do Nóia não foi percebido pelo código. Para resolver isso, utilizamos a próxima palavra (SECRETARIA) para tratar esse caso. | ||
# Exceções Notáveis | ||
# String: VAMOS, município Poço das Trincheiras, 06/01/2022, ato CCB3A6AB | ||
re_nomes_municipios = ( | ||
r"ESTADO DE ALAGOAS(?:| )\n{1,2}PREFEITURA MUNICIPAL DE (.*\n{0,2}(?!VAMOS).*$)\n\s(?:\s|SECRETARIA)") | ||
|
||
|
||
def extrair_diarios_municipais(texto_diario: str, gazette: dict, territories: list): | ||
texto_diario_slice = texto_diario.lstrip().splitlines() | ||
|
||
# Processamento | ||
linhas_apagar = [] # slice de linhas a ser apagadas ao final. | ||
ama_header = texto_diario_slice[0] | ||
ama_header_count = 0 | ||
codigo_count = 0 | ||
codigo_total = texto_diario.count("Código Identificador") | ||
|
||
for num_linha, linha in enumerate(texto_diario_slice): | ||
# Remoção do cabeçalho AMA, porém temos que manter a primeira aparição. | ||
if linha.startswith(ama_header): | ||
ama_header_count += 1 | ||
if ama_header_count > 1: | ||
linhas_apagar.append(num_linha) | ||
|
||
# Remoção das linhas finais | ||
if codigo_count == codigo_total: | ||
linhas_apagar.append(num_linha) | ||
elif linha.startswith("Código Identificador"): | ||
codigo_count += 1 | ||
|
||
# Apagando linhas do slice | ||
texto_diario_slice = [l for n, l in enumerate( | ||
texto_diario_slice) if n not in linhas_apagar] | ||
|
||
# Inserindo o cabeçalho no diário de cada município. | ||
texto_diarios = {} | ||
nomes_municipios = re.findall( | ||
re_nomes_municipios, texto_diario, re.MULTILINE) | ||
for municipio in nomes_municipios: | ||
municipio = Municipio(municipio) | ||
texto_diarios[municipio] = ama_header + '\n\n' | ||
|
||
num_linha = 0 | ||
municipio_atual = None | ||
while num_linha < len(texto_diario_slice): | ||
linha = texto_diario_slice[num_linha].rstrip() | ||
|
||
if linha.startswith("ESTADO DE ALAGOAS"): | ||
nome = nome_municipio(texto_diario_slice, num_linha) | ||
if nome is not None: | ||
municipio_atual = Municipio(nome) | ||
|
||
# Só começa, quando algum muncípio for encontrado. | ||
if municipio_atual is None: | ||
num_linha += 1 | ||
continue | ||
|
||
# Conteúdo faz parte de um muncípio | ||
texto_diarios[municipio_atual] += linha + '\n' | ||
num_linha += 1 | ||
|
||
diarios = [] | ||
for municipio, diario in texto_diarios.items(): | ||
diarios.append(Diario(municipio, ama_header, diario, gazette, territories).__dict__) | ||
return diarios | ||
|
||
|
||
def nome_municipio(texto_diario_slice: slice, num_linha: int): | ||
texto = '\n'.join(texto_diario_slice[num_linha:num_linha+10]) | ||
match = re.findall(re_nomes_municipios, texto, re.MULTILINE) | ||
if len(match) > 0: | ||
return match[0].strip().replace('\n', '') | ||
return None |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,103 @@ | ||
import json | ||
import re | ||
import unicodedata | ||
from datetime import date, datetime | ||
from .utils import get_territorie_info | ||
import hashlib | ||
from io import BytesIO | ||
|
||
|
||
class Municipio: | ||
|
||
def __init__(self, municipio): | ||
municipio = municipio.rstrip().replace('\n', '') # limpeza inicial | ||
# Alguns nomes de municípios possuem um /AL no final, exemplo: Viçosa no diário 2022-01-17, ato 8496EC0A. Para evitar erros como "vicosa-/al-secretaria-municipal...", a linha seguir remove isso. | ||
municipio = re.sub("(\/AL.*|GABINETE DO PREFEITO.*|PODER.*|http.*|PORTARIA.*|Extrato.*|ATA DE.*|SECRETARIA.*|Fundo.*|SETOR.*|ERRATA.*|- AL.*|GABINETE.*)", "", municipio) | ||
self.id = self._computa_id(municipio) | ||
self.nome = municipio | ||
|
||
def _computa_id(self, nome_municipio): | ||
ret = nome_municipio.strip().lower().replace(" ", "-") | ||
ret = unicodedata.normalize('NFKD', ret) | ||
ret = ret.encode('ASCII', 'ignore').decode("utf-8") | ||
return ret | ||
|
||
def __hash__(self): | ||
return hash(self.id) | ||
|
||
def __eq__(self, other): | ||
return self.id == other.id | ||
|
||
def __str__(self): | ||
return json.dumps(self.__dict__, indent=2, default=str, ensure_ascii=False) | ||
|
||
|
||
class Diario: | ||
|
||
_mapa_meses = { | ||
"Janeiro": 1, | ||
"Fevereiro": 2, | ||
"Março": 3, | ||
"Abril": 4, | ||
"Maio": 5, | ||
"Junho": 6, | ||
"Julho": 7, | ||
"Agosto": 8, | ||
"Setembro": 9, | ||
"Outubro": 10, | ||
"Novembro": 11, | ||
"Dezembro": 12, | ||
} | ||
|
||
def __init__(self, municipio: Municipio, cabecalho: str, texto: str, gazette: dict, territories: list): | ||
|
||
|
||
self.territory_id, self.territory_name, self.state_code = get_territorie_info( | ||
name=municipio.nome, | ||
state=cabecalho.split(",")[0], | ||
territories=territories) | ||
|
||
self.source_text = texto.rstrip() | ||
self.date = self._extrai_data_publicacao(cabecalho) | ||
self.edition_number = cabecalho.split("Nº")[1].strip() | ||
self.is_extra_edition = False | ||
self.power = "executive_legislative" | ||
self.file_url = gazette["file_url"] | ||
self.file_path = gazette["file_path"] | ||
self.file_checksum = self.md5sum(BytesIO(self.source_text.encode(encoding='UTF-8'))) | ||
self.id = gazette["id"] | ||
self.scraped_at = datetime.utcnow() | ||
self.created_at = self.scraped_at | ||
self.file_raw_txt = f"/{self.territory_id}/{self.date}/{self.file_checksum}.txt" | ||
self.processed = True | ||
self.url = self.file_raw_txt | ||
|
||
def _extrai_data_publicacao(self, ama_header: str): | ||
match = re.findall( | ||
r".*(\d{2}) de (\w*) de (\d{4})", ama_header, re.MULTILINE)[0] | ||
mes = Diario._mapa_meses[match[1]] | ||
return date(year=int(match[2]), month=mes, day=int(match[0])) | ||
|
||
def md5sum(self, file): | ||
"""Calculate the md5 checksum of a file-like object without reading its | ||
whole content in memory. | ||
from io import BytesIO | ||
md5sum(BytesIO(b'file content to hash')) | ||
'784406af91dd5a54fbb9c84c2236595a' | ||
""" | ||
m = hashlib.md5() | ||
while True: | ||
d = file.read(8096) | ||
if not d: | ||
break | ||
m.update(d) | ||
return m.hexdigest() | ||
|
||
def __hash__(self): | ||
return hash(self.id) | ||
|
||
def __eq__(self, other): | ||
return self.id == other.id | ||
|
||
def __str__(self): | ||
return dict(self.__dict__) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
from .get_territory_info import get_territorie_info |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
|
||
import unicodedata | ||
|
||
|
||
def get_territorie_info(state: str, name: str, territories: list): | ||
|
||
state = state.strip() | ||
name = limpar_name(name) | ||
|
||
for territorie in territories: | ||
territorie_name = limpar_name(territorie["territory_name"]) | ||
if territorie["state"].lower() == state.lower() and territorie_name == name: | ||
|
||
return territorie["id"], territorie["territory_name"], territorie["state_code"] | ||
|
||
|
||
def limpar_name(name: str): | ||
|
||
clean_name = name.replace("'", "") | ||
clean_name = unicodedata.normalize("NFD", clean_name) | ||
clean_name = clean_name.encode("ascii", "ignore").decode("utf-8") | ||
clean_name = clean_name.lower() | ||
clean_name = clean_name.strip() | ||
|
||
clean_name = "major isidoro" if clean_name == "major izidoro" else clean_name | ||
|
||
return clean_name |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
from associations import extrair_diarios_municipais | ||
|
||
|
||
def extrarir_diarios(pdf_text, gazette, territories): | ||
|
||
diarios = extrair_diarios_municipais(pdf_text, gazette, territories) | ||
return diarios |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.