File size: 7,709 Bytes
84c274d
 
69b7038
c221f76
69b7038
7947e09
 
7209519
 
 
5127610
 
84c274d
7209519
 
 
 
 
 
 
 
84c274d
5127610
ea3a2e4
98c4eab
84c274d
3845371
ea3a2e4
98c4eab
84c274d
5127610
ea3a2e4
98c4eab
84c274d
 
 
7209519
7947e09
7209519
7947e09
 
 
7209519
 
 
 
69b7038
7209519
 
7947e09
 
 
 
 
 
7209519
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c221f76
69b7038
 
 
7209519
 
 
7947e09
7209519
84c274d
f673aa2
 
 
84c274d
 
 
5127610
 
 
 
 
 
 
84c274d
5127610
 
ea66f6c
 
5127610
 
 
 
84c274d
5127610
 
69b7038
84c274d
 
 
 
5127610
84c274d
 
 
 
 
 
 
 
 
5127610
84c274d
5127610
 
c221f76
84c274d
c221f76
 
7947e09
 
84c274d
4017502
5127610
84c274d
5127610
 
 
 
 
 
84c274d
5127610
 
c3c8af8
84c274d
 
7947e09
 
 
 
 
 
 
 
 
 
 
 
3921ea2
 
7947e09
3921ea2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7947e09
3921ea2
 
7947e09
 
3921ea2
 
7947e09
 
3921ea2
 
 
 
 
 
 
 
 
 
 
7947e09
3921ea2
7947e09
 
5127610
 
7209519
 
 
5127610
 
 
84c274d
5127610
84c274d
5127610
84c274d
 
5127610
84c274d
7209519
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
import io
import os
import boto3
import gc 
import sys
import hashlib
from datetime import datetime, timezone, timedelta
from PIL import Image
from botocore.config import Config
from ultralytics import YOLO
from fastapi import FastAPI, UploadFile
from fastapi.middleware.cors import CORSMiddleware

# ==========================================
# 1. CONFIGURACIÓN DE CLOUDFLARE R2
# ==========================================
R2_BUCKET_NAME = os.getenv("R2_BUCKET_NAME")
R2_ENDPOINT_URL = os.getenv("R2_ENDPOINT_URL")
R2_ACCESS_KEY = os.getenv("R2_ACCESS_KEY")
R2_SECRET_KEY = os.getenv("R2_SECRET_KEY")

model_configs = {
    "VEF": {
        "r2_key": "files/md5/39/398b1e461a92a06981e0a1127a9f56",
        "path": "/home/user/models/train/VEF_model_13f/weights/best.onnx"
    },
    "USD": {  
        "r2_key": "files/md5/8b/50f8fa0b30f38111e8f77fcb396639",
        "path": "/home/user/models/train/USD_model_plus_01/weights/best.onnx"
    },
    "INFERENCIA": {
        "r2_key": "files/md5/1d/ee121124dc76d37c3a5efc4993f961",
        "path": "/home/user/models/train/USD_VEF_Model_01j/weights/best.onnx"
    }
}

# ==========================================
# 2. FUNCIONES AUXILIARES
# ==========================================
def get_s3_client():
    """Retorna un cliente s3 configurado para Cloudflare R2"""
    return boto3.client(
        service_name="s3",
        endpoint_url=R2_ENDPOINT_URL,
        aws_access_key_id=R2_ACCESS_KEY,
        aws_secret_access_key=R2_SECRET_KEY,
        config=Config(signature_version="s3v4")
    )

# ==========================================
# 3. DESCARGA CONSTRUCTORA Y DESTRUCTIVA
# ==========================================
def download_models_from_r2():
    s3_client = get_s3_client()

    for name, config in model_configs.items():
        os.makedirs(os.path.dirname(config["path"]), exist_ok=True)
        
        if not os.path.exists(config["path"]):
            print(f"Descargando modelo {name} desde Cloudflare R2...")
            try:
                s3_client.download_file(
                    Bucket=R2_BUCKET_NAME,
                    Key=config["r2_key"],
                    Filename=config["path"]
                )
                print(f"¡Modelo {name} descargado con éxito!")
            except Exception as e:
                print(f"❌ Error al descargar el modelo {name}: {e}")
                raise e
        else:
            print(f"El modelo {name} ya existe localmente. Cargando...")
        
    del s3_client
    gc.collect()

download_models_from_r2()

# ==========================================
# 4. CARGA DE MODELOS
# ==========================================
models = {
    "USD":        YOLO(model_configs["USD"]["path"], task="detect"),
    "VEF":        YOLO(model_configs["VEF"]["path"], task="detect"),
    "INFERENCIA": YOLO(model_configs["INFERENCIA"]["path"], task="detect"),
}

classes = {
    "USD": [
        "fifty-back",        "fifty-front", 
        "five-back",         "five-front", 
        "one-back",          "one-front", 
        "one_hundred-back",  "one_hundred-front",
        "ten-back",          "ten-front", 
        "twenty-back",       "twenty-front",
    ],
    "VEF": [
        "five-back-vef",        "five-front-vef",
        "fifty-back-vef",       "fifty-front-vef",
        "five_hundred-back-vef", "five_hundred-front-vef",
        "one_hundred-back-vef", "one_hundred-front-vef",
        "ten-back-vef",         "ten-front-vef", 
        "twenty-back-vef",      "twenty-front-vef", 
        "two_hundred-back-vef", "two_hundred-front-vef", 
    ],
    "INFERENCIA": [
        "dollar_back", "dollar_front",
        "vef_back", "vef_front",
    ],
}

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.post("/detection")
def detection_vef(image: UploadFile):
    print("FOTO RECIBIDA")
    
    imageBytes = image.file.read()
    
    imageStream = io.BytesIO(imageBytes)
    imageFile = Image.open(imageStream).convert("RGB")

    debug_buffer = io.BytesIO() 
    imageFile.save(debug_buffer, format="JPEG") 

    which_currency = models["INFERENCIA"].predict(imageFile, verbose=False, imgsz=320, conf=0.10)
    
    if len(which_currency[0].boxes) == 0:
        return {"message": "No objects detected"}
        
    currency_label = classes["INFERENCIA"][int(which_currency[0].boxes[0].cls.item())]
    
    if "vef" in currency_label:
        currency = "VEF"
    else:
        currency = "USD"
        
    results = models[currency].predict(imageFile, verbose=False, imgsz=320, conf=0.25)

    if len(results[0].boxes) > 0:
        # Tomamos el label y la confianza de la primera detección (la de mayor confianza usualmente)
        primary_label = classes[currency][int(results[0].boxes[0].cls.item())]
        primary_conf = results[0].boxes[0].conf.item() # <--- Extraemos la confianza
        
        # -----------------------------------------------------
        # LÓGICA DE GUARDADO EN R2 (LOGS)
        # -----------------------------------------------------
        try:
            # Zona horaria de Venezuela (UTC-4)
            vzla_tz = timezone(timedelta(hours=-4))
            now = datetime.now(vzla_tz)
            
            # Formato base del nombre
            base_filename = f"{now.strftime('%d-%m-%Y_%H%M%S')}_{primary_label}_{primary_conf:.4f}"
            
            # Keys correctas con sus extensiones para R2
            r2_image_key = f"logs/{base_filename}.jpg"
            r2_text_key = f"logs/{base_filename}.txt"
            
            # 1. Preparar las coordenadas del TXT en formato YOLO (norm_x_center, norm_y_center, norm_width, norm_height)
            log_lines = []
            for box in results[0].boxes:
                class_id = int(box.cls.item())
                # xywhn devuelve valores normalizados entre 0 y 1
                x_center, y_center, width, height = box.xywhn[0].tolist()
                
                line = f"{class_id} {x_center:.6f} {y_center:.6f} {width:.6f} {height:.6f}\n"
                log_lines.append(line)
            
            # Convertimos el string acumulado en bytes listos para S3/R2
            text_bytes = "".join(log_lines).encode("utf-8")
            
            # 2. Subir ambos archivos usando el mismo cliente S3
            s3_client = get_s3_client()
            
            # Subir Imagen
            s3_client.put_object(
                Bucket=R2_BUCKET_NAME,
                Key=r2_image_key,
                Body=imageBytes,
                ContentType="image/jpeg"
            )
            print(f"[LOG] Imagen respaldada en R2: {r2_image_key}")

            # Subir TXT de anotaciones
            s3_client.put_object(
                Bucket=R2_BUCKET_NAME,
                Key=r2_text_key,
                Body=text_bytes,
                ContentType="text/plain"  # ContentType correcto para archivos de texto limpio
            )
            print(f"[LOG] TXT de anotaciones respaldado en R2: {r2_text_key}")
            
        except Exception as e:
            print(f"❌ [ERROR] Fallo al subir logs a R2: {e}")
        # -----------------------------------------------------

        boxes = [
            {
                "label": classes[currency][int(box.cls.item())],
                "confidence": box.conf.item(),
                "bbox": box.xyxy.tolist()
            }
            for box in results[0].boxes
        ]
        print(boxes)
        return {"detections": boxes}
    else:
        return {"message": "No objects detected"}

@app.get("/")
def status():
    print("200 OK")
    return {"message": "200 OK"}