Spaces:
Sleeping
Sleeping
Commit ·
0c6fe9c
1
Parent(s): 1ad9db6
aggiunto monitoraggio accessi
Browse files- app.py +95 -31
- data/logs/access_logs.csv +0 -0
- modules/utilities/logger.py +76 -0
app.py
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import cv2
|
| 3 |
import os
|
|
@@ -37,42 +39,95 @@ if not os.path.exists(demo_csv_path):
|
|
| 37 |
with open(demo_csv_path, "w") as f:
|
| 38 |
f.write(csv_content)
|
| 39 |
|
| 40 |
-
def forecast_logic(file):
|
|
|
|
|
|
|
| 41 |
if file is None: raise gr.Error("Seleziona un file CSV")
|
| 42 |
if isinstance(file, list): file = file[0]
|
| 43 |
|
| 44 |
img, text = forecast.predict_workload(file)
|
|
|
|
| 45 |
if img is None: raise gr.Error(text)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
return img, text
|
| 47 |
|
| 48 |
-
def binary_classification(text):
|
| 49 |
-
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
-
def
|
| 53 |
-
if text.strip():
|
| 54 |
-
try: return multi(text)
|
| 55 |
-
except Exception as e: raise gr.Error(f'Errore nel modello: {str(e)}')
|
| 56 |
-
raise gr.Error('Il testo è obbligatorio!')
|
| 57 |
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
if file: return cv2.imread(file)
|
| 61 |
-
return None
|
| 62 |
-
|
| 63 |
-
def image_classification(img):
|
| 64 |
-
if img is not None: return image(img)
|
| 65 |
-
raise gr.Error('L\'immagine è obbligatoria!')
|
| 66 |
-
|
| 67 |
-
def retina_classification(retina):
|
| 68 |
-
if retina is not None: return retina_detector(retina)
|
| 69 |
-
raise gr.Error('L\'immagine è obbligatoria!')
|
| 70 |
-
|
| 71 |
-
def bpo_dispatch_logic(text):
|
| 72 |
-
"""
|
| 73 |
-
Funzione Ponte: Chiama il modulo AI e decide l'azione di business.
|
| 74 |
-
Restituisce un aggiornamento COMPLETO del componente NER per pulire la grafica.
|
| 75 |
-
"""
|
| 76 |
try:
|
| 77 |
intent, urgency, entities = predict_bpo_ticket(text)
|
| 78 |
|
|
@@ -91,6 +146,15 @@ def bpo_dispatch_logic(text):
|
|
| 91 |
|
| 92 |
html_output = utils.render_ner_html(entities)
|
| 93 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
return intent, urgency, action, html_output
|
| 95 |
|
| 96 |
except Exception as e:
|
|
@@ -273,7 +337,7 @@ with gr.Blocks(title="NGT AI Platform", theme=theme, css_paths="style.css") as d
|
|
| 273 |
|
| 274 |
# 4. COLLEGAMENTO FUNZIONE
|
| 275 |
sentiment_btn.click(
|
| 276 |
-
fn=
|
| 277 |
inputs=sentiment_input,
|
| 278 |
outputs=sentiment_output
|
| 279 |
)
|
|
@@ -322,7 +386,7 @@ with gr.Blocks(title="NGT AI Platform", theme=theme, css_paths="style.css") as d
|
|
| 322 |
# Usiamo un Label con top_classes=5 per vedere la distribuzione completa
|
| 323 |
multi_output = gr.Label(num_top_classes=5, label="Confidenza del Modello")
|
| 324 |
|
| 325 |
-
analyze_btn_multi.click(
|
| 326 |
|
| 327 |
# --- Chest X-Ray Diagnostics ---
|
| 328 |
with gr.Tab("🩻 Chest X-Ray Diagnostics") as tab_xray:
|
|
@@ -351,7 +415,7 @@ with gr.Blocks(title="NGT AI Platform", theme=theme, css_paths="style.css") as d
|
|
| 351 |
gr.Markdown("#### 📋 Referto AI", elem_classes="h4-margin")
|
| 352 |
output_label = gr.Label(num_top_classes=4, label="Probabilità Patologia")
|
| 353 |
|
| 354 |
-
analyze_btn_img.click(
|
| 355 |
|
| 356 |
# --- Diabetic Retinopathy ---
|
| 357 |
with gr.Tab("👁️ Diabetic Retinopathy") as tab_retina:
|
|
@@ -384,7 +448,7 @@ with gr.Blocks(title="NGT AI Platform", theme=theme, css_paths="style.css") as d
|
|
| 384 |
output_dr_prob = gr.Label(label="Livello di Confidenza (Rischio)")
|
| 385 |
|
| 386 |
analyze_btn_dr.click(
|
| 387 |
-
|
| 388 |
inputs=image_input_dr,
|
| 389 |
outputs=[output_dr_diagnosis, output_dr_prob]
|
| 390 |
)
|
|
|
|
| 1 |
+
from modules.utilities import logger
|
| 2 |
+
import time
|
| 3 |
import gradio as gr
|
| 4 |
import cv2
|
| 5 |
import os
|
|
|
|
| 39 |
with open(demo_csv_path, "w") as f:
|
| 40 |
f.write(csv_content)
|
| 41 |
|
| 42 |
+
def forecast_logic(file, request: gr.Request):
|
| 43 |
+
start_time = time.time()
|
| 44 |
+
|
| 45 |
if file is None: raise gr.Error("Seleziona un file CSV")
|
| 46 |
if isinstance(file, list): file = file[0]
|
| 47 |
|
| 48 |
img, text = forecast.predict_workload(file)
|
| 49 |
+
|
| 50 |
if img is None: raise gr.Error(text)
|
| 51 |
+
|
| 52 |
+
elapsed_time = time.time() - start_time
|
| 53 |
+
logger.log_interaction(
|
| 54 |
+
request=request,
|
| 55 |
+
module_name="AI Forecaster",
|
| 56 |
+
action="Prediction",
|
| 57 |
+
input_data=file,
|
| 58 |
+
execution_time=elapsed_time
|
| 59 |
+
)
|
| 60 |
return img, text
|
| 61 |
|
| 62 |
+
def binary_classification(text, request: gr.Request):
|
| 63 |
+
start_time = time.time()
|
| 64 |
+
|
| 65 |
+
if not text.strip():
|
| 66 |
+
raise gr.Error('Il testo è obbligatorio!')
|
| 67 |
+
result = binary(text)
|
| 68 |
+
|
| 69 |
+
elapsed_time = time.time() - start_time
|
| 70 |
+
logger.log_interaction(
|
| 71 |
+
request=request,
|
| 72 |
+
module_name="Sentiment Analysis (BPO)",
|
| 73 |
+
action="Prediction",
|
| 74 |
+
input_data=text,
|
| 75 |
+
execution_time=elapsed_time
|
| 76 |
+
)
|
| 77 |
+
return result
|
| 78 |
+
|
| 79 |
+
def multi_classification(text, request: gr.Request):
|
| 80 |
+
start_time = time.time()
|
| 81 |
+
|
| 82 |
+
if not text.strip():
|
| 83 |
+
raise gr.Error('Il testo è obbligatorio!')
|
| 84 |
+
|
| 85 |
+
try:
|
| 86 |
+
result = multi(text)
|
| 87 |
+
|
| 88 |
+
elapsed_time = time.time() - start_time
|
| 89 |
+
logger.log_interaction(
|
| 90 |
+
request=request,
|
| 91 |
+
module_name="Smart Content Tagger",
|
| 92 |
+
action="Prediction",
|
| 93 |
+
input_data=text,
|
| 94 |
+
execution_time=elapsed_time
|
| 95 |
+
)
|
| 96 |
+
return result
|
| 97 |
+
|
| 98 |
+
except Exception as e:
|
| 99 |
+
raise gr.Error(f'Errore nel modello: {str(e)}')
|
| 100 |
+
|
| 101 |
+
def image_classification(img, request: gr.Request):
|
| 102 |
+
start_time = time.time()
|
| 103 |
+
result = image(img)
|
| 104 |
+
elapsed_time = time.time() - start_time
|
| 105 |
+
logger.log_interaction(
|
| 106 |
+
request=request,
|
| 107 |
+
module_name="Chest X-Ray",
|
| 108 |
+
action="Prediction",
|
| 109 |
+
input_data=img,
|
| 110 |
+
execution_time=elapsed_time
|
| 111 |
+
)
|
| 112 |
+
return result
|
| 113 |
+
|
| 114 |
+
def retina_classification(retina, request: gr.Request):
|
| 115 |
+
start_time = time.time()
|
| 116 |
+
result = retina_detector(retina)
|
| 117 |
+
elapsed_time = time.time() - start_time
|
| 118 |
+
logger.log_interaction(
|
| 119 |
+
request=request,
|
| 120 |
+
module_name="Diabetic Retinopathy",
|
| 121 |
+
action="Prediction",
|
| 122 |
+
input_data=retina,
|
| 123 |
+
execution_time=elapsed_time
|
| 124 |
+
)
|
| 125 |
+
return result
|
| 126 |
|
| 127 |
+
def bpo_dispatch_logic(text, request: gr.Request):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
|
| 129 |
+
start_time = time.time()
|
| 130 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
try:
|
| 132 |
intent, urgency, entities = predict_bpo_ticket(text)
|
| 133 |
|
|
|
|
| 146 |
|
| 147 |
html_output = utils.render_ner_html(entities)
|
| 148 |
|
| 149 |
+
elapsed_time = time.time() - start_time
|
| 150 |
+
logger.log_interaction(
|
| 151 |
+
request=request,
|
| 152 |
+
module_name="BPO Dispatcher",
|
| 153 |
+
action="Prediction",
|
| 154 |
+
input_data=text,
|
| 155 |
+
execution_time=elapsed_time
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
return intent, urgency, action, html_output
|
| 159 |
|
| 160 |
except Exception as e:
|
|
|
|
| 337 |
|
| 338 |
# 4. COLLEGAMENTO FUNZIONE
|
| 339 |
sentiment_btn.click(
|
| 340 |
+
fn=binary_classification,
|
| 341 |
inputs=sentiment_input,
|
| 342 |
outputs=sentiment_output
|
| 343 |
)
|
|
|
|
| 386 |
# Usiamo un Label con top_classes=5 per vedere la distribuzione completa
|
| 387 |
multi_output = gr.Label(num_top_classes=5, label="Confidenza del Modello")
|
| 388 |
|
| 389 |
+
analyze_btn_multi.click(multi_classification, inputs=multi_input, outputs=multi_output)
|
| 390 |
|
| 391 |
# --- Chest X-Ray Diagnostics ---
|
| 392 |
with gr.Tab("🩻 Chest X-Ray Diagnostics") as tab_xray:
|
|
|
|
| 415 |
gr.Markdown("#### 📋 Referto AI", elem_classes="h4-margin")
|
| 416 |
output_label = gr.Label(num_top_classes=4, label="Probabilità Patologia")
|
| 417 |
|
| 418 |
+
analyze_btn_img.click(image_classification, inputs=image_input, outputs=output_label)
|
| 419 |
|
| 420 |
# --- Diabetic Retinopathy ---
|
| 421 |
with gr.Tab("👁️ Diabetic Retinopathy") as tab_retina:
|
|
|
|
| 448 |
output_dr_prob = gr.Label(label="Livello di Confidenza (Rischio)")
|
| 449 |
|
| 450 |
analyze_btn_dr.click(
|
| 451 |
+
retina_classification,
|
| 452 |
inputs=image_input_dr,
|
| 453 |
outputs=[output_dr_diagnosis, output_dr_prob]
|
| 454 |
)
|
data/logs/access_logs.csv
ADDED
|
File without changes
|
modules/utilities/logger.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import uuid
|
| 3 |
+
import csv
|
| 4 |
+
import threading
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from huggingface_hub import CommitScheduler
|
| 8 |
+
import gradio as gr
|
| 9 |
+
|
| 10 |
+
# --- CONFIGURAZIONE ---
|
| 11 |
+
DATASET_REPO_ID = "NextGenTech/ngt-ai-platform-logs"
|
| 12 |
+
LOG_DIR = Path("data/logs")
|
| 13 |
+
LOG_FILE = LOG_DIR / "access_logs.csv"
|
| 14 |
+
TIME = 5 #intervallo di scrittura dei log sul dataset
|
| 15 |
+
|
| 16 |
+
LOG_DIR.mkdir(parents=True, exist_ok=True)
|
| 17 |
+
|
| 18 |
+
if not LOG_FILE.exists():
|
| 19 |
+
with open(LOG_FILE, "w", newline="", encoding="utf-8") as f:
|
| 20 |
+
writer = csv.writer(f)
|
| 21 |
+
writer.writerow([
|
| 22 |
+
"timestamp", "session_id", "module", "action",
|
| 23 |
+
"ip_address", "user_agent", "language", "input_size", "processing_time"
|
| 24 |
+
])
|
| 25 |
+
|
| 26 |
+
scheduler = CommitScheduler(
|
| 27 |
+
repo_id=DATASET_REPO_ID,
|
| 28 |
+
repo_type="dataset",
|
| 29 |
+
folder_path=LOG_DIR,
|
| 30 |
+
path_in_repo="logs",
|
| 31 |
+
every=TIME,
|
| 32 |
+
token=os.environ.get("HF_TOKEN_WRITE")
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
def log_interaction(request: gr.Request, module_name: str, action: str, input_data=None, execution_time=0.0):
|
| 36 |
+
"""
|
| 37 |
+
Registra un evento di analytics in modo invisibile.
|
| 38 |
+
"""
|
| 39 |
+
try:
|
| 40 |
+
|
| 41 |
+
if request:
|
| 42 |
+
headers = request.headers
|
| 43 |
+
ip = headers.get("x-forwarded-for", request.client.host)
|
| 44 |
+
user_agent = headers.get("user-agent", "Unknown")
|
| 45 |
+
language = headers.get("accept-language", "Unknown").split(',')[0]
|
| 46 |
+
else:
|
| 47 |
+
ip, user_agent, language = "LOCAL", "Dev-Mode", "it"
|
| 48 |
+
|
| 49 |
+
session_raw = f"{ip}{user_agent}{datetime.now().date()}"
|
| 50 |
+
session_id = str(uuid.uuid5(uuid.NAMESPACE_DNS, session_raw))[:8]
|
| 51 |
+
|
| 52 |
+
input_meta = "0"
|
| 53 |
+
if isinstance(input_data, str):
|
| 54 |
+
input_meta = f"{len(input_data)} chars"
|
| 55 |
+
elif hasattr(input_data, 'shape'): # Immagini numpy
|
| 56 |
+
input_meta = f"{input_data.shape}"
|
| 57 |
+
elif input_data is not None:
|
| 58 |
+
input_meta = "Binary/File"
|
| 59 |
+
|
| 60 |
+
with scheduler.lock:
|
| 61 |
+
with open(LOG_FILE, "a", newline="", encoding="utf-8") as f:
|
| 62 |
+
writer = csv.writer(f)
|
| 63 |
+
writer.writerow([
|
| 64 |
+
datetime.now().isoformat(),
|
| 65 |
+
session_id,
|
| 66 |
+
module_name,
|
| 67 |
+
action,
|
| 68 |
+
ip,
|
| 69 |
+
user_agent,
|
| 70 |
+
language,
|
| 71 |
+
input_meta,
|
| 72 |
+
f"{execution_time:.4f}s"
|
| 73 |
+
])
|
| 74 |
+
|
| 75 |
+
except Exception as e:
|
| 76 |
+
print(f"⚠️ Errore durante il logging: {e}")
|