File size: 5,430 Bytes
9909d0e
 
 
 
 
 
 
 
 
 
 
a16d3e9
9909d0e
 
 
 
a16d3e9
 
 
 
 
 
 
9909d0e
 
 
a16d3e9
9909d0e
 
 
a16d3e9
 
 
 
 
9909d0e
 
 
a16d3e9
9909d0e
a16d3e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9909d0e
 
a16d3e9
 
 
 
 
 
 
 
 
 
 
 
9909d0e
 
 
a16d3e9
9909d0e
 
 
a16d3e9
 
9909d0e
 
 
 
 
 
a16d3e9
9909d0e
 
 
 
 
 
 
a16d3e9
 
9909d0e
a16d3e9
 
9909d0e
 
 
a16d3e9
9909d0e
 
 
 
 
a16d3e9
9909d0e
 
 
a16d3e9
9909d0e
 
 
 
a16d3e9
 
 
 
 
 
9909d0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a16d3e9
9909d0e
 
a16d3e9
9909d0e
 
 
a16d3e9
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
import streamlit as st
import tensorflow_datasets as tfds
import tensorflow as tf
import numpy as np
import time
import tensorflow.keras as keras
from tensorflow.keras.applications import VGG16
from tensorflow.keras.layers import Dense, Flatten
from tensorflow.keras.models import Model, load_model
from datasets import load_dataset
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
import seaborn as sns
from huggingface_hub import HfApi
import os


# πŸ“Œ Percorso della cartella dove sarΓ  salvato il dataset se uso TFlow, non serve se setto hf_dataset_cache
#DATA_DIR = "/app" #"/tmp"


# πŸ“Œ Autenticazione Hugging Face dal Secret nello Space
HF_TOKEN = os.getenv("HF_TOKEN")
os.environ["HF_HOME"] = "/app/.cache"
os.environ["HF_DATASETS_CACHE"] = "/app/.cache"


if HF_TOKEN:
    api = HfApi()
    user_info = api.whoami(HF_TOKEN)

    if "name" in user_info:
        st.write(f"βœ… Autenticato come {user_info['name']}")
    else:
        st.warning("⚠️ Token API non valido! Controlla il Secret nello Space.")
else:
    st.warning("⚠️ Nessun token API trovato! Verifica il Secret nello Space.")

# πŸ“Œ Carica solo 300 immagini da `imagenet_resized/64x64`
st.write("πŸ”„ Caricamento di 300 immagini da `tiny-imagenet`...")

# πŸ“Œ Recupera il valore della variabile d'ambiente
hf_cache_path = os.getenv("HF_DATASETS_CACHE", "❌ Variabile non impostata!")

# πŸ”Ή Mostra il valore nella UI di Streamlit
st.write(f"πŸ“‚ Cache dei dataset Hugging Face: {hf_cache_path}")

# πŸ“Œ Testa se la cache ha i permessi giusti PRIMA di caricare il dataset
test_file = "/app/.cache/test.txt"
try:
    with open(test_file, "w") as f:
        f.write("Test permessi OK!")
    st.write("βœ… La cartella ha i permessi giusti!")
except PermissionError:
    st.error("❌ ERRORE: La cartella /app/.cache non ha permessi di scrittura!")



# πŸ“Œ Carica il dataset direttamente da Hugging Face
os.environ["HF_HOME"] = "/tmp/huggingface"
os.environ["HF_DATASETS_CACHE"] = "/tmp/huggingface"
os.makedirs(os.getenv("HF_DATASETS_CACHE"), exist_ok=True)
dataset = load_dataset("zh-plus/tiny-imagenet", split="train")

# πŸ“Œ Recupera il primo esempio
sample = dataset[0]
image = sample["image"]
label = sample["label"]

# πŸ“Œ Mostra l'immagine e la classe in Streamlit
st.image(image, caption=f"Classe: {label}", use_container_width=True)
st.write(f"πŸ”Ž Esempio dal dataset: {sample}")

#Carica il dataset esterno da imagenet PER TENSORFLOW
#imagenet = tfds.load("imagenet_resized/64x64", split="train", as_supervised=True, download=True, data_dir=DATA_DIR)

image_list = []
label_list = []

#for i, (image, label) in enumerate(imagenet.take(300)):  # Prende solo 300 immagini  PER TENSORFLOW 
for i, sample in enumerate(dataset):
    if i >= 300:  # Prende solo 300 immagini
        break

    image = tf.image.resize(image, (64, 64)) / 255.0  # Normalizzazione
    image_list.append(image.numpy())
    label_list.append(np.array(sample["label"]))  

X_train = np.array(image_list)
y_train = np.array(label_list)

st.write(f"βœ… Scaricate e preprocessate {len(X_train)} immagini da `tiny-imagene/64x64`!")

# πŸ“Œ Caricamento del modello
if os.path.exists("Silva.h5"):
    model = load_model("Silva.h5")
    st.write("βœ… Modello `Silva.h5` caricato, nessun nuovo training necessario!")
else:
    st.write("πŸš€ Training in corso perchΓ© `Silva.h5` non esiste...")

    # Caricare il modello VGG16 pre-addestrato
    base_model = VGG16(weights="imagenet", include_top=False, input_shape=(64, 64, 3))

    # Congelare i livelli convoluzionali
    for layer in base_model.layers:
        layer.trainable = False

    # Aggiungere nuovi livelli Dense
    x = Flatten()(base_model.output)
    x = Dense(256, activation="relu")(x)
    x = Dense(128, activation="relu")(x)
    output = Dense(len(set(y_train)), activation="softmax")(x)

    # Creare il modello finale
    model = Model(inputs=base_model.input, outputs=output)
    model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"])

    # πŸ“Œ Barra di progresso del training
    progress_bar = st.progress(0)
    status_text = st.empty()
    start_time = time.time()

    # πŸ“Œ Addestramento con progress bar
    for epoch in range(10):
        history = model.fit(X_train, y_train, epochs=1)
        progress_bar.progress((epoch + 1) / 10)
        elapsed_time = time.time() - start_time
        status_text.text(f"⏳ Tempo rimanente stimato: {int(elapsed_time / (epoch + 1) * (10 - (epoch + 1)))} secondi")

    st.write("βœ… Addestramento completato!")

    # πŸ“Œ Salvare il modello
    model.save("Silva.h5")
    st.write("βœ… Modello salvato come `Silva.h5`!")

# πŸ“Œ Bottone per scaricare il modello
if os.path.exists("Silva.h5"):
    with open("Silva.h5", "rb") as f:
        st.download_button(
            label="πŸ“₯ Scarica il modello Silva.h5",
            data=f,
            file_name="Silva.h5",
            mime="application/octet-stream"
        )

# πŸ“Œ Bottone per caricare il modello su Hugging Face
def upload_model():
    api.upload_file(
        path_or_fileobj="Silva.h5",
        path_in_repo="Silva.h5",
        repo_id="scontess/trainigVVG16",   #"scontess/Silva",
        repo_type="space"
    )
    st.success("βœ… Modello 'Silva' caricato su Hugging Face!")

st.write("πŸ“₯ Carica il modello Silva su Hugging Face")
if st.button("πŸš€ Carica Silva su Model Store"):
    upload_model()