Spaces:
Runtime error
Runtime error
Upload app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
+
import os, glob, uuid, random, json, pymysql, gradio as gr
|
| 3 |
+
from typing import List, Dict, Any
|
| 4 |
+
|
| 5 |
+
IMAGE_DIR = os.getenv("IMAGE_DIR","assets")
|
| 6 |
+
SENTIMENTS_PATH = os.getenv("SENTIMENTS_PATH", os.path.join(IMAGE_DIR,"sentiments.json"))
|
| 7 |
+
IMG_EXTS = (".png",".jpg",".jpeg",".webp",".bmp",".gif")
|
| 8 |
+
POLL_TYPE="sentiment"
|
| 9 |
+
DEFAULT_SENTIMENTS=["Très négatif","Négatif","Neutre","Positif","Très positif"]
|
| 10 |
+
|
| 11 |
+
DB_HOST=os.getenv("DB_HOST"); DB_PORT=int(os.getenv("DB_PORT","3306"))
|
| 12 |
+
DB_NAME=os.getenv("DB_NAME"); DB_USER=os.getenv("DB_USER"); DB_PASSWORD=os.getenv("DB_PASSWORD")
|
| 13 |
+
DB_SSL=os.getenv("DB_SSL","false").lower()=="true"; ALLOW_DDL=os.getenv("ALLOW_DDL","false").lower()=="true"
|
| 14 |
+
|
| 15 |
+
def db_connect():
|
| 16 |
+
kw=dict(host=DB_HOST,port=DB_PORT,user=DB_USER,password=DB_PASSWORD,database=DB_NAME,charset="utf8mb4",autocommit=True)
|
| 17 |
+
if DB_SSL: kw["ssl"]={"ssl":{}}
|
| 18 |
+
return pymysql.connect(**kw)
|
| 19 |
+
|
| 20 |
+
def ensure_tables():
|
| 21 |
+
if not ALLOW_DDL: return
|
| 22 |
+
sql="CREATE TABLE IF NOT EXISTS poll_response (id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, poll_type VARCHAR(32) NOT NULL, session_uuid CHAR(36) NOT NULL, item_index INT NOT NULL, item_file VARCHAR(255) NOT NULL, choice VARCHAR(64) NOT NULL, user_agent VARCHAR(255) DEFAULT NULL, ip_hash CHAR(64) DEFAULT NULL, created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id), KEY idx_poll_item (poll_type, item_index), KEY idx_created (created_at)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;"
|
| 23 |
+
conn=db_connect();
|
| 24 |
+
with conn.cursor() as cur: cur.execute(sql)
|
| 25 |
+
conn.close()
|
| 26 |
+
|
| 27 |
+
def load_sentiments():
|
| 28 |
+
try:
|
| 29 |
+
if os.path.exists(SENTIMENTS_PATH):
|
| 30 |
+
with open(SENTIMENTS_PATH,"r",encoding="utf-8") as f:
|
| 31 |
+
data=json.load(f)
|
| 32 |
+
if isinstance(data,list) and data: return [str(x) for x in data]
|
| 33 |
+
if isinstance(data,dict) and isinstance(data.get("sentiments"),list): return [str(x) for x in data["sentiments"]]
|
| 34 |
+
except Exception as e:
|
| 35 |
+
print("[warn] sentiments.json illisible:", e)
|
| 36 |
+
return DEFAULT_SENTIMENTS
|
| 37 |
+
|
| 38 |
+
def load_images()->List[Dict[str,Any]]:
|
| 39 |
+
files=[p for p in glob.glob(os.path.join(IMAGE_DIR,"*")) if p.lower().endswith(IMG_EXTS)]
|
| 40 |
+
files.sort()
|
| 41 |
+
if not files: raise RuntimeError(f"Aucune image trouvée dans {IMAGE_DIR}")
|
| 42 |
+
return [{"path":p,"file":os.path.basename(p)} for p in files]
|
| 43 |
+
|
| 44 |
+
def aggregate(conn, items, sentiments):
|
| 45 |
+
rows=[]
|
| 46 |
+
with conn.cursor() as cur:
|
| 47 |
+
for i,it in enumerate(items, start=1):
|
| 48 |
+
cur.execute("SELECT choice, COUNT(*) FROM poll_response WHERE poll_type=%s AND item_index=%s GROUP BY choice", (POLL_TYPE,i))
|
| 49 |
+
counts={c:cnt for c,cnt in (cur.fetchall() or [])}
|
| 50 |
+
total=sum(counts.values()); row=[i,it["file"],total]
|
| 51 |
+
for s in sentiments: row.append(counts.get(s,0))
|
| 52 |
+
rows.append(row)
|
| 53 |
+
return rows
|
| 54 |
+
|
| 55 |
+
def app():
|
| 56 |
+
ensure_tables()
|
| 57 |
+
sentiments=load_sentiments()
|
| 58 |
+
items=load_images()
|
| 59 |
+
headers=["#","Fichier","Total"]+sentiments
|
| 60 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 61 |
+
gr.Markdown("# Poll Sentiments")
|
| 62 |
+
gr.Markdown("Choisissez un sentiment pour chaque image, validez, puis consultez les agrégats globaux.")
|
| 63 |
+
state_items=gr.State(items); state_sent=gr.State(sentiments); session_id=gr.State(str(uuid.uuid4()))
|
| 64 |
+
with gr.Group(visible=True) as poll_group:
|
| 65 |
+
with gr.Row():
|
| 66 |
+
btn_shuffle=gr.Button("🔀 Mélanger l’ordre")
|
| 67 |
+
btn_reset=gr.Button("♻️ Réinitialiser les choix")
|
| 68 |
+
btn_submit=gr.Button("✅ Valider mes choix", variant="primary")
|
| 69 |
+
warn=gr.Markdown(visible=False)
|
| 70 |
+
imgs=[]; dds=[]
|
| 71 |
+
rows=(len(items)+3)//4; idx=0
|
| 72 |
+
with gr.Column():
|
| 73 |
+
for r in range(rows):
|
| 74 |
+
with gr.Row():
|
| 75 |
+
for c in range(4):
|
| 76 |
+
if idx>=len(items): break
|
| 77 |
+
with gr.Column():
|
| 78 |
+
imgs.append(gr.Image(value=items[idx]["path"], label=f"Image {idx+1}", interactive=False))
|
| 79 |
+
dds.append(gr.Dropdown(choices=sentiments, label="Votre choix"))
|
| 80 |
+
idx+=1
|
| 81 |
+
with gr.Group(visible=False) as result_group:
|
| 82 |
+
gr.Markdown("## Agrégats (tous les usagers)")
|
| 83 |
+
df=gr.Dataframe(headers=headers, interactive=False)
|
| 84 |
+
btn_back=gr.Button("↩️ Revenir au poll")
|
| 85 |
+
def on_shuffle(state, sentiments):
|
| 86 |
+
items=list(state); import random; random.shuffle(items)
|
| 87 |
+
return [*([gr.update(value=items[i]['path'],label=f'Image {i+1}') for i in range(len(items))]), *([gr.update(value=None, choices=sentiments) for _ in items]), gr.update(value='',visible=False), items]
|
| 88 |
+
btn_shuffle.click(on_shuffle, inputs=[state_items,state_sent], outputs=[*imgs,*dds,warn,state_items])
|
| 89 |
+
def on_reset(): return [gr.update(value=None) for _ in dds]+[gr.update(value='',visible=False)]
|
| 90 |
+
btn_reset.click(on_reset, inputs=None, outputs=[*dds,warn])
|
| 91 |
+
def on_submit(*vals, state, sentiments, sess):
|
| 92 |
+
if any(v in (None,"") for v in vals):
|
| 93 |
+
missing=sum(1 for v in vals if v in (None,""))
|
| 94 |
+
return gr.update(value=f"❗ {missing} choix manquent.", visible=True), gr.update(visible=True), gr.update(visible=False), None
|
| 95 |
+
conn=db_connect()
|
| 96 |
+
with conn.cursor() as cur:
|
| 97 |
+
for i,v in enumerate(vals, start=1):
|
| 98 |
+
cur.execute("INSERT INTO poll_response (poll_type,session_uuid,item_index,item_file,choice) VALUES (%s,%s,%s,%s,%s)", ("sentiment",sess,i,state[i-1]['file'],v))
|
| 99 |
+
rows=aggregate(conn,state,sentiments); conn.close()
|
| 100 |
+
return gr.update(visible=False), gr.update(value=rows), gr.update(visible=True), None
|
| 101 |
+
btn_submit.click(on_submit, inputs=[*dds,state_items,state_sent,session_id], outputs=[poll_group,df,result_group,warn])
|
| 102 |
+
btn_back.click(lambda: (gr.update(visible=True), gr.update(visible=False)), inputs=None, outputs=[poll_group, result_group])
|
| 103 |
+
return demo
|
| 104 |
+
demo=app()
|
| 105 |
+
if __name__=="__main__": demo.launch()
|