Spaces:
Sleeping
Sleeping
Create run_local.py (#5)
Browse files- Create run_local.py (e9d8605de2c7ec4d5d7f3514aa5c689cd620eb3f)
Co-authored-by: Sardo <ChristianSardo@users.noreply.huggingface.co>
- run_local.py +213 -0
run_local.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# run_local.py — Teste local para app2.py com YOLO + OpenCV
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import sys
|
| 5 |
+
import types
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from fastapi.responses import HTMLResponse
|
| 8 |
+
import uvicorn
|
| 9 |
+
|
| 10 |
+
# ================================================================
|
| 11 |
+
# 0️⃣ Preparar ambiente fake ANTES de importar app2.py
|
| 12 |
+
# ================================================================
|
| 13 |
+
|
| 14 |
+
# Variáveis de ambiente fake para evitar erros no import
|
| 15 |
+
os.environ.setdefault("AWS_ACCESS_KEY_ID", "fake")
|
| 16 |
+
os.environ.setdefault("AWS_SECRET_ACCESS_KEY", "fake")
|
| 17 |
+
os.environ.setdefault("AWS_S3_BUCKET_NAME", "fake-bucket")
|
| 18 |
+
os.environ.setdefault("AWS_S3_REGION", "us-east-1")
|
| 19 |
+
os.environ.setdefault("SUPABASE_URL", "http://fake.supabase")
|
| 20 |
+
os.environ.setdefault("SUPABASE_KEY", "fake-key")
|
| 21 |
+
os.environ.setdefault("YOLO_MODEL_PATH", "best.pt") # opcional
|
| 22 |
+
|
| 23 |
+
# Fake ultralytics caso você não queira instalar local
|
| 24 |
+
try:
|
| 25 |
+
import ultralytics # tenta usar real se tiver
|
| 26 |
+
except ImportError:
|
| 27 |
+
ultra_mod = types.ModuleType("ultralytics")
|
| 28 |
+
class DummyBox:
|
| 29 |
+
def __init__(self): pass
|
| 30 |
+
class DummyResult:
|
| 31 |
+
def __init__(self):
|
| 32 |
+
self.names = {0: "screw"}
|
| 33 |
+
self.boxes = None
|
| 34 |
+
class DummyYOLO:
|
| 35 |
+
def __init__(self, *args, **kwargs): pass
|
| 36 |
+
def predict(self, img, *args, **kwargs):
|
| 37 |
+
return [DummyResult()]
|
| 38 |
+
ultra_mod.YOLO = DummyYOLO
|
| 39 |
+
sys.modules["ultralytics"] = ultra_mod
|
| 40 |
+
print("[Fake] ultralytics carregado!")
|
| 41 |
+
|
| 42 |
+
# ================================================================
|
| 43 |
+
# 1️⃣ Importar app real
|
| 44 |
+
# ================================================================
|
| 45 |
+
import app2
|
| 46 |
+
app = app2.app # reusar FastAPI original
|
| 47 |
+
|
| 48 |
+
# ================================================================
|
| 49 |
+
# 2️⃣ Fake S3 e Fake Supabase
|
| 50 |
+
# ================================================================
|
| 51 |
+
LOCAL_ROOT = Path("./local_storage").resolve()
|
| 52 |
+
(LOCAL_ROOT / "imagens_originais").mkdir(parents=True, exist_ok=True)
|
| 53 |
+
(LOCAL_ROOT / "imagens_resultados").mkdir(parents=True, exist_ok=True)
|
| 54 |
+
|
| 55 |
+
class FakeS3:
|
| 56 |
+
def put_object(self, Bucket, Key, Body, ContentType):
|
| 57 |
+
dest = LOCAL_ROOT / Key
|
| 58 |
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
| 59 |
+
with open(dest, "wb") as f:
|
| 60 |
+
f.write(Body)
|
| 61 |
+
print(f"[FakeS3] gravado: {dest}")
|
| 62 |
+
|
| 63 |
+
def delete_object(self, Bucket, Key):
|
| 64 |
+
dest = LOCAL_ROOT / Key
|
| 65 |
+
try:
|
| 66 |
+
dest.unlink()
|
| 67 |
+
except: pass
|
| 68 |
+
|
| 69 |
+
def generate_presigned_url(self, *_args, **kwargs):
|
| 70 |
+
key = kwargs["Params"]["Key"]
|
| 71 |
+
print(f"[FakeS3] URL gerada local para {key}")
|
| 72 |
+
return f"file://{(LOCAL_ROOT / key).as_posix()}"
|
| 73 |
+
|
| 74 |
+
class _FakeResp:
|
| 75 |
+
def __init__(self, data): self.data = data
|
| 76 |
+
def execute(self): return self
|
| 77 |
+
|
| 78 |
+
class FakeTable:
|
| 79 |
+
def __init__(self, store): self.store = store
|
| 80 |
+
def insert(self, payload):
|
| 81 |
+
new_id = self.store["next_id"]
|
| 82 |
+
self.store["next_id"] += 1
|
| 83 |
+
row = dict(payload)
|
| 84 |
+
row["id"] = new_id
|
| 85 |
+
self.store["rows"][new_id] = row
|
| 86 |
+
print(f"[FakeSupabase] inserido id={new_id}")
|
| 87 |
+
return _FakeResp([row])
|
| 88 |
+
def select(self, *_cols):
|
| 89 |
+
class _Sel:
|
| 90 |
+
def __init__(self, table): self.table=table; self._id=None
|
| 91 |
+
def eq(self, fld, val):
|
| 92 |
+
if fld=="id": self._id = int(val)
|
| 93 |
+
return self
|
| 94 |
+
def single(self):
|
| 95 |
+
return _FakeResp(self.table.store["rows"].get(self._id))
|
| 96 |
+
return _Sel(self)
|
| 97 |
+
|
| 98 |
+
class FakeSupabase:
|
| 99 |
+
def __init__(self):
|
| 100 |
+
self.tables = {"amostras": {"next_id": 1, "rows": {}}}
|
| 101 |
+
def from_(self, name): return FakeTable(self.tables[name])
|
| 102 |
+
|
| 103 |
+
# Patchar os clientes globais do app
|
| 104 |
+
app2.s3_client = FakeS3()
|
| 105 |
+
app2.supabase_client = FakeSupabase()
|
| 106 |
+
|
| 107 |
+
# ================================================================
|
| 108 |
+
# 3️⃣ Interface Web Local (UI)
|
| 109 |
+
# ================================================================
|
| 110 |
+
@app.get("/ui", response_class=HTMLResponse)
|
| 111 |
+
def local_ui():
|
| 112 |
+
return """
|
| 113 |
+
<!DOCTYPE html>
|
| 114 |
+
<html lang="pt-br">
|
| 115 |
+
<head>
|
| 116 |
+
<meta charset="UTF-8"/>
|
| 117 |
+
<title>Teste Local - YOLO + Corrosão</title>
|
| 118 |
+
<style>
|
| 119 |
+
body { background:#0d1117; color:#e6edf3; font-family:Arial; padding:24px; }
|
| 120 |
+
h1 { font-size:20px; }
|
| 121 |
+
.card { background:#161b22; padding:20px; border-radius:12px; max-width:1100px; margin:auto; }
|
| 122 |
+
button { padding:10px 20px; background:#238636; border:none; color:white; border-radius:6px; cursor:pointer; }
|
| 123 |
+
button:hover { background:#2ea043; }
|
| 124 |
+
.grid { display:grid; gap:16px; }
|
| 125 |
+
.grid.crops { grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); }
|
| 126 |
+
.cropbox { background:#1f242c; padding:12px; border-radius:10px; }
|
| 127 |
+
img { width:100%; border-radius:6px; background:white; }
|
| 128 |
+
label { display:block; margin:10px 0 4px; }
|
| 129 |
+
select, input[type=file] { background:#0d1117; color:#e6edf3; border:1px solid #30363d; border-radius:6px; padding:8px; }
|
| 130 |
+
small { opacity:0.7; }
|
| 131 |
+
.badge { display:inline-block; background:#30363d; padding:4px 8px; border-radius:999px; font-size:12px; margin-left:8px; }
|
| 132 |
+
</style>
|
| 133 |
+
</head>
|
| 134 |
+
<body>
|
| 135 |
+
<div class="card">
|
| 136 |
+
<h1>Teste Local — YOLO detecta parafusos → OpenCV mede corrosão</h1>
|
| 137 |
+
<form id="form">
|
| 138 |
+
<label for="file">Imagem</label>
|
| 139 |
+
<input type="file" id="file" name="file" accept="image/*" required />
|
| 140 |
+
|
| 141 |
+
<label for="ctype">Tipo de corrosão</label>
|
| 142 |
+
<select id="ctype" name="corrosion_type">
|
| 143 |
+
<option value="white">Branca</option>
|
| 144 |
+
<option value="black">Preta</option>
|
| 145 |
+
<option value="red">Avermelhada</option>
|
| 146 |
+
</select>
|
| 147 |
+
|
| 148 |
+
<div style="margin-top:12px;">
|
| 149 |
+
<button>Enviar</button>
|
| 150 |
+
<span class="badge">Dica: teste com iluminação estável</span>
|
| 151 |
+
</div>
|
| 152 |
+
</form>
|
| 153 |
+
|
| 154 |
+
<div id="out" style="display:none; margin-top:20px;">
|
| 155 |
+
<h2>Detecções:</h2>
|
| 156 |
+
<p><strong id="detCount"></strong> <span class="badge" id="ctypeBadge"></span></p>
|
| 157 |
+
|
| 158 |
+
<h3>Imagem anotada:</h3>
|
| 159 |
+
<img id="annot"/>
|
| 160 |
+
|
| 161 |
+
<h3 style="margin-top:20px;">Resultados por parafuso (crop):</h3>
|
| 162 |
+
<div id="grid" class="grid crops"></div>
|
| 163 |
+
</div>
|
| 164 |
+
</div>
|
| 165 |
+
|
| 166 |
+
<script>
|
| 167 |
+
document.getElementById("form").addEventListener("submit", async e => {
|
| 168 |
+
e.preventDefault();
|
| 169 |
+
const fd = new FormData(e.target);
|
| 170 |
+
const res = await fetch("/analyze", { method:"POST", body:fd });
|
| 171 |
+
if(!res.ok){
|
| 172 |
+
const t = await res.text();
|
| 173 |
+
alert("Erro no processamento: " + t);
|
| 174 |
+
return;
|
| 175 |
+
}
|
| 176 |
+
const data = await res.json();
|
| 177 |
+
|
| 178 |
+
document.getElementById("detCount").textContent = data.detections_count + " parafusos detectados";
|
| 179 |
+
document.getElementById("ctypeBadge").textContent = "tipo: " + (data.corrosion_type || "white");
|
| 180 |
+
document.getElementById("annot").src = data.annotated_image;
|
| 181 |
+
|
| 182 |
+
const grid = document.getElementById("grid");
|
| 183 |
+
grid.innerHTML="";
|
| 184 |
+
data.detections.forEach(det => {
|
| 185 |
+
const a = det.analysis || {};
|
| 186 |
+
const div = document.createElement("div");
|
| 187 |
+
div.className="cropbox";
|
| 188 |
+
div.innerHTML = `
|
| 189 |
+
<strong>#${det.index} — ${det.class_name} (${det.score})</strong><br/>
|
| 190 |
+
Corrosão: ${a.percent ?? "?"}%<br/>
|
| 191 |
+
<small>Pixels: ${a.corrosion_pixels ?? "?"} / ${a.total_pixels ?? "?"}</small><br/><br/>
|
| 192 |
+
<img src="${a.isolated_image}" />
|
| 193 |
+
<img style="margin-top:8px;" src="${a.corrosion_image}" />
|
| 194 |
+
`;
|
| 195 |
+
grid.appendChild(div);
|
| 196 |
+
});
|
| 197 |
+
|
| 198 |
+
document.getElementById("out").style.display="block";
|
| 199 |
+
});
|
| 200 |
+
</script>
|
| 201 |
+
|
| 202 |
+
</body>
|
| 203 |
+
</html>
|
| 204 |
+
"""
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
# ================================================================
|
| 208 |
+
# 4️⃣ Subir servidor local
|
| 209 |
+
# ================================================================
|
| 210 |
+
if __name__ == "__main__":
|
| 211 |
+
print("\n✅ Desenvolvimento LOCAL iniciado!")
|
| 212 |
+
print("Abra: http://localhost:8000/ui\n")
|
| 213 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|