Javare commited on
Commit
5a5f41d
·
verified ·
1 Parent(s): 255588c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -0
app.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException
2
+ from fastapi.staticfiles import StaticFiles
3
+ from fastapi.responses import FileResponse
4
+ from pydantic import BaseModel
5
+ import os
6
+ from huggingface_hub import HfApi, hf_hub_download
7
+ import json
8
+
9
+ app = FastAPI()
10
+
11
+ # ⚠️ REMPLACE PAR LE CHEMIN DE TON DATASET
12
+ DATASET_REPO_ID = "Javare/Local_AI_Leaderboard"
13
+ FILENAME = "scores.json"
14
+ HF_TOKEN = os.environ.get("HF_TOKEN")
15
+
16
+ class ScoreEntry(BaseModel):
17
+ config: str
18
+ browser: str
19
+ power: str
20
+ score: float
21
+
22
+ def get_scores():
23
+ try:
24
+ # Télécharge le fichier de scores depuis le dataset Hugging Face
25
+ path = hf_hub_download(repo_id=DATASET_REPO_ID, filename=FILENAME, repo_type="dataset", token=HF_TOKEN)
26
+ with open(path, "r", encoding="utf-8") as f:
27
+ return json.load(f)
28
+ except Exception:
29
+ # Si le fichier n'existe pas encore (premier lancement), on démarre à vide
30
+ return []
31
+
32
+ @app.get("/api/scores")
33
+ def read_scores():
34
+ scores = get_scores()
35
+ scores.sort(key=lambda x: x["score"], reverse=True)
36
+ return scores[:10] # Renvoie uniquement le TOP 10
37
+
38
+ @app.post("/api/score")
39
+ def add_score(entry: ScoreEntry):
40
+ if not HF_TOKEN:
41
+ raise HTTPException(status_code=500, detail="HF_TOKEN manquant dans les Secrets du Space")
42
+
43
+ scores = get_scores()
44
+ scores.append(entry.dict())
45
+
46
+ # Sauvegarde locale temporaire du JSON complet
47
+ local_path = "scores.json"
48
+ with open(local_path, "w", encoding="utf-8") as f:
49
+ json.dump(scores, f, ensure_ascii=False, indent=2)
50
+
51
+ # Envoi sécurisé vers ton Dataset Hugging Face
52
+ api = HfApi()
53
+ try:
54
+ api.upload_file(
55
+ path_or_fileobj=local_path,
56
+ path_in_repo=FILENAME,
57
+ repo_id=DATASET_REPO_ID,
58
+ repo_type="dataset",
59
+ token=HF_TOKEN
60
+ )
61
+ except Exception as e:
62
+ raise HTTPException(status_code=500, detail=f"Erreur de synchronisation : {str(e)}")
63
+
64
+ return {"status": "success"}
65
+
66
+ # Déclare l'accès aux fichiers statiques de ton interface
67
+ @app.get("/")
68
+ def read_index():
69
+ return FileResponse("index.html")
70
+
71
+ app.mount("/assets", StaticFiles(directory="assets"), name="assets")