Spaces:
Sleeping
Sleeping
Fernando Cervan
commited on
Commit
·
8f6361b
1
Parent(s):
9eebefd
Salvando alterações
Browse files- Inferencia.py +26 -1
- PromptDocumento.py +32 -0
- app.py +13 -2
Inferencia.py
CHANGED
@@ -1,5 +1,7 @@
|
|
1 |
from transformers import pipeline
|
2 |
import torch
|
|
|
|
|
3 |
class Inferencia:
|
4 |
|
5 |
def __init__(self):
|
@@ -28,4 +30,27 @@ class Inferencia:
|
|
28 |
|
29 |
output = pipe(text=messages, max_new_tokens=200)
|
30 |
|
31 |
-
return output[0]["generated_text"][-1]["content"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
from transformers import pipeline
|
2 |
import torch
|
3 |
+
import json
|
4 |
+
|
5 |
class Inferencia:
|
6 |
|
7 |
def __init__(self):
|
|
|
30 |
|
31 |
output = pipe(text=messages, max_new_tokens=200)
|
32 |
|
33 |
+
return output[0]["generated_text"][-1]["content"]
|
34 |
+
|
35 |
+
@staticmethod
|
36 |
+
def string_para_dicionario(string_json):
|
37 |
+
"""
|
38 |
+
Transforma uma string JSON envolta em crases e com a palavra 'json' em um dicionário Python.
|
39 |
+
|
40 |
+
Args:
|
41 |
+
string_json (str): A string JSON a ser convertida, podendo estar envolta em crases e conter 'json'.
|
42 |
+
|
43 |
+
Returns:
|
44 |
+
dict: Um dicionário Python correspondente à string JSON.
|
45 |
+
"""
|
46 |
+
try:
|
47 |
+
# Remove as crases (`) e a palavra 'json' se estiverem presentes
|
48 |
+
if string_json.startswith("```json") and string_json.endswith("```"):
|
49 |
+
string_json = string_json[7:-3].strip() # Remove "```json" e "```"
|
50 |
+
|
51 |
+
# Converte a string JSON limpa em um dicionário Python
|
52 |
+
dicionario = json.loads(string_json)
|
53 |
+
return dicionario
|
54 |
+
except json.JSONDecodeError as e:
|
55 |
+
# Caso ocorra um erro na conversão, levanta uma exceção com detalhes
|
56 |
+
raise ValueError(f"Erro ao decodificar a string JSON: {e}")
|
PromptDocumento.py
ADDED
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
class PromptDocumento:
|
3 |
+
|
4 |
+
@staticmethod
|
5 |
+
def cnh():
|
6 |
+
return """
|
7 |
+
Extraia o nome, cpf, data de nascimento, número de registro, primeira habilitação,
|
8 |
+
validade da CNH, RG (documento de identidade), órgão emissor, estado,
|
9 |
+
categoria da habilitação, nacionalidade, filiação pai (se houver), filiação mãe (se houver),
|
10 |
+
local, data da emissão e observações (se houver).
|
11 |
+
Para os campos "se houver", caso não tenha nenhum valor, o JSON será preenchido em branco.
|
12 |
+
Retorne apenas o JSON abaixo preenchido com os valores encontrados:
|
13 |
+
|
14 |
+
{
|
15 |
+
"nome": "",
|
16 |
+
"cpf": "",
|
17 |
+
"data_nascimento": "",
|
18 |
+
"numero_registro": "",
|
19 |
+
"primeiro_habilitacao": "",
|
20 |
+
"validade_cnh": "",
|
21 |
+
"rg": "",
|
22 |
+
"orgao_emissor": "",
|
23 |
+
"orgao_emissor_estado": "",
|
24 |
+
"categoria_habilitacao": "",
|
25 |
+
"nacionalidade": "",
|
26 |
+
"filiacao_pai": "",
|
27 |
+
"filiacao_mae": "",
|
28 |
+
"local": "",
|
29 |
+
"data_emissao": "",
|
30 |
+
"observacoes": "",
|
31 |
+
}
|
32 |
+
"""
|
app.py
CHANGED
@@ -2,6 +2,7 @@ import streamlit as st
|
|
2 |
from LogCustomizado import LogCustomizado as logc
|
3 |
from Inferencia import Inferencia
|
4 |
from PIL import Image
|
|
|
5 |
|
6 |
st.set_page_config(page_title="CADIN - Cadastro Inteligente")
|
7 |
|
@@ -34,11 +35,21 @@ if arquivos_upload is not None:
|
|
34 |
prompt_analisa_tipo_documento,
|
35 |
imagem_convertida
|
36 |
)
|
|
|
37 |
st.write(dados_imagem)
|
|
|
38 |
logc.gerar_log(mensagem_log=f"DADOS IMAGEM: {dados_imagem}")
|
39 |
|
40 |
-
|
41 |
|
42 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
43 |
|
44 |
logc.gerar_log(mensagem_log=f"FIM DO PROCESSAMENTO")
|
|
|
|
|
|
2 |
from LogCustomizado import LogCustomizado as logc
|
3 |
from Inferencia import Inferencia
|
4 |
from PIL import Image
|
5 |
+
from PromptDocumento import PromptDocumento
|
6 |
|
7 |
st.set_page_config(page_title="CADIN - Cadastro Inteligente")
|
8 |
|
|
|
35 |
prompt_analisa_tipo_documento,
|
36 |
imagem_convertida
|
37 |
)
|
38 |
+
|
39 |
st.write(dados_imagem)
|
40 |
+
|
41 |
logc.gerar_log(mensagem_log=f"DADOS IMAGEM: {dados_imagem}")
|
42 |
|
43 |
+
dados_imagem_dict = Inferencia.string_para_dicionario(dados_imagem)
|
44 |
|
45 |
+
if dados_imagem_dict["tipo_documento"] == "CNH":
|
46 |
+
dados_cnh = Inferencia.extrair_dados_imagem(
|
47 |
+
PromptDocumento.cnh(),
|
48 |
+
imagem_convertida
|
49 |
+
)
|
50 |
+
logc.gerar_log(mensagem_log=f"DADOS CNH: {dados_cnh}")
|
51 |
+
logc.gerar_log(mensagem_log=f"ARQUIVO PROCESSADO: {arquivo.name}")
|
52 |
|
53 |
logc.gerar_log(mensagem_log=f"FIM DO PROCESSAMENTO")
|
54 |
+
|
55 |
+
|