GitHub Actions commited on
Commit
e89eaf5
·
0 Parent(s):

Deploy: 2026-04-29 19:34

Browse files
Files changed (15) hide show
  1. .env.example +5 -0
  2. .python-version +1 -0
  3. Dockerfile +16 -0
  4. README.md +12 -0
  5. app/__init__.py +0 -0
  6. app/analysis.py +188 -0
  7. app/app.py +103 -0
  8. app/database.py +33 -0
  9. app/models.py +79 -0
  10. app/schemas.py +54 -0
  11. app/seed.py +50 -0
  12. pyproject.toml +17 -0
  13. requirements.txt +7 -0
  14. survey.db +0 -0
  15. uv.lock +0 -0
.env.example ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # base de donnnee Supabase
2
+ DATABASE_URL=...
3
+
4
+ # Token Admin
5
+ ADMIN_TOKEN=d...
.python-version ADDED
@@ -0,0 +1 @@
 
 
1
+ 3.14
Dockerfile ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/
4
+
5
+ WORKDIR /code
6
+
7
+ # Paths locaux maintenant que le Dockerfile est dans backend/
8
+ COPY pyproject.toml uv.lock* /code/
9
+
10
+ RUN uv pip install --system --no-cache -r /code/pyproject.toml
11
+
12
+ COPY . /code
13
+
14
+ EXPOSE 7860
15
+
16
+ CMD ["uvicorn", "app.app:app", "--host", "0.0.0.0", "--port", "7860"]
README.md ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Mon Projet FastAPI
3
+ emoji: 🚀
4
+ colorFrom: blue
5
+ colorTo: green
6
+ sdk: docker
7
+ pinned: false
8
+ ---
9
+
10
+ # TP-INF-232 Backend API
11
+
12
+ Ceci est mon backend FastAPI déployé sur Hugging Face Spaces.
app/__init__.py ADDED
File without changes
app/analysis.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import pandas as pd
3
+ import numpy as np
4
+ from scipy import stats
5
+ from sqlalchemy.orm import Session
6
+ from app.models import Response
7
+
8
+ # ── Helpers ──────────────────────────────────────────────────────────────────
9
+
10
+ def _parse_json_column(series: pd.Series) -> pd.Series:
11
+ """Transforme une colonne de chaînes JSON en listes Python."""
12
+ return series.apply(lambda x: json.loads(x) if isinstance(x, str) and x.strip() else [])
13
+
14
+ def _get_distribution(series: pd.Series, explode: bool = False) -> dict:
15
+ """Retourne labels + counts triés par fréquence décroissante."""
16
+ if explode:
17
+ # Pour les colonnes multi-choix (listes)
18
+ data = series.explode().dropna()
19
+ else:
20
+ data = series.dropna()
21
+
22
+ if data.empty:
23
+ return {"labels": [], "values": []}
24
+
25
+ counts = data.value_counts()
26
+ return {
27
+ "labels": counts.index.tolist(),
28
+ "values": counts.values.tolist()
29
+ }
30
+
31
+ def _freq_score(freq: str) -> int:
32
+ """Mappe la fréquence d'usage IA en score numérique."""
33
+ mapping = {
34
+ "jamais": 0,
35
+ "rarement": 1,
36
+ "parfois": 2,
37
+ "souvent": 3,
38
+ "très souvent": 4,
39
+ }
40
+ return mapping.get(str(freq).lower(), 0)
41
+
42
+ # ── Calcul principal ─────────────────────────────────────────────────────────
43
+
44
+ def compute_stats(db: Session) -> dict:
45
+ # 1. Chargement des données
46
+ responses = db.query(Response).all()
47
+ total = len(responses)
48
+
49
+ if total == 0:
50
+ return {"total": 0}
51
+
52
+ # 2. Conversion en DataFrame
53
+ df = pd.DataFrame([r.to_dict() for r in responses])
54
+
55
+ # 3. Pré-traitement des colonnes JSON
56
+ json_cols = [
57
+ "outils_ia", "contextes_ia", "dangers_ia",
58
+ "usage_ia_etudes", "methode_preparation_exam",
59
+ "freins_ia_etudes", "fonctionnalites_utiles"
60
+ ]
61
+ for col in json_cols:
62
+ if col in df.columns:
63
+ df[col] = df[col].apply(lambda x: x if isinstance(x, list) else [])
64
+
65
+ # 4. Distributions simples (champs catégoriels)
66
+ stats_dict = {
67
+ "total": total,
68
+ "dist_niveau_etudes": _get_distribution(df["niveau_etudes"]),
69
+ "dist_faculte": _get_distribution(df["faculte"]),
70
+ "dist_genre": _get_distribution(df["genre"]),
71
+ "dist_utilise_ia": _get_distribution(df["utilise_ia"]),
72
+ "dist_frequence_ia_etudes": _get_distribution(df["frequence_ia_etudes"]),
73
+ "dist_difficulte_preparation": _get_distribution(df["difficulte_preparation"]),
74
+ "dist_utiliserait_app": _get_distribution(df["utiliserait_app"]),
75
+ "dist_format_prefere": _get_distribution(df["format_prefere"]),
76
+ "dist_budget_mensuel": _get_distribution(df["budget_mensuel"]),
77
+ }
78
+
79
+ # 5. Distributions multi-choix (JSON explode)
80
+ stats_dict.update({
81
+ "dist_outils_ia": _get_distribution(df["outils_ia"], explode=True),
82
+ "dist_contextes_ia": _get_distribution(df["contextes_ia"], explode=True),
83
+ "dist_dangers_ia": _get_distribution(df["dangers_ia"], explode=True),
84
+ "dist_usage_ia_etudes": _get_distribution(df["usage_ia_etudes"], explode=True),
85
+ "dist_methode_preparation": _get_distribution(df["methode_preparation_exam"], explode=True),
86
+ "dist_freins_ia_etudes": _get_distribution(df["freins_ia_etudes"], explode=True),
87
+ "dist_fonctionnalites_utiles": _get_distribution(df["fonctionnalites_utiles"], explode=True),
88
+ })
89
+
90
+ # 6. Moyennes Likert
91
+ likert_fields = {
92
+ "Connaissance IA": "niveau_connaissance_ia",
93
+ "IA = Opportunité": "ia_opportunite",
94
+ "IA = Menace emploi": "ia_menace_emploi",
95
+ "Confiance IA": "confiance_ia",
96
+ "IA améliore réussite":"ia_ameliore_reussite",
97
+ "Solution pertinente": "solution_repond_probleme",
98
+ }
99
+ stats_dict["likert_means"] = {
100
+ label: round(df[field].mean(), 2) if field in df.columns else 0.0
101
+ for label, field in likert_fields.items()
102
+ }
103
+
104
+ # 6b. Statistiques descriptives complètes pour chaque variable Likert
105
+ likert_descriptive = {}
106
+ for label, field in likert_fields.items():
107
+ if field in df.columns:
108
+ series = df[field].dropna()
109
+ if len(series) > 0:
110
+ q1 = float(np.percentile(series, 25))
111
+ q3 = float(np.percentile(series, 75))
112
+ likert_descriptive[label] = {
113
+ "mean": round(float(series.mean()), 2),
114
+ "median": round(float(series.median()), 2),
115
+ "mode": int(series.mode().iloc[0]) if len(series.mode()) > 0 else 0,
116
+ "stddev": round(float(series.std()), 2),
117
+ "variance": round(float(series.var()), 2),
118
+ "min": int(series.min()),
119
+ "max": int(series.max()),
120
+ "q1": round(q1, 2),
121
+ "q3": round(q3, 2),
122
+ "iqr": round(q3 - q1, 2),
123
+ "n": int(len(series)),
124
+ }
125
+ else:
126
+ likert_descriptive[label] = None
127
+ else:
128
+ likert_descriptive[label] = None
129
+ stats_dict["likert_descriptive"] = likert_descriptive
130
+
131
+ # 6c. Tableau croisé Faculté × Usage IA
132
+ if "faculte" in df.columns and "utilise_ia" in df.columns:
133
+ ct = pd.crosstab(df["faculte"], df["utilise_ia"])
134
+ stats_dict["crosstab_faculte_usage"] = {
135
+ "index": ct.index.tolist(),
136
+ "columns": ct.columns.tolist(),
137
+ "data": ct.values.tolist(),
138
+ }
139
+ else:
140
+ stats_dict["crosstab_faculte_usage"] = {"index": [], "columns": [], "data": []}
141
+
142
+ # 7. H1 : Corrélation usage ↔ perception (avec P-value)
143
+ if total >= 2:
144
+ df["freq_score"] = df["frequence_ia_etudes"].apply(_freq_score)
145
+ df["perception_score"] = (
146
+ df["ia_opportunite"].fillna(0) +
147
+ df["confiance_ia"].fillna(0) +
148
+ df["niveau_connaissance_ia"].fillna(0)
149
+ ) / 3
150
+
151
+ corr, p_value = stats.pearsonr(df["freq_score"], df["perception_score"])
152
+
153
+ # Régression linéaire simple (Y = ax + b)
154
+ slope, intercept, r_value, p_reg, std_err = stats.linregress(df["freq_score"], df["perception_score"])
155
+
156
+ stats_dict["h1_correlation_usage_perception"] = round(corr, 3)
157
+ stats_dict["h1_p_value"] = round(p_value, 4)
158
+ stats_dict["h1_regression"] = {
159
+ "slope": round(slope, 3),
160
+ "intercept": round(intercept, 3),
161
+ "r_squared": round(r_value**2, 3)
162
+ }
163
+ else:
164
+ stats_dict["h1_correlation_usage_perception"] = 0.0
165
+ stats_dict["h1_p_value"] = 1.0
166
+ stats_dict["h1_regression"] = {"slope": 0, "intercept": 0, "r_squared": 0}
167
+
168
+ # 8. H2 : Analyse des méthodes
169
+ # On considère "sans méthode" si la liste est vide ou contient "rien"
170
+ df["has_no_method"] = df["methode_preparation_exam"].apply(
171
+ lambda x: len(x) == 0 or any("rien" in str(m).lower() or "aucune" in str(m).lower() for m in x)
172
+ )
173
+ stats_dict["h2_pct_sans_methode"] = round(df["has_no_method"].mean() * 100, 1)
174
+
175
+ df["mentions_manque_methode"] = df["difficulte_preparation"].fillna("").str.contains("méthode", case=False)
176
+ stats_dict["h2_pct_manque_methode"] = round(df["mentions_manque_methode"].mean() * 100, 1)
177
+
178
+ # 9. H3 : Taux d'adoption
179
+ adoption_keywords = ["oui", "certainement", "probablement", "absolument", "régulièrement"]
180
+ df["is_adopter"] = df["utiliserait_app"].fillna("").apply(
181
+ lambda x: any(kw in str(x).lower() for kw in adoption_keywords)
182
+ )
183
+ stats_dict["h3_pct_adoption"] = round(df["is_adopter"].mean() * 100, 1)
184
+
185
+ # 10. Suggestions libres
186
+ stats_dict["suggestions"] = df["suggestions"].dropna().str.strip().replace("", np.nan).dropna().tolist()
187
+
188
+ return stats_dict
app/app.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import logging
4
+ from pathlib import Path
5
+ from dotenv import load_dotenv
6
+ from fastapi import FastAPI, Depends, HTTPException, Header
7
+ from fastapi.middleware.cors import CORSMiddleware
8
+ from sqlalchemy.orm import Session
9
+
10
+ from app.database import engine, get_db, Base
11
+ from app.models import Response
12
+ from app.schemas import SurveySubmission
13
+ from app.analysis import compute_stats
14
+
15
+ logger = logging.getLogger(__name__)
16
+ load_dotenv()
17
+
18
+ app = FastAPI(title="Survey API — IA & PassExamAI", version="1.0.0")
19
+
20
+ @app.on_event("startup")
21
+ def startup_event():
22
+ logger.info("Ensuring DB schema exists...")
23
+ Base.metadata.create_all(bind=engine)
24
+
25
+ app.add_middleware(
26
+ CORSMiddleware,
27
+ allow_origins=["*"],
28
+ allow_methods=["*"],
29
+ allow_headers=["*"],
30
+ )
31
+
32
+ # ── Frontend statique — monté seulement si le dossier existe ──────
33
+ FRONTEND = Path(__file__).parent.parent.parent / "frontend"
34
+ if FRONTEND.exists():
35
+ from fastapi.staticfiles import StaticFiles
36
+ from fastapi.responses import FileResponse
37
+ app.mount("/static", StaticFiles(directory=str(FRONTEND / "static")), name="static")
38
+
39
+ @app.get("/", include_in_schema=False)
40
+ def serve_form():
41
+ return FileResponse(str(FRONTEND / "index.html"))
42
+
43
+ @app.get("/dashboard", include_in_schema=False)
44
+ def serve_dashboard():
45
+ return FileResponse(str(FRONTEND / "dashboard.html"))
46
+
47
+ # ── Admin token — optionnel si non défini ────────────────────────
48
+ ADMIN_TOKEN = os.getenv("ADMIN_TOKEN")
49
+
50
+ def verify_admin(x_admin_token: str = Header(...)):
51
+ if not ADMIN_TOKEN or x_admin_token != ADMIN_TOKEN:
52
+ raise HTTPException(status_code=403, detail="Token invalide")
53
+
54
+ # ── Routes ────────────────────────────────────────────────────────
55
+ @app.get("/api/health")
56
+ def health():
57
+ return {"status": "ok"}
58
+
59
+ @app.post("/api/submit", status_code=201)
60
+ def submit_response(data: SurveySubmission, db: Session = Depends(get_db)):
61
+ row = Response(
62
+ niveau_etudes=data.niveau_etudes,
63
+ faculte=data.faculte,
64
+ filiere=data.filiere,
65
+ genre=data.genre,
66
+ utilise_ia=data.utilise_ia,
67
+ outils_ia=json.dumps(data.outils_ia, ensure_ascii=False),
68
+ contextes_ia=json.dumps(data.contextes_ia, ensure_ascii=False),
69
+ niveau_connaissance_ia=data.niveau_connaissance_ia,
70
+ ia_opportunite=data.ia_opportunite,
71
+ ia_menace_emploi=data.ia_menace_emploi,
72
+ confiance_ia=data.confiance_ia,
73
+ dangers_ia=json.dumps(data.dangers_ia, ensure_ascii=False),
74
+ frequence_ia_etudes=data.frequence_ia_etudes,
75
+ usage_ia_etudes=json.dumps(data.usage_ia_etudes, ensure_ascii=False),
76
+ methode_preparation_exam=json.dumps(data.methode_preparation_exam, ensure_ascii=False),
77
+ difficulte_preparation=data.difficulte_preparation,
78
+ ia_ameliore_reussite=data.ia_ameliore_reussite,
79
+ freins_ia_etudes=json.dumps(data.freins_ia_etudes, ensure_ascii=False),
80
+ solution_repond_probleme=data.solution_repond_probleme,
81
+ fonctionnalites_utiles=json.dumps(data.fonctionnalites_utiles, ensure_ascii=False),
82
+ utiliserait_app=data.utiliserait_app,
83
+ format_prefere=data.format_prefere,
84
+ budget_mensuel=data.budget_mensuel,
85
+ suggestions=data.suggestions or "",
86
+ )
87
+ db.add(row)
88
+ db.commit()
89
+ db.refresh(row)
90
+ return {"success": True, "id": row.id}
91
+
92
+ @app.get("/api/stats")
93
+ def get_public_stats(db: Session = Depends(get_db)):
94
+ return compute_stats(db)
95
+
96
+ @app.get("/api/analysis")
97
+ def get_analysis(db: Session = Depends(get_db), _=Depends(verify_admin)):
98
+ return compute_stats(db)
99
+
100
+ @app.get("/api/responses")
101
+ def get_responses(db: Session = Depends(get_db), _=Depends(verify_admin)):
102
+ rows = db.query(Response).order_by(Response.submitted_at.desc()).all()
103
+ return [r.to_dict() for r in rows]
app/database.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sqlalchemy import create_engine
2
+ from sqlalchemy.orm import DeclarativeBase, sessionmaker
3
+ import os
4
+
5
+ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
6
+ LOCAL_DB = f"sqlite:///{os.path.join(BASE_DIR, 'survey.db')}"
7
+ DATABASE_URL = os.getenv("DATABASE_URL", LOCAL_DB)
8
+
9
+ engine_args = {}
10
+ if DATABASE_URL.startswith("sqlite"):
11
+ engine_args = {"check_same_thread": False}
12
+
13
+ # Ajuste si besoin (Docker persistent)
14
+ engine = create_engine(
15
+ DATABASE_URL,
16
+ connect_args=engine_args,
17
+ pool_pre_ping=True, # évite "connection is closed"
18
+ pool_recycle=1800, # recycle connexions (30 min)
19
+ pool_size=5,
20
+ max_overflow=10,
21
+ )
22
+
23
+ SessionLocal = sessionmaker(bind=engine, autocommit=False, autoflush=True)
24
+
25
+ class Base(DeclarativeBase):
26
+ pass
27
+
28
+ def get_db():
29
+ db = SessionLocal()
30
+ try:
31
+ yield db
32
+ finally:
33
+ db.close()
app/models.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from datetime import datetime, timezone
3
+ from sqlalchemy import Column, Integer, String, Text, DateTime
4
+ from app.database import Base
5
+
6
+
7
+ class Response(Base):
8
+ __tablename__ = "responses"
9
+
10
+ id = Column(Integer, primary_key=True, index=True)
11
+ submitted_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
12
+
13
+ # Section 0 — Profil
14
+ niveau_etudes = Column(String(50))
15
+ faculte = Column(String(100))
16
+ filiere = Column(String(100))
17
+ genre = Column(String(20))
18
+ utilise_ia = Column(String(5)) # "oui" / "non"
19
+ outils_ia = Column(Text) # JSON list
20
+ contextes_ia = Column(Text) # JSON list (max 2)
21
+
22
+ # Section 1 — Perception IA
23
+ niveau_connaissance_ia = Column(Integer) # Likert 1-5
24
+ ia_opportunite = Column(Integer) # Likert 1-5
25
+ ia_menace_emploi = Column(Integer) # Likert 1-5
26
+ confiance_ia = Column(Integer) # Likert 1-5
27
+ dangers_ia = Column(Text) # JSON list
28
+
29
+ # Section 2 — IA & Éducation
30
+ frequence_ia_etudes = Column(String(50))
31
+ usage_ia_etudes = Column(Text) # JSON list
32
+ methode_preparation_exam = Column(Text) # JSON list
33
+ difficulte_preparation = Column(String(100))
34
+ ia_ameliore_reussite = Column(Integer) # Likert 1-5
35
+ freins_ia_etudes = Column(Text) # JSON list
36
+
37
+ # Section 3 — Validation PassExamAI
38
+ solution_repond_probleme = Column(Integer) # Likert 1-5
39
+ fonctionnalites_utiles = Column(Text) # JSON list
40
+ utiliserait_app = Column(String(50))
41
+ format_prefere = Column(String(50))
42
+ budget_mensuel = Column(String(100))
43
+ suggestions = Column(Text)
44
+
45
+ def to_dict(self):
46
+ def parse(val):
47
+ try:
48
+ return json.loads(val) if val else []
49
+ except Exception:
50
+ return val
51
+
52
+ return {
53
+ "id": self.id,
54
+ "submitted_at": self.submitted_at.isoformat() if self.submitted_at else None,
55
+ "niveau_etudes": self.niveau_etudes,
56
+ "faculte": self.faculte,
57
+ "filiere": self.filiere,
58
+ "genre": self.genre,
59
+ "utilise_ia": self.utilise_ia,
60
+ "outils_ia": parse(self.outils_ia),
61
+ "contextes_ia": parse(self.contextes_ia),
62
+ "niveau_connaissance_ia": self.niveau_connaissance_ia,
63
+ "ia_opportunite": self.ia_opportunite,
64
+ "ia_menace_emploi": self.ia_menace_emploi,
65
+ "confiance_ia": self.confiance_ia,
66
+ "dangers_ia": parse(self.dangers_ia),
67
+ "frequence_ia_etudes": self.frequence_ia_etudes,
68
+ "usage_ia_etudes": parse(self.usage_ia_etudes),
69
+ "methode_preparation_exam": parse(self.methode_preparation_exam),
70
+ "difficulte_preparation": self.difficulte_preparation,
71
+ "ia_ameliore_reussite": self.ia_ameliore_reussite,
72
+ "freins_ia_etudes": parse(self.freins_ia_etudes),
73
+ "solution_repond_probleme": self.solution_repond_probleme,
74
+ "fonctionnalites_utiles": parse(self.fonctionnalites_utiles),
75
+ "utiliserait_app": self.utiliserait_app,
76
+ "format_prefere": self.format_prefere,
77
+ "budget_mensuel": self.budget_mensuel,
78
+ "suggestions": self.suggestions,
79
+ }
app/schemas.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Optional
2
+ from pydantic import BaseModel, Field, field_validator
3
+
4
+
5
+ class SurveySubmission(BaseModel):
6
+ # Section 0
7
+ niveau_etudes: str
8
+ faculte: str
9
+ filiere: str
10
+ genre: str
11
+ utilise_ia: str
12
+ outils_ia: List[str] = []
13
+ contextes_ia: List[str] = Field(default=[])
14
+
15
+ # Section 1
16
+ niveau_connaissance_ia: int = Field(ge=1, le=5)
17
+ ia_opportunite: int = Field(ge=1, le=5)
18
+ ia_menace_emploi: int = Field(ge=1, le=5)
19
+ confiance_ia: int = Field(ge=1, le=5)
20
+ dangers_ia: List[str] = []
21
+
22
+ # Section 2
23
+ frequence_ia_etudes: str
24
+ usage_ia_etudes: List[str] = []
25
+ methode_preparation_exam: List[str] = []
26
+ difficulte_preparation: str
27
+ ia_ameliore_reussite: int = Field(ge=1, le=5)
28
+ freins_ia_etudes: List[str] = []
29
+
30
+ # Section 3
31
+ solution_repond_probleme: int = Field(ge=1, le=5)
32
+ fonctionnalites_utiles: List[str] = []
33
+ utiliserait_app: str
34
+ format_prefere: str
35
+ budget_mensuel: str
36
+ suggestions: Optional[str] = ""
37
+
38
+ @field_validator("contextes_ia")
39
+ @classmethod
40
+ def max_two_contextes(cls, v):
41
+ if len(v) > 2:
42
+ raise ValueError("Maximum 2 contextes autorisés")
43
+ return v
44
+
45
+
46
+ class ResponseOut(BaseModel):
47
+ id: int
48
+ submitted_at: str
49
+ niveau_etudes: str
50
+ filiere: str
51
+ genre: str
52
+ utilise_ia: str
53
+
54
+ model_config = {"from_attributes": True}
app/seed.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import httpx
2
+ import random
3
+
4
+ # ← change selon l'environnement
5
+ BASE_URL = "https://jordan001237-tp-inf-232.hf.space"
6
+
7
+ NIVEAUX = ["Licence 1", "Licence 2", "Licence 3", "Master 1", "Master 2"]
8
+ FACULTES = ["FST", "FASSO", "FSEG", "FP", "FS"]
9
+ GENRES = ["Homme", "Femme"]
10
+ FREQUENCES = ["jamais", "rarement", "parfois", "souvent", "très souvent"]
11
+ OUTILS = ["ChatGPT", "Gemini", "Claude", "Copilot", "Perplexity"]
12
+ FORMATS = ["Quiz interactif", "Résumés PDF", "Vidéos courtes", "Flashcards"]
13
+ BUDGETS = ["0 FCFA", "500-1000 FCFA", "1000-3000 FCFA", "3000+ FCFA"]
14
+
15
+ def random_payload():
16
+ return {
17
+ "niveau_etudes": random.choice(NIVEAUX),
18
+ "faculte": random.choice(FACULTES),
19
+ "filiere": random.choice(["Informatique", "Mathématiques", "Physique", "Gestion"]),
20
+ "genre": random.choice(GENRES),
21
+ "utilise_ia": random.choice(["Oui", "Non", "Parfois"]),
22
+ "outils_ia": random.sample(OUTILS, k=random.randint(1, 3)),
23
+ "contextes_ia": random.sample(["Révisions", "Devoirs", "Recherche", "Rédaction"], k=2),
24
+ "niveau_connaissance_ia": random.randint(1, 5),
25
+ "ia_opportunite": random.randint(1, 5),
26
+ "ia_menace_emploi": random.randint(1, 5),
27
+ "confiance_ia": random.randint(1, 5),
28
+ "dangers_ia": random.sample(["Désinformation", "Plagiat", "Dépendance", "Vie privée"], k=2),
29
+ "frequence_ia_etudes": random.choice(FREQUENCES),
30
+ "usage_ia_etudes": random.sample(["Résumés", "Exercices", "Explications", "Traduction"], k=2),
31
+ "methode_preparation_exam": random.sample(["Fiches", "Annales", "Groupes d'étude", "rien"], k=2),
32
+ "difficulte_preparation": random.choice(["Manque de méthode", "Pas assez de temps", "Cours incomplets"]),
33
+ "ia_ameliore_reussite": random.randint(1, 5),
34
+ "freins_ia_etudes": random.sample(["Connexion", "Langue", "Confiance", "Coût"], k=2),
35
+ "solution_repond_probleme": random.randint(1, 5),
36
+ "fonctionnalites_utiles": random.sample(["Quiz auto", "Résumés", "Planning", "Chatbot"], k=2),
37
+ "utiliserait_app": random.choice(["Oui certainement", "Probablement", "Non"]),
38
+ "format_prefere": random.choice(FORMATS),
39
+ "budget_mensuel": random.choice(BUDGETS),
40
+ "suggestions": random.choice(["Bonne initiative", "Très utile", "", "J'attends ça !"]),
41
+ }
42
+
43
+ def seed(n: int = 30):
44
+ with httpx.Client(timeout=30) as client:
45
+ for i in range(n):
46
+ r = client.post(f"{BASE_URL}/api/submit", json=random_payload())
47
+ print(f"[{i+1}/{n}] status={r.status_code}")
48
+
49
+ if __name__ == "__main__":
50
+ seed(30) # insère 30 réponses fictives
pyproject.toml ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "backend"
3
+ version = "0.1.0"
4
+ description = "Add your description here"
5
+ readme = "README.md"
6
+ requires-python = ">=3.14"
7
+ dependencies = [
8
+ "fastapi>=0.136.1",
9
+ "httpx>=0.28.1",
10
+ "load-dotenv>=0.1.0",
11
+ "matplotlib>=3.10.9",
12
+ "pandas>=3.0.2",
13
+ "psycopg2-binary",
14
+ "scipy>=1.15.2",
15
+ "sqlalchemy>=2.0.49",
16
+ "uvicorn>=0.46.0",
17
+ ]
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ fastapi>=0.110.0
2
+ matplotlib>=3.8.0
3
+ pandas>=2.2.0
4
+ psycopg2-binary>=2.9.9
5
+ scipy>=1.12.0
6
+ sqlalchemy>=2.0.0
7
+ uvicorn>=0.27.0
survey.db ADDED
Binary file (36.9 kB). View file
 
uv.lock ADDED
The diff for this file is too large to render. See raw diff