Spaces:
Sleeping
Sleeping
import os | |
import pydicom | |
import numpy as np | |
from PIL import Image | |
from dotenv import load_dotenv | |
import cv2 | |
import google.generativeai as genai | |
load_dotenv() | |
def setup_analysis(): | |
"""Configura o ambiente para análise de imagens.""" | |
api_key = os.getenv('API_KEY') | |
if not api_key: | |
raise ValueError("Chave de API não encontrada no arquivo .env") | |
# Configurar o modelo Gemini | |
genai.configure(api_key=api_key) | |
model = genai.GenerativeModel('gemini-2.0-flash-exp') | |
return model | |
def analyze_with_model(model, image, prompt): | |
"""Realiza análise da imagem usando o modelo configurado.""" | |
try: | |
response = model.generate_content([image, prompt]) | |
return response.text | |
except Exception as e: | |
raise Exception(f"Erro na análise: {str(e)}") | |
def process_image(image_path): | |
"""Processa a imagem para análise, suportando formatos DICOM e comuns.""" | |
try: | |
if image_path.lower().endswith('.dcm'): | |
return process_dicom(image_path) | |
else: | |
return process_regular_image(image_path) | |
except Exception as e: | |
raise Exception(f"Erro ao processar imagem: {str(e)}") | |
def process_dicom(dicom_path): | |
"""Processa arquivo DICOM.""" | |
ds = pydicom.dcmread(dicom_path) | |
image = ds.pixel_array.astype(float) | |
# Normalização | |
image = ((image - image.min()) / (image.max() - image.min()) * 255).astype(np.uint8) | |
# Converter para RGB se necessário | |
if len(image.shape) == 2: | |
image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB) | |
return Image.fromarray(image) | |
def process_regular_image(image_path): | |
"""Processa imagens em formatos comuns (jpg, png, etc).""" | |
image = Image.open(image_path) | |
if image.mode != 'RGB': | |
image = image.convert('RGB') | |
return image | |
def extract_dicom_metadata(dicom_path): | |
"""Extrai metadados relevantes de arquivos DICOM.""" | |
try: | |
ds = pydicom.dcmread(dicom_path) | |
metadata = { | |
'PatientID': getattr(ds, 'PatientID', 'N/A'), | |
'StudyDate': getattr(ds, 'StudyDate', 'N/A'), | |
'Modality': getattr(ds, 'Modality', 'N/A'), | |
'BodyPartExamined': getattr(ds, 'BodyPartExamined', 'N/A'), | |
} | |
return metadata | |
except Exception as e: | |
return {'error': f"Erro ao extrair metadados: {str(e)}"} | |
def format_report(analysis_result): | |
"""Formata o resultado da análise em HTML para exibição.""" | |
html_report = f""" | |
<div class="report-container"> | |
<h2>Laudo Radiológico</h2> | |
<div class="report-section"> | |
<h3>Qualidade da Imagem</h3> | |
<p>{analysis_result.get('qualidade_imagem', 'N/A')}</p> | |
</div> | |
<div class="report-section"> | |
<h3>Região Anatômica</h3> | |
<p>{analysis_result.get('regiao_anatomica', 'N/A')}</p> | |
</div> | |
<div class="report-section"> | |
<h3>Achados</h3> | |
<p>{analysis_result.get('achados', 'N/A')}</p> | |
</div> | |
<div class="report-section"> | |
<h3>Impressão</h3> | |
<p>{analysis_result.get('impressao', 'N/A')}</p> | |
</div> | |
</div> | |
""" | |
return html_report |