leitor-cnh / Inferencia.py
Fernando Cervan
Salvando alterações
807e236
from transformers import pipeline
import torch
import json
from LogCustomizado import LogCustomizado as logc
class Inferencia:
def __init__(self):
...
def extrair_dados_imagem(self, prompt, imagem):
logc.gerar_log(mensagem_log="EXECUTANDO PIPELINE...")
pipe = pipeline(
"image-text-to-text",
model="google/gemma-3-4b-it",
torch_dtype=torch.bfloat16 # Otimiza para rodar na CPU
)
messages = [
{
"role": "system",
"content": [{"type": "text", "text": "You are a helpful assistant."}]
},
{
"role": "user",
"content": [
{"type": "image", "url": imagem},
{"type": "text",
"text": prompt}
]
}
]
logc.gerar_log(mensagem_log="OBTENDO RESPOSTA DA PIPE...")
output = pipe(text=messages, max_new_tokens=400)
return output[0]["generated_text"][-1]["content"]
@staticmethod
def string_para_dicionario(string_json):
"""
Transforma uma string JSON envolta em crases e com a palavra 'json' em um dicionário Python.
Args:
string_json (str): A string JSON a ser convertida, podendo estar envolta em crases e conter 'json'.
Returns:
dict: Um dicionário Python correspondente à string JSON.
"""
try:
# Remove as crases (`) e a palavra 'json' se estiverem presentes
if string_json.startswith("```json") and string_json.endswith("```"):
string_json = string_json[7:-3].strip() # Remove "```json" e "```"
# Converte a string JSON limpa em um dicionário Python
dicionario = json.loads(string_json)
return dicionario
except json.JSONDecodeError as e:
# Caso ocorra um erro na conversão, levanta uma exceção com detalhes
raise ValueError(f"Erro ao decodificar a string JSON: {e}")