Spaces:
Sleeping
Sleeping
Upload app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
+
import os, glob, uuid, random, pymysql, gradio as gr
|
| 3 |
+
from typing import List, Dict, Any
|
| 4 |
+
|
| 5 |
+
IMAGE_DIR = os.getenv("IMAGE_DIR", "assets")
|
| 6 |
+
IMG_EXTS = (".png", ".jpg", ".jpeg", ".webp", ".bmp", ".gif")
|
| 7 |
+
POLL_TYPE = "thumbs"
|
| 8 |
+
CHOICES = [("👍 ThumbUp", "up"), ("👎 ThumbDown", "down")]
|
| 9 |
+
|
| 10 |
+
DB_HOST = os.getenv("DB_HOST")
|
| 11 |
+
DB_PORT = int(os.getenv("DB_PORT", "3306"))
|
| 12 |
+
DB_NAME = os.getenv("DB_NAME")
|
| 13 |
+
DB_USER = os.getenv("DB_USER")
|
| 14 |
+
DB_PASSWORD = os.getenv("DB_PASSWORD")
|
| 15 |
+
DB_SSL = os.getenv("DB_SSL", "false").lower() == "true"
|
| 16 |
+
ALLOW_DDL = os.getenv("ALLOW_DDL", "false").lower() == "true"
|
| 17 |
+
|
| 18 |
+
def db_connect():
|
| 19 |
+
kwargs = dict(host=DB_HOST, port=DB_PORT, user=DB_USER, password=DB_PASSWORD, database=DB_NAME, charset="utf8mb4", autocommit=True)
|
| 20 |
+
if DB_SSL:
|
| 21 |
+
kwargs["ssl"] = {"ssl": {}}
|
| 22 |
+
return pymysql.connect(**kwargs)
|
| 23 |
+
|
| 24 |
+
def ensure_tables():
|
| 25 |
+
if not ALLOW_DDL: return
|
| 26 |
+
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;"
|
| 27 |
+
conn=db_connect();
|
| 28 |
+
with conn.cursor() as cur: cur.execute(sql)
|
| 29 |
+
conn.close()
|
| 30 |
+
|
| 31 |
+
def load_images()->List[Dict[str,Any]]:
|
| 32 |
+
files=[p for p in glob.glob(os.path.join(IMAGE_DIR,"*")) if p.lower().endswith(IMG_EXTS)]
|
| 33 |
+
files.sort()
|
| 34 |
+
if not files: raise RuntimeError(f"Aucune image trouvée dans {IMAGE_DIR}")
|
| 35 |
+
return [{"path":p,"file":os.path.basename(p)} for p in files]
|
| 36 |
+
|
| 37 |
+
def aggregate(conn, items):
|
| 38 |
+
rows=[]
|
| 39 |
+
with conn.cursor() as cur:
|
| 40 |
+
for i,it in enumerate(items, start=1):
|
| 41 |
+
cur.execute("SELECT SUM(choice='up'), SUM(choice='down'), COUNT(*) FROM poll_response WHERE poll_type=%s AND item_index=%s",(POLL_TYPE,i))
|
| 42 |
+
up,down,total=cur.fetchone() or (0,0,0)
|
| 43 |
+
up=up or 0; down=down or 0; total=total or 0
|
| 44 |
+
pct = f"{round(100*up/total)}%" if total>0 else "0%"
|
| 45 |
+
rows.append([i,it["file"],up,down,total,pct])
|
| 46 |
+
return rows
|
| 47 |
+
|
| 48 |
+
def app():
|
| 49 |
+
ensure_tables()
|
| 50 |
+
items = load_images()
|
| 51 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 52 |
+
gr.Markdown("# Poll 👍 / 👎")
|
| 53 |
+
gr.Markdown("Faites vos choix puis validez. Le tableau affiche les **agrégats** globaux.")
|
| 54 |
+
state_items=gr.State(items); session_id=gr.State(str(uuid.uuid4()))
|
| 55 |
+
with gr.Group(visible=True) as poll_group:
|
| 56 |
+
with gr.Row():
|
| 57 |
+
btn_shuffle=gr.Button("🔀 Mélanger l’ordre")
|
| 58 |
+
btn_reset=gr.Button("♻️ Réinitialiser les choix")
|
| 59 |
+
btn_submit=gr.Button("✅ Valider mes choix", variant="primary")
|
| 60 |
+
warn=gr.Markdown(visible=False)
|
| 61 |
+
imgs=[]; radios=[]
|
| 62 |
+
rows=(len(items)+3)//4; idx=0
|
| 63 |
+
with gr.Column():
|
| 64 |
+
for r in range(rows):
|
| 65 |
+
with gr.Row():
|
| 66 |
+
for c in range(4):
|
| 67 |
+
if idx>=len(items): break
|
| 68 |
+
with gr.Column():
|
| 69 |
+
imgs.append(gr.Image(value=items[idx]["path"], label=f"Image {idx+1}", interactive=False))
|
| 70 |
+
radios.append(gr.Radio(choices=[lbl for lbl,_ in CHOICES], label="Votre choix"))
|
| 71 |
+
idx+=1
|
| 72 |
+
with gr.Group(visible=False) as result_group:
|
| 73 |
+
gr.Markdown("## Agrégats (tous les usagers)")
|
| 74 |
+
df=gr.Dataframe(headers=["#","Fichier","Up","Down","Total","%Up"], interactive=False)
|
| 75 |
+
btn_back=gr.Button("↩️ Revenir au poll")
|
| 76 |
+
def on_shuffle(state):
|
| 77 |
+
items=list(state); random.shuffle(items)
|
| 78 |
+
return [*([gr.update(value=items[i]['path'],label=f'Image {i+1}') for i in range(len(items))]), *([gr.update(value=None) for _ in items]), gr.update(value='',visible=False), items]
|
| 79 |
+
btn_shuffle.click(on_shuffle, inputs=[state_items], outputs=[*imgs,*radios,warn,state_items])
|
| 80 |
+
def on_reset(): return [gr.update(value=None) for _ in radios]+[gr.update(value='',visible=False)]
|
| 81 |
+
btn_reset.click(on_reset, inputs=None, outputs=[*radios,warn])
|
| 82 |
+
def on_submit(*vals, state, sess):
|
| 83 |
+
lab2val={lbl:v for lbl,v in CHOICES}
|
| 84 |
+
choices=[None if v is None else lab2val.get(v) for v in vals]
|
| 85 |
+
if any(v is None for v in choices):
|
| 86 |
+
missing=sum(1 for v in choices if v is None)
|
| 87 |
+
return gr.update(value=f"❗ {missing} choix manquent.", visible=True), gr.update(visible=True), gr.update(visible=False), None
|
| 88 |
+
conn=db_connect()
|
| 89 |
+
with conn.cursor() as cur:
|
| 90 |
+
for i,v in enumerate(choices, start=1):
|
| 91 |
+
cur.execute("INSERT INTO poll_response (poll_type,session_uuid,item_index,item_file,choice) VALUES (%s,%s,%s,%s,%s)", ("thumbs",sess,i,state[i-1]['file'],v))
|
| 92 |
+
rows=aggregate(conn,state); conn.close()
|
| 93 |
+
return gr.update(visible=False), gr.update(value=rows), gr.update(visible=True), None
|
| 94 |
+
btn_submit.click(on_submit, inputs=[*radios,state_items,session_id], outputs=[poll_group,df,result_group,warn])
|
| 95 |
+
btn_back.click(lambda: (gr.update(visible=True), gr.update(visible=False)), inputs=None, outputs=[poll_group, result_group])
|
| 96 |
+
return demo
|
| 97 |
+
demo=app()
|
| 98 |
+
if __name__=="__main__": demo.launch()
|