Spaces:
Runtime error
Runtime error
Upload 7 files
Browse files- aimodel.py +3 -17
- aiutils.py +75 -0
- client.py +24 -3
- utils.py +1 -1
aimodel.py
CHANGED
|
@@ -6,9 +6,9 @@ import uuid
|
|
| 6 |
import re
|
| 7 |
from fastai.vision.all import *
|
| 8 |
from pathlib import Path
|
| 9 |
-
import torch.nn as nn
|
| 10 |
import random
|
| 11 |
import shutil
|
|
|
|
| 12 |
|
| 13 |
MEMORY_SIZE = 50
|
| 14 |
SUCCESS_MEMORY_RATIO = 0.5
|
|
@@ -49,6 +49,7 @@ def get_memory_samples(n_samples=None):
|
|
| 49 |
return memory_samples
|
| 50 |
|
| 51 |
def prepare_dataset():
|
|
|
|
| 52 |
dataset_dir = Path(utils.DATASET_DIR)
|
| 53 |
dataset_dir.mkdir(parents=True, exist_ok=True)
|
| 54 |
for item in dataset_dir.iterdir():
|
|
@@ -98,22 +99,7 @@ def train_model():
|
|
| 98 |
num_classes = len(dls.vocab)
|
| 99 |
|
| 100 |
# Criar um novo Learner com o número correto de classes
|
| 101 |
-
learn =
|
| 102 |
-
|
| 103 |
-
if os.path.exists(utils.MODEL_PATH):
|
| 104 |
-
try:
|
| 105 |
-
# Carregar o modelo completo (incluindo a camada de classificação antiga)
|
| 106 |
-
learn.load(utils.MODEL_PATH.replace(".pkl", ""))
|
| 107 |
-
logging.info("Modelo existente carregado.")
|
| 108 |
-
|
| 109 |
-
# Substituir a camada de classificação (a última camada linear)
|
| 110 |
-
# Precisamos acessar o modelo subjacente (PyTorch) para fazer isso
|
| 111 |
-
num_ftrs = learn.model.fc.in_features
|
| 112 |
-
learn.model.fc = nn.Linear(num_ftrs, num_classes).to(learn.model.fc.weight.device)
|
| 113 |
-
logging.info("Camada de classificação substituída.")
|
| 114 |
-
|
| 115 |
-
except Exception as e:
|
| 116 |
-
logging.error(f"Erro ao carregar o modelo existente: {e}. Treinando do zero.")
|
| 117 |
|
| 118 |
learn.fine_tune(5)
|
| 119 |
learn.export(utils.MODEL_PATH)
|
|
|
|
| 6 |
import re
|
| 7 |
from fastai.vision.all import *
|
| 8 |
from pathlib import Path
|
|
|
|
| 9 |
import random
|
| 10 |
import shutil
|
| 11 |
+
import aiutils
|
| 12 |
|
| 13 |
MEMORY_SIZE = 50
|
| 14 |
SUCCESS_MEMORY_RATIO = 0.5
|
|
|
|
| 49 |
return memory_samples
|
| 50 |
|
| 51 |
def prepare_dataset():
|
| 52 |
+
aiutils.prepare_dirs()
|
| 53 |
dataset_dir = Path(utils.DATASET_DIR)
|
| 54 |
dataset_dir.mkdir(parents=True, exist_ok=True)
|
| 55 |
for item in dataset_dir.iterdir():
|
|
|
|
| 99 |
num_classes = len(dls.vocab)
|
| 100 |
|
| 101 |
# Criar um novo Learner com o número correto de classes
|
| 102 |
+
learn = aiutils.get_learner()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
|
| 104 |
learn.fine_tune(5)
|
| 105 |
learn.export(utils.MODEL_PATH)
|
aiutils.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastai.vision.all import *
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import utils
|
| 4 |
+
import os
|
| 5 |
+
import logging
|
| 6 |
+
import random
|
| 7 |
+
import json
|
| 8 |
+
|
| 9 |
+
MEMORY_SIZE = 50
|
| 10 |
+
SUCCESS_MEMORY_RATIO = 0.5
|
| 11 |
+
|
| 12 |
+
def load_success_fail_data(path):
|
| 13 |
+
datas = []
|
| 14 |
+
if os.path.exists(path):
|
| 15 |
+
try:
|
| 16 |
+
with open(path, "r") as f:
|
| 17 |
+
datas = json.load(f)
|
| 18 |
+
except json.JSONDecodeError:
|
| 19 |
+
logging.error(f"JSONDecodeError in {path}")
|
| 20 |
+
return datas
|
| 21 |
+
|
| 22 |
+
def get_memory_samples(n_samples=None):
|
| 23 |
+
success_data = load_success_fail_data(utils.SUCCESS_PATH)
|
| 24 |
+
fail_data = load_success_fail_data(utils.FAIL_PATH)
|
| 25 |
+
|
| 26 |
+
memory_samples = []
|
| 27 |
+
num_success = int((n_samples if n_samples else MEMORY_SIZE) * SUCCESS_MEMORY_RATIO)
|
| 28 |
+
num_fail = (n_samples if n_samples else MEMORY_SIZE) - num_success
|
| 29 |
+
|
| 30 |
+
if success_data:
|
| 31 |
+
sampled_success = random.sample(success_data, min(num_success, len(success_data)))
|
| 32 |
+
for item in sampled_success:
|
| 33 |
+
memory_samples.append({'url': item['url'], 'type': item['predicted']})
|
| 34 |
+
|
| 35 |
+
if fail_data:
|
| 36 |
+
sampled_fail = random.sample(fail_data, min(num_fail, len(fail_data)))
|
| 37 |
+
for item in sampled_fail:
|
| 38 |
+
memory_samples.append({'url': item['url'], 'type': item['correct']})
|
| 39 |
+
|
| 40 |
+
if n_samples is not None and len(memory_samples) > n_samples:
|
| 41 |
+
return random.sample(memory_samples, n_samples)
|
| 42 |
+
elif n_samples is None and len(memory_samples) > MEMORY_SIZE:
|
| 43 |
+
return random.sample(memory_samples, MEMORY_SIZE)
|
| 44 |
+
else:
|
| 45 |
+
return memory_samples
|
| 46 |
+
|
| 47 |
+
def prepare_dirs():
|
| 48 |
+
base_dir = utils.BASE_DIR
|
| 49 |
+
os.makedirs(base_dir, exist_ok=True) # Creates the base directory if it doesn't exist
|
| 50 |
+
|
| 51 |
+
campaign_types = ["DEMAND", "OFFER", "PROZIS", "NO_CAMPAIGN"]
|
| 52 |
+
|
| 53 |
+
for campaign_type in campaign_types:
|
| 54 |
+
campaign_folder = os.path.join(base_dir, campaign_type.lower())
|
| 55 |
+
os.makedirs(campaign_folder, exist_ok=True)
|
| 56 |
+
print(f"Folder created: {campaign_folder}")
|
| 57 |
+
|
| 58 |
+
def get_learner():
|
| 59 |
+
learn = vision_learner(dls, resnet18, metrics=accuracy, pretrained=True)
|
| 60 |
+
|
| 61 |
+
if os.path.exists(utils.MODEL_PATH):
|
| 62 |
+
try:
|
| 63 |
+
# Carregar o modelo completo (incluindo a camada de classificação antiga)
|
| 64 |
+
learn.load(utils.MODEL_PATH.replace(".pkl", ""))
|
| 65 |
+
logging.info("Modelo existente carregado.")
|
| 66 |
+
|
| 67 |
+
# Substituir a camada de classificação (a última camada linear)
|
| 68 |
+
# Precisamos acessar o modelo subjacente (PyTorch) para fazer isso
|
| 69 |
+
num_ftrs = learn.model.fc.in_features
|
| 70 |
+
learn.model.fc = nn.Linear(num_ftrs, num_classes).to(learn.model.fc.weight.device)
|
| 71 |
+
logging.info("Camada de classificação substituída.")
|
| 72 |
+
|
| 73 |
+
except Exception as e:
|
| 74 |
+
logging.error(f"Erro ao carregar o modelo existente: {e}. Treinando do zero.")
|
| 75 |
+
|
client.py
CHANGED
|
@@ -9,7 +9,7 @@ API_URL = "https://marioprzbasto-campaign-detector.hf.space"
|
|
| 9 |
|
| 10 |
st.title("Classificador de Campanhas Prozis")
|
| 11 |
|
| 12 |
-
opcao = st.selectbox("Escolha a ação:", ["Success", "Fail", "Upload Model", "Classificar", "Feedback", "Bulk Classification", "URLs"])
|
| 13 |
|
| 14 |
def load_image_from_url(url):
|
| 15 |
try:
|
|
@@ -38,7 +38,7 @@ if opcao == "Classificar":
|
|
| 38 |
|
| 39 |
if st.button("Classificar"):
|
| 40 |
if image_url:
|
| 41 |
-
response = requests.post(f"{API_URL}/predict", data={"url": image_url})
|
| 42 |
if response.status_code == 200:
|
| 43 |
st.success(response.json())
|
| 44 |
else:
|
|
@@ -181,6 +181,8 @@ elif opcao == "Success":
|
|
| 181 |
with col1:
|
| 182 |
st.image(img, caption="Imagem de sucesso", use_container_width=True)
|
| 183 |
with col2:
|
|
|
|
|
|
|
| 184 |
st.write(f"**URL:** {item['url']}")
|
| 185 |
if 'predicted' in item:
|
| 186 |
st.write(f"**Previsto:** {item['predicted']}")
|
|
@@ -206,6 +208,8 @@ elif opcao == "Fail":
|
|
| 206 |
with col1:
|
| 207 |
st.image(img, caption="Imagem de falha", use_container_width=True)
|
| 208 |
with col2:
|
|
|
|
|
|
|
| 209 |
st.write(f"**URL:** {item['url']}")
|
| 210 |
if 'predicted' in item:
|
| 211 |
st.write(f"**Previsto:** {item['predicted']}")
|
|
@@ -232,4 +236,21 @@ elif opcao == "Upload Model":
|
|
| 232 |
except requests.exceptions.RequestException as e:
|
| 233 |
st.error(f"Erro ao enviar o modelo: {e}")
|
| 234 |
if response is not None:
|
| 235 |
-
st.error(f"Detalhes do erro: {response.text}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
st.title("Classificador de Campanhas Prozis")
|
| 11 |
|
| 12 |
+
opcao = st.selectbox("Escolha a ação:", ["Success", "Fail", "Upload Model", "Classificar", "Feedback", "Bulk Classification", "URLs", "Download da Pasta /tmp"])
|
| 13 |
|
| 14 |
def load_image_from_url(url):
|
| 15 |
try:
|
|
|
|
| 38 |
|
| 39 |
if st.button("Classificar"):
|
| 40 |
if image_url:
|
| 41 |
+
response = requests.post(f"{API_URL}/predict", data={"id": str(uuid.uuid4()), "url": image_url})
|
| 42 |
if response.status_code == 200:
|
| 43 |
st.success(response.json())
|
| 44 |
else:
|
|
|
|
| 181 |
with col1:
|
| 182 |
st.image(img, caption="Imagem de sucesso", use_container_width=True)
|
| 183 |
with col2:
|
| 184 |
+
if 'id' in item:
|
| 185 |
+
st.write(f"**ID:** {item['id']}")
|
| 186 |
st.write(f"**URL:** {item['url']}")
|
| 187 |
if 'predicted' in item:
|
| 188 |
st.write(f"**Previsto:** {item['predicted']}")
|
|
|
|
| 208 |
with col1:
|
| 209 |
st.image(img, caption="Imagem de falha", use_container_width=True)
|
| 210 |
with col2:
|
| 211 |
+
if 'id' in item:
|
| 212 |
+
st.write(f"**ID:** {item['id']}")
|
| 213 |
st.write(f"**URL:** {item['url']}")
|
| 214 |
if 'predicted' in item:
|
| 215 |
st.write(f"**Previsto:** {item['predicted']}")
|
|
|
|
| 236 |
except requests.exceptions.RequestException as e:
|
| 237 |
st.error(f"Erro ao enviar o modelo: {e}")
|
| 238 |
if response is not None:
|
| 239 |
+
st.error(f"Detalhes do erro: {response.text}")
|
| 240 |
+
|
| 241 |
+
elif opcao == "Download da Pasta /tmp":
|
| 242 |
+
st.subheader("Download da Pasta /tmp como ZIP")
|
| 243 |
+
if st.button("Gerar e Baixar ZIP"):
|
| 244 |
+
try:
|
| 245 |
+
response = requests.get(f"{API_URL}/download_selected_tmp", stream=True)
|
| 246 |
+
response.raise_for_status()
|
| 247 |
+
st.download_button(
|
| 248 |
+
label="Clique para Baixar /tmp.zip",
|
| 249 |
+
data=response.content,
|
| 250 |
+
file_name="tmp_contents.zip",
|
| 251 |
+
mime="application/zip",
|
| 252 |
+
)
|
| 253 |
+
except requests.exceptions.RequestException as e:
|
| 254 |
+
st.error(f"Erro ao solicitar o download: {e}")
|
| 255 |
+
if response is not None:
|
| 256 |
+
st.error(f"Detalhes do erro: {response.status_code} - {response.text}")
|
utils.py
CHANGED
|
@@ -10,7 +10,7 @@ PREDICT_DIR = "/tmp/predict"
|
|
| 10 |
MODEL_PATH = "/tmp/model.pkl"
|
| 11 |
FAIL_PATH = "/tmp/fails.json"
|
| 12 |
SUCCESS_PATH = "/tmp/success.json"
|
| 13 |
-
ZIP_PATH = "/tmp"
|
| 14 |
MAX_JSON_SIZE = 100
|
| 15 |
|
| 16 |
def truncate_json(file_path):
|
|
|
|
| 10 |
MODEL_PATH = "/tmp/model.pkl"
|
| 11 |
FAIL_PATH = "/tmp/fails.json"
|
| 12 |
SUCCESS_PATH = "/tmp/success.json"
|
| 13 |
+
ZIP_PATH = "/tmp/my_app_temp/download.zip"
|
| 14 |
MAX_JSON_SIZE = 100
|
| 15 |
|
| 16 |
def truncate_json(file_path):
|