VsCode commited on
Commit
2c9f880
·
1 Parent(s): 2badcc4

changing API

Browse files
Files changed (1) hide show
  1. app.py +165 -4
app.py CHANGED
@@ -1,7 +1,168 @@
1
- from fastapi import FastAPI
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
- app = FastAPI()
4
 
5
  @app.get("/")
6
- def init():
7
- return {"Hello": "Ed"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, File, UploadFile, HTTPException
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+ from huggingface_hub import login
4
+ from transformers import pipeline
5
+ from PIL import Image
6
+ import io
7
+ import base64
8
+ from datetime import datetime
9
+ from typing import Optional
10
+
11
+ # Login no Hugging Face
12
+ login(new_session=False)
13
+
14
+ app = FastAPI(
15
+ title="CareLink Medical API",
16
+ description="API para análise de exames médicos usando IA",
17
+ version="1.0.0"
18
+ )
19
+
20
+ # Configurar CORS para permitir requisições do frontend
21
+ app.add_middleware(
22
+ CORSMiddleware,
23
+ allow_origins=["*"], # Em produção, especifique o domínio do frontend
24
+ allow_credentials=True,
25
+ allow_methods=["*"],
26
+ allow_headers=["*"],
27
+ )
28
+
29
+ # Inicializar o pipeline do modelo (fazer isso uma vez no startup)
30
+ print("Carregando modelo MedGemma...")
31
+ pipe = None
32
+
33
+ @app.on_event("startup")
34
+ async def startup_event():
35
+ global pipe
36
+ try:
37
+ pipe = pipeline("image-text-to-text", model="google/medgemma-4b-it")
38
+ print("Modelo MedGemma carregado com sucesso!")
39
+ except Exception as e:
40
+ print(f"Erro ao carregar modelo: {e}")
41
 
 
42
 
43
  @app.get("/")
44
+ def root():
45
+ return {
46
+ "message": "CareLink Medical API",
47
+ "status": "online",
48
+ "version": "1.0.0",
49
+ "endpoints": {
50
+ "analyze_exam": "/api/analyze-exam (POST)",
51
+ "health": "/health (GET)"
52
+ }
53
+ }
54
+
55
+
56
+ @app.get("/health")
57
+ def health_check():
58
+ return {
59
+ "status": "healthy",
60
+ "model_loaded": pipe is not None,
61
+ "timestamp": datetime.now().isoformat()
62
+ }
63
+
64
+
65
+ @app.post("/api/analyze-exam")
66
+ async def analyze_exam(
67
+ file: UploadFile = File(...),
68
+ patient_name: Optional[str] = None
69
+ ):
70
+ """
71
+ Analisa uma imagem de exame médico usando o modelo MedGemma.
72
+
73
+ - **file**: Imagem do exame (JPEG, PNG, etc)
74
+ - **patient_name**: Nome do paciente (opcional)
75
+ """
76
+
77
+ if pipe is None:
78
+ raise HTTPException(
79
+ status_code=503,
80
+ detail="Modelo ainda não foi carregado. Tente novamente em alguns instantes."
81
+ )
82
+
83
+ # Validar tipo de arquivo
84
+ if not file.content_type.startswith('image/'):
85
+ raise HTTPException(
86
+ status_code=400,
87
+ detail="O arquivo enviado não é uma imagem válida"
88
+ )
89
+
90
+ try:
91
+ # Ler a imagem
92
+ contents = await file.read()
93
+ image = Image.open(io.BytesIO(contents))
94
+
95
+ # Converter imagem para base64 para retornar ao frontend (opcional)
96
+ buffered = io.BytesIO()
97
+ image.save(buffered, format=image.format or "PNG")
98
+ img_base64 = base64.b64encode(buffered.getvalue()).decode()
99
+
100
+ # Preparar mensagem para o modelo
101
+ messages = [
102
+ {
103
+ "role": "user",
104
+ "content": [
105
+ {"type": "image", "image": image},
106
+ {
107
+ "type": "text",
108
+ "text": "Analise esta imagem de exame médico. Descreva o que você observa, "
109
+ "identifique possíveis achados clínicos e forneça uma análise detalhada. "
110
+ "Se possível, indique se há algo que requer atenção médica."
111
+ }
112
+ ]
113
+ }
114
+ ]
115
+
116
+ # Processar com o modelo
117
+ print(f"Analisando exame para paciente: {patient_name or 'não especificado'}")
118
+ result = pipe(messages)
119
+
120
+ # Extrair a resposta do modelo
121
+ analysis_text = ""
122
+ if isinstance(result, list) and len(result) > 0:
123
+ if isinstance(result[0], dict) and "generated_text" in result[0]:
124
+ analysis_text = result[0]["generated_text"]
125
+ else:
126
+ analysis_text = str(result[0])
127
+ else:
128
+ analysis_text = str(result)
129
+
130
+ # Montar resposta estruturada
131
+ response = {
132
+ "success": True,
133
+ "timestamp": datetime.now().isoformat(),
134
+ "patient_name": patient_name,
135
+ "file_info": {
136
+ "filename": file.filename,
137
+ "content_type": file.content_type,
138
+ "size_bytes": len(contents)
139
+ },
140
+ "analysis": {
141
+ "model": "google/medgemma-4b-it",
142
+ "result": analysis_text,
143
+ "confidence": "high" # Você pode adicionar lógica para calcular confiança
144
+ },
145
+ "image_preview": f"data:image/png;base64,{img_base64[:100]}..." # Preview truncado
146
+ }
147
+
148
+ print(f"Análise concluída com sucesso para: {file.filename}")
149
+ return response
150
+
151
+ except Exception as e:
152
+ print(f"Erro ao processar imagem: {str(e)}")
153
+ raise HTTPException(
154
+ status_code=500,
155
+ detail=f"Erro ao processar a imagem: {str(e)}"
156
+ )
157
+
158
+
159
+ @app.get("/api/test-model")
160
+ def test_model():
161
+ """Endpoint para testar se o modelo está funcionando"""
162
+ if pipe is None:
163
+ return {"status": "error", "message": "Modelo não carregado"}
164
+ return {
165
+ "status": "ok",
166
+ "model": "google/medgemma-4b-it",
167
+ "message": "Modelo carregado e pronto para uso"
168
+ }