Spaces:
Sleeping
Sleeping
File size: 37,314 Bytes
96e3feb 7cff386 96e3feb 24521f4 96e3feb 960655f 96e3feb 7cff386 f03f0ce db8d943 96e3feb dc1df5c 96e3feb dc1df5c 24521f4 96e3feb 1b68f7e 9dad147 1b68f7e db8d943 96e3feb 24521f4 dc1df5c 7cff386 96e3feb 24521f4 7cff386 24521f4 96e3feb 24521f4 dc1df5c 7cff386 96e3feb 24521f4 7cff386 24521f4 96e3feb 24521f4 dc1df5c 7cff386 96e3feb 24521f4 7cff386 24521f4 96e3feb 24521f4 dc1df5c 7cff386 96e3feb 24521f4 7cff386 24521f4 96e3feb 24521f4 dc1df5c 7cff386 96e3feb 24521f4 7cff386 24521f4 96e3feb 24521f4 dc1df5c 7cff386 96e3feb 24521f4 7cff386 24521f4 96e3feb 24521f4 dc1df5c 7cff386 96e3feb 24521f4 7cff386 24521f4 96e3feb 24521f4 dc1df5c 7cff386 96e3feb 24521f4 7cff386 24521f4 96e3feb 24521f4 dc1df5c 7cff386 96e3feb 24521f4 7cff386 24521f4 96e3feb 24521f4 dc1df5c 7cff386 96e3feb 24521f4 7cff386 24521f4 96e3feb db8d943 60285d9 db8d943 60285d9 db8d943 60285d9 db8d943 60285d9 db8d943 60285d9 db8d943 60285d9 db8d943 60285d9 24521f4 7cff386 24521f4 1b68f7e 96e3feb 24521f4 1b68f7e 96e3feb dc1df5c 96e3feb 1b68f7e 7cff386 96e3feb 7cff386 96e3feb 7cff386 0ad30f3 7cff386 0ad30f3 7cff386 96e3feb 7cff386 0ad30f3 dc1df5c 0ad30f3 7cff386 96e3feb c523761 96e3feb c523761 96e3feb c523761 96e3feb c523761 96e3feb 24521f4 96e3feb f03f0ce 844db63 f03f0ce ff3c77a f03f0ce ff3c77a f03f0ce 96e3feb 844db63 7cff386 96e3feb 24521f4 ff3c77a 96e3feb 844db63 ff3c77a 844db63 24521f4 96e3feb 7cff386 c523761 1b68f7e 7cff386 c523761 7cff386 c523761 7cff386 c523761 7cff386 1b68f7e 7cff386 c523761 ff3c77a 7cff386 c523761 7cff386 1b68f7e ff3c77a 7cff386 1b68f7e f03f0ce 1b68f7e f03f0ce 96e3feb 04fb29c 1b68f7e 04fb29c f03f0ce ff3c77a f03f0ce 04fb29c f03f0ce 1b68f7e f03f0ce 04fb29c f03f0ce 04fb29c f03f0ce ff3c77a f03f0ce 04fb29c f03f0ce 1b68f7e 04fb29c 96e3feb db8d943 60285d9 db8d943 60285d9 db8d943 60285d9 db8d943 1b68f7e ff3c77a db8d943 ff3c77a db8d943 1b68f7e db8d943 1b68f7e ff3c77a db8d943 60285d9 db8d943 60285d9 db8d943 60285d9 db8d943 8587f3f db8d943 1b68f7e ff3c77a db8d943 bdc0601 1b68f7e db8d943 8587f3f db8d943 dc1df5c 24521f4 60782a7 24521f4 60782a7 24521f4 60782a7 24521f4 60782a7 24521f4 60782a7 24521f4 9dad147 24521f4 db8d943 7cff386 9dad147 db8d943 9dad147 db8d943 1b68f7e db8d943 1b68f7e db8d943 1b68f7e db8d943 bdc0601 7cff386 24521f4 1b68f7e 9dad147 67f07cd 9dad147 67f07cd 1b68f7e 9dad147 1b68f7e 9dad147 60285d9 1b68f7e 67f07cd 1b68f7e 67f07cd 1b68f7e 9dad147 1b68f7e 9dad147 60285d9 1b68f7e 67f07cd 9dad147 60782a7 9dad147 13601a0 1b68f7e 60782a7 67f07cd 9dad147 7cff386 f36f4af 0ad30f3 24521f4 db8d943 1b68f7e 24521f4 1b68f7e 96e3feb dc1df5c 7c5d39b 9dad147 67f07cd 7c5d39b 67f07cd 24521f4 9dad147 24521f4 67f07cd 24521f4 1b68f7e 24521f4 1b68f7e 24521f4 7cff386 dc1df5c 67f07cd 7cff386 60285d9 dc1df5c 67f07cd 7cff386 60285d9 24521f4 1b68f7e 9dad147 1b68f7e 60285d9 1b68f7e 67f07cd 1b68f7e 24521f4 dc1df5c 960655f 1b68f7e 960655f 1b68f7e bdc0601 96e3feb 9dad147 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 | import os
import re
import json
import random
from typing import Dict, Any, List, Optional
import gradio as gr
from huggingface_hub import InferenceClient
# Load external CSS file into a string so Gradio can inject it
CSS_PATH = os.path.join(os.path.dirname(__file__), "style.css")
try:
with open(CSS_PATH, encoding="utf-8") as f:
CUSTOM_CSS = f.read()
except FileNotFoundError:
CUSTOM_CSS = ""
# ────────────────────────────────────────────────────────────────────────────────
# CONFIG
# Default to a serverless text-generation model. You can override this in Space
# settings by defining a MODEL_ID variable if you want to experiment.
MODEL_ID = os.environ.get("MODEL_ID", "google/gemma-2-2b-it")
# Personal access token from your Hugging Face account (Space secret).
HF_TOKEN = os.environ.get("HF_TOKEN")
REPO_PATH = "/data/questions.json" # where we store generated questions
CATEGORIES = [
{"key": "alimentation", "icon": "🍎", "fr": "Alimentation", "en": "Nutrition"},
{"key": "mouvement", "icon": "🦘", "fr": "Mouvement", "en": "Movement"},
{"key": "cerveau", "icon": "🧠", "fr": "Cerveau", "en": "Brain"},
{"key": "liens", "icon": "🤝", "fr": "Liens", "en": "Connections"},
{"key": "bien-etre", "icon": "💬", "fr": "Bien-être", "en": "Well-being"},
]
GUIDES = {
"fr": {
"alimentation": "Habitudes simples: hydratation, fruits/légumes, collations, rythme des repas. Pas de régime strict, pas de moralisation.",
"mouvement": "Mouvement du quotidien: marche, escaliers, étirements courts, pauses actives. Pas de performance sportive.",
"cerveau": "Stimulation douce: curiosité, respiration, mini-jeux, petit apprentissage. Zéro jargon médical.",
"liens": "Interactions simples: gratitude, messages courts, appels brefs, moments partagés. Ton chaleureux, inclusif.",
"bien-etre": "Micro bien-être: pauses, sommeil régulier, respirations, petits rituels qui apaisent. Jamais culpabilisant.",
},
"en": {
"alimentation": "Simple habits: hydration, fruit/veg, snacks, meal rhythm. No strict diets, no moralizing.",
"mouvement": "Daily movement: walking, stairs, light stretches, active breaks. No performance pressure.",
"cerveau": "Gentle stimulation: curiosity, breathing, tiny games, small learning moments. No medical jargon.",
"liens": "Simple connections: gratitude, short texts, quick calls, shared moments. Warm and inclusive tone.",
"bien-etre": "Micro well-being: breaks, sleep rhythm, breathing, tiny soothing rituals. Never guilt-based.",
},
}
# Themes
THEME_KEYS = ["family", "friends", "romance", "silly", "education"]
THEME_LABELS = {
"fr": {
"family": "famille",
"friends": "amis",
"romance": "romance",
"silly": "décalé",
"education": "éducation",
},
"en": {
"family": "family",
"friends": "friends",
"romance": "romance",
"silly": "silly",
"education": "education",
},
}
THEME_DESCRIPTIONS = {
"fr": {
"family": "Thème famille : liens intergénérationnels, rituels familiaux, souvenirs partagés.",
"friends": "Thème amis : complicité, soutien, moments légers, retrouvailles.",
"romance": "Thème romance : connexion, douceur, attention à l’autre, moments à deux.",
"silly": "Thème décalé : questions ludiques, inattendues, créatives, pour faire rire.",
"education": "Thème éducation : curiosité, apprentissages, petites découvertes du quotidien.",
},
"en": {
"family": "Family theme: intergenerational bonds, family rituals, shared memories.",
"friends": "Friends theme: support, playfulness, shared moments, reconnection.",
"romance": "Romance theme: connection, tenderness, attention to each other, moments for two.",
"silly": "Silly theme: playful, unexpected, creative questions that invite laughter.",
"education": "Education theme: curiosity, learning, tiny everyday discoveries.",
},
}
# Few-shot + fallback pools
FEWSHOTS = {
"fr": {
"alimentation": {
"questions": [
"Quelle boisson te donne envie de boire plus d’eau dans la journée ?",
"Quel ajout simple rend ton petit-déj plus rassasiant ?",
"Quand as-tu naturellement faim d’un fruit ou d’un yaourt ?",
"Quelle petite habitude t’aide à ne pas sauter de repas ?",
"Quel plat simple te fait du bien après une journée chargée ?",
"Quelle collation t’aide à tenir jusqu’au dîner sans avoir trop faim ?",
],
"micro_actions": [
"Remplir une gourde ce matin.",
"Ajouter un fruit à la collation de l’après-midi.",
"Remplacer une boisson sucrée par un verre d’eau aujourd’hui.",
"Préparer un snack simple pour demain.",
],
},
"mouvement": {
"questions": [
"Quel trajet pourrais-tu faire à pied au moins une fois cette semaine ?",
"Quelle pause-active de 2 minutes peux-tu glisser entre deux tâches ?",
"Qu’est-ce qui te fait bouger sans y penser (ex: marcher au téléphone) ?",
"Quel moment conviendrait pour quelques étirements doux chaque jour ?",
"Avec qui aimerais-tu partager une courte marche ?",
"Quel geste te réveille le matin (étirement, marche, danse exprès…) ?",
],
"micro_actions": [
"Monter un étage par les escaliers aujourd’hui.",
"Faire 5 étirements doux après le café.",
"Se lever pendant un appel et marcher quelques pas.",
"Programmer une mini-alarme « bouger » dans l’après-midi.",
],
},
"cerveau": {
"questions": [
"Qu’est-ce qui a suscité ta curiosité aujourd’hui ?",
"Quel moment t’irait pour 3 minutes de respiration ?",
"Quel mini-jeu aimes-tu pour réveiller l’esprit (ex: 3 mots fléchés) ?",
"Quel petit sujet aimerais-tu explorer cette semaine ?",
"Quelle activité calme t’aide à passer du travail au repos ?",
"Quel souvenir récent t’a fait sourire en y repensant ?",
],
"micro_actions": [
"Programmer un minuteur de 3 minutes pour respirer.",
"Lire un paragraphe d’un sujet nouveau ce soir.",
"Faire un mini-jeu de cerveau (3 mots fléchés, Sudoku, etc.).",
"Noter une idée ou question qui t’intrigue.",
],
},
"liens": {
"questions": [
"Qui pourrais-tu remercier aujourd’hui et comment ?",
"À qui enverrais-tu un message court pour reprendre contact ?",
"Avec qui partagerais-tu une courte marche cette semaine ?",
"Avec qui aimerais-tu avoir une vraie conversation bientôt ?",
"Quand t’es-tu senti·e soutenu·e pour la dernière fois, et par qui ?",
"Qui aimerais-tu encourager cette semaine ?",
],
"micro_actions": [
"Envoyer un message de gratitude à une personne.",
"Proposer une pause-café de 10 minutes.",
"Envoyer une photo ou un souvenir à quelqu’un avec un petit mot.",
"Poser une vraie question à quelqu’un sur sa journée.",
],
},
"bien-etre": {
"questions": [
"Quel signal t’indique qu’il est temps de faire une pause ?",
"Quelle routine de 2 minutes t’aide à te recentrer ?",
"Quel moment favorise un coucher plus régulier ?",
"Qu’est-ce qui t’aide à te sentir plus léger·e en fin de journée ?",
"Quel endroit de ton quotidien te donne une sensation de calme ?",
"Quand as-tu l’impression de vraiment respirer ?",
],
"micro_actions": [
"Éteindre les écrans 10 minutes plus tôt ce soir.",
"Écrire 3 lignes sur ton humeur du jour.",
"Prendre 5 respirations lentes avant de changer d’activité.",
"Planifier une mini-pause de 5 minutes pour toi demain.",
],
},
},
"en": {
"alimentation": {
"questions": [
"What drink makes you want to sip more water through the day?",
"What small add-on makes your breakfast more filling?",
"When do you naturally crave a fruit or yogurt?",
"What tiny habit helps you not skip meals?",
"What simple dinner feels gentle after a long day?",
"Which snack helps you stay focused without a big energy crash?",
],
"micro_actions": [
"Fill a water bottle this morning.",
"Add one fruit to your afternoon snack.",
"Swap one sugary drink for water today.",
"Plan a simple snack for tomorrow.",
],
},
"mouvement": {
"questions": [
"Which short trip could you walk at least once this week?",
"Which 2-minute active break fits between two tasks?",
"What makes you move without noticing (e.g., walking on calls)?",
"When would a short stretch break feel good each day?",
"Where do you naturally end up walking more?",
"What small move helps you wake up in the morning?",
],
"micro_actions": [
"Take one flight of stairs today.",
"Do 5 light stretches after coffee.",
"Stand up and walk during one call.",
"Set a tiny “move” reminder for this afternoon.",
],
},
"cerveau": {
"questions": [
"What sparked your curiosity today?",
"When could you do 3 minutes of breathing?",
"Which mini-game wakes you up (e.g., 3 crossword clues)?",
"What small topic would you like to learn about this week?",
"What gentle activity helps you shift from work to rest?",
"What recent memory made you smile when you thought of it again?",
],
"micro_actions": [
"Set a 3-minute timer to breathe.",
"Read one paragraph on a new topic tonight.",
"Play a tiny brain game.",
"Write down one idea or question that interests you.",
],
},
"liens": {
"questions": [
"Who could you thank today—and how?",
"Who might you text briefly to reconnect?",
"Who could you invite for a short walk this week?",
"Who would you like to have a real conversation with soon?",
"When did you last feel supported, and by whom?",
"Who would you like to encourage this week?",
],
"micro_actions": [
"Send a gratitude message to one person.",
"Offer a 10-minute coffee break.",
"Send a photo or memory to someone with a short note.",
"Ask someone one genuine question about their day.",
],
},
"bien-etre": {
"questions": [
"What cue tells you it’s time for a pause?",
"What 2-minute routine helps you reset?",
"What time supports a steadier bedtime?",
"What helps you feel lighter at the end of the day?",
"Which place in your daily life feels calming?",
"When do you feel like you can really breathe?",
],
"micro_actions": [
"Turn screens off 10 minutes earlier tonight.",
"Write three lines about your mood today.",
"Take 5 slow breaths before changing tasks.",
"Schedule a 5-minute mini-break for yourself tomorrow.",
],
},
},
}
# ────────────────────────────────────────────────────────────────────────────────
# REPOSITORY HELPERS (questions only, per category)
# ────────────────────────────────────────────────────────────────────────────────
# REPOSITORY HELPERS (questions only, per language + category)
def _default_repo() -> Dict[str, Dict[str, List[str]]]:
"""
Structure:
{
"fr": {"alimentation": [...], "mouvement": [...], ...},
"en": {"alimentation": [...], "mouvement": [...], ...}
}
"""
base_per_lang = {c["key"]: [] for c in CATEGORIES}
return {"fr": dict(base_per_lang), "en": dict(base_per_lang)}
def load_repo() -> Dict[str, Dict[str, List[str]]]:
os.makedirs(os.path.dirname(REPO_PATH), exist_ok=True)
if not os.path.exists(REPO_PATH):
data = _default_repo()
with open(REPO_PATH, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
return data
try:
with open(REPO_PATH, "r", encoding="utf-8") as f:
data = json.load(f)
except Exception:
data = _default_repo()
with open(REPO_PATH, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
return data
# If this is the old format (categories at top level), reset to new format.
if not isinstance(data, dict) or "fr" not in data or "en" not in data:
data = _default_repo()
with open(REPO_PATH, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
return data
# Ensure both languages + all categories exist
base = _default_repo()
for lang in ("fr", "en"):
src = data.get(lang, {})
if isinstance(src, dict):
for k, v in src.items():
if k in base[lang] and isinstance(v, list):
base[lang][k] = v
return base
def save_repo(data: Dict[str, Dict[str, List[str]]]) -> None:
os.makedirs(os.path.dirname(REPO_PATH), exist_ok=True)
with open(REPO_PATH, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
# ────────────────────────────────────────────────────────────────────────────────
# PROMPT + MODEL HELPERS
def build_prompt(lang: str, category_key: str, theme: str) -> str:
cat = next((c for c in CATEGORIES if c["key"] == category_key), None)
if not cat:
category_key = "alimentation"
cat = next((c for c in CATEGORIES if c["key"] == category_key), None)
guide = GUIDES[lang][category_key]
few = FEWSHOTS[lang][category_key]
theme_desc = THEME_DESCRIPTIONS[lang].get(theme, "")
schema = (
"{\n"
' "category": "<category_key>",\n'
' "language": "<fr|en>",\n'
' "questions": ["q1", "q2", "q3", "q4"],\n'
' "micro_actions": ["m1", "m2"],\n'
' "theme": "<family|friends|romance|silly|education>",\n'
' "safety_notes": ""\n'
"}"
)
example_questions = few["questions"][:2]
example_micro = few["micro_actions"][:2]
if lang == "fr":
return f"""
Tu es l’IA du jeu de cartes Neurovie (modèle FINGER).
Tu crées des cartes-question pour parler de routines du quotidien.
- Catégorie: {cat['fr']} {cat['icon']}.
- Focus: {guide}
- Thème actuel: {theme_desc}
- Format: 4 questions + 2 micro-actions, 1 phrase courte chacune.
- Style: concret, bienveillant, sans jugement.
- Interdit: conseils médicaux, diagnostics, emojis.
Réponds UNIQUEMENT en JSON, sans texte autour, selon ce schéma:
{schema}
Exemple de style (à VARIER, ne pas copier):
Questions: {example_questions}
Micro-actions: {example_micro}
Maintenant, renvoie un NOUVEAU JSON différent de l'exemple.
""".strip()
else:
return f"""
You are the AI for the Neurovie card game (FINGER model).
You create question-cards about everyday routines.
- Category: {cat['en']} {cat['icon']}.
- Focus: {guide}
- Current theme: {theme_desc}
- Format: 4 questions + 2 micro-actions, one short sentence each.
- Style: concrete, kind, non-judgmental.
- Forbidden: medical advice, diagnoses, emojis.
Reply ONLY with JSON, no extra text, in this shape:
{schema}
Style example (to vary, do NOT copy):
Questions: {example_questions}
Micro-actions: {example_micro}
Now return a NEW JSON different from the example.
""".strip()
def try_parse_json(text: str) -> Optional[Dict[str, Any]]:
"""
Try to extract a JSON object from the model output.
Handles cases where the model wraps JSON in ``` or ```json fences.
"""
if not text:
return None
stripped = text.strip()
# If the model wrapped the JSON in ``` or ```json fences, strip them.
if stripped.startswith("```"):
lines = stripped.splitlines()
# Drop the first line (``` or ```json)
lines = lines[1:]
# Drop final line if it's a closing fence
if lines and lines[-1].strip().startswith("```"):
lines = lines[:-1]
stripped = "\n".join(lines).strip()
# Now look for the first {...} block
match = re.search(r"\{[\s\S]*\}", stripped)
if not match:
return None
candidate = match.group(0)
try:
return json.loads(candidate)
except Exception:
return None
def model_call(prompt: str) -> str:
"""
Call Hugging Face Inference API using the conversational (chat) task.
This matches models like google/gemma-2-2b-it which only support 'conversational'.
"""
if not MODEL_ID:
raise RuntimeError("MODEL_ID env var is empty. Set it or use the default.")
if not HF_TOKEN:
raise RuntimeError(
"HF_TOKEN is not set. Add a Hugging Face token as a Space secret named HF_TOKEN."
)
client = InferenceClient(model=MODEL_ID, token=HF_TOKEN)
try:
resp = client.chat.completions.create(
model=MODEL_ID,
messages=[
{
"role": "system",
"content": (
"You generate JSON only. "
"Do not add any explanation outside of the JSON object."
),
},
{
"role": "user",
"content": prompt,
},
],
max_tokens=260,
temperature=0.9,
top_p=0.92,
)
except Exception as e:
raise RuntimeError(f"Inference API error: {e}") from e
# Extract text from the first choice
try:
message = resp.choices[0].message
content = message.content
except Exception as e:
raise RuntimeError(f"Unexpected chat response format: {e}") from e
# content can be a string or a list of parts
if isinstance(content, list):
# Newer HF SDK sometimes uses list-of-parts format
parts = []
for part in content:
# part may be a dict like {"type": "text", "text": "..."}
if isinstance(part, dict) and "text" in part:
parts.append(part["text"])
else:
parts.append(str(part))
text = "".join(parts)
else:
text = str(content)
text = text.strip()
if not text:
raise RuntimeError("Empty response from model.")
return text
def normalize_output(
data: Dict[str, Any],
lang: str,
category_key: str,
theme: str,
) -> Dict[str, Any]:
"""
Make model output always valid, even if the model returns emojis, wrong category labels,
capitalized names, or unexpected keys.
"""
# --- FIX CATEGORY ---
raw_cat = str(data.get("category", "")).strip()
# Strip emojis
raw_cat = re.sub(r"[^\w\- ]+", "", raw_cat)
# Lowercase
raw_cat = raw_cat.lower()
# Map likely variants to internal keys
mapping = {
"alimentation": "alimentation",
"nutrition": "alimentation",
"mouvement": "mouvement",
"movement": "mouvement",
"cerveau": "cerveau",
"brain": "cerveau",
"liens": "liens",
"links": "liens",
"bienetre": "bien-etre",
"bien-etre": "bien-etre",
"wellbeing": "bien-etre",
"well being": "bien-etre",
}
# Choose corrected category
clean_cat = mapping.get(raw_cat, category_key)
# --- FIX QUESTIONS ---
q = [str(x).strip() for x in data.get("questions", []) if str(x).strip()]
q = (q + [""] * 4)[:4]
# --- FIX MICRO-ACTIONS ---
m = [str(x).strip() for x in data.get("micro_actions", []) if str(x).strip()]
m = (m + [""] * 2)[:2]
# --- THEME ---
model_theme = str(data.get("theme", "")).strip().lower()
if model_theme not in THEME_KEYS:
model_theme = theme # fall back to selected theme key
# --- SAFETY NOTES ---
safety_notes = str(data.get("safety_notes", ""))
return {
"category": clean_cat,
"language": lang,
"questions": q,
"micro_actions": m,
"theme": model_theme,
"safety_notes": safety_notes,
}
def ai_generate(lang: str, category_key: str, theme: str) -> Dict[str, Any]:
"""
Try to call the model. If anything fails or JSON is invalid,
fall back to shuffling the few-shots and include a safety_notes message.
"""
prompt = build_prompt(lang, category_key, theme)
try:
raw_text = model_call(prompt)
parsed = try_parse_json(raw_text) if raw_text else None
if parsed:
return normalize_output(parsed, lang, category_key, theme)
# Model replied but not valid JSON
few = FEWSHOTS[lang][category_key]
q_pool = few["questions"][:]
m_pool = few["micro_actions"][:]
random.shuffle(q_pool)
random.shuffle(m_pool)
return {
"category": category_key,
"language": lang,
"questions": (q_pool + [""] * 4)[:4],
"micro_actions": (m_pool + [""] * 2)[:2],
"theme": theme,
"safety_notes": (
"Model replied but JSON parsing failed. "
f"raw_text starts with: {repr(raw_text[:160])}"
),
}
except Exception as e:
# Any HF / network / auth error ends up here
few = FEWSHOTS[lang][category_key]
q_pool = few["questions"][:]
m_pool = few["micro_actions"][:]
random.shuffle(q_pool)
random.shuffle(m_pool)
return {
"category": category_key,
"language": lang,
"questions": (q_pool + [""] * 4)[:4],
"micro_actions": (m_pool + [""] * 2)[:2],
"theme": theme,
"safety_notes": f"Model call error: {type(e).__name__}: {e}",
}
# ────────────────────────────────────────────────────────────────────────────────
# MAIN LOGIC: REPO + SESSION "SEEN" QUESTIONS
def get_questions_and_micro(
lang: str,
category_key: str,
variant: str,
seen: List[str],
) -> Dict[str, Any]:
...
seen_set = set(seen or [])
repo = load_repo()
lang_repo = repo.get(lang, {})
repo_qs = lang_repo.get(category_key, [])
unseen_repo = [q for q in repo_qs if q and q not in seen_set]
used_ai = False
theme_used = theme
safety_notes = ""
if len(unseen_repo) >= 4:
# entirely from repo, no AI call
random.shuffle(unseen_repo)
questions = unseen_repo[:4]
# micro-actions from local fewshot pool (cheap)
m_pool = FEWSHOTS[lang][category_key]["micro_actions"][:]
random.shuffle(m_pool)
micro = (m_pool + ["", ""])[:2]
safety_notes = ""
else:
# need fresh AI content
ai_out = ai_generate(lang, category_key, theme)
questions = ai_out["questions"]
micro = ai_out["micro_actions"]
theme_used = ai_out.get("theme", theme)
safety_notes = ai_out.get("safety_notes", "")
used_ai = True
# store new questions in the repo for this language only
new_qs = [q for q in questions if q and q not in repo_qs]
if new_qs:
updated = repo_qs + new_qs
repo.setdefault(lang, {})
repo[lang][category_key] = updated
save_repo(repo)
# update seen for this session
for q in questions:
if q:
seen_set.add(q)
payload = {
"category": category_key,
"language": lang,
"questions": questions,
"micro_actions": micro,
"source": "ai" if used_ai else "repo",
"theme": theme_used,
"safety_notes": safety_notes,
}
# For UI we only return questions + micro + updated seen.
return {
"questions": questions,
"micro_actions": micro,
"seen": list(seen_set),
}
# ────────────────────────────────────────────────────────────────────────────────
# UI – pastel, animated, color-coded cards
def _map_category(choice: str) -> str:
mapping = {
"alimentation 🍎": "alimentation",
"Nutrition 🍎": "alimentation",
"mouvement 🦘": "mouvement",
"Movement 🦘": "mouvement",
"cerveau 🧠": "cerveau",
"Brain 🧠": "cerveau",
"liens 🤝": "liens",
"Connections 🤝": "liens",
"bien-etre 💬": "bien-etre",
"Well-being 💬": "bien-etre",
}
return mapping.get(choice, "alimentation")
def _map_theme(label: str, lang: str) -> str:
"""
Convert the user-visible theme label back to its internal key.
Works for both languages and also accepts the key itself as fallback.
"""
label = (label or "").strip().lower()
# First check if it's already a key
if label in THEME_KEYS:
return label
# Otherwise map via THEME_LABELS
for key in THEME_KEYS:
if label == THEME_LABELS["fr"][key].lower() or label == THEME_LABELS["en"][key].lower():
return key
# Fallback
return "family"
def _card_html(category_key: str, kind: str, title: str, body: str, delay_s: float) -> str:
kind_attr = "question" if kind == "q" else "micro"
cat_class = f"nv-card--cat-{category_key}"
# each card has its own animation delay => "dealing" feel
return (
f"<div class='nv-card {cat_class}' data-kind='{kind_attr}' "
f"style='animation-delay:{delay_s:.2f}s'><div class='nv-card-title'>{title}</div>"
f"<div>{body}</div></div>"
)
def update_cards(lang: str, category_choice: str, theme_choice: str, seen: List[str]):
category_key = _map_category(category_choice)
theme_key = _map_theme(theme_choice, lang)
result = get_questions_and_micro(lang, category_key, theme_key, seen or [])
questions = result["questions"]
micro = result["micro_actions"]
new_seen = result["seen"]
# Stagger cards a bit
delays_q = [0.05, 0.10, 0.15, 0.20]
delays_m = [0.25, 0.30]
if lang == "fr":
q_prefix = "Question"
m_prefix = "Micro-action"
else:
q_prefix = "Question"
m_prefix = "Micro-action"
q_htmls = []
for i in range(4):
text = questions[i] if i < len(questions) else ""
q_htmls.append(
_card_html(
category_key,
"q",
f"{q_prefix} {i+1}",
text,
delays_q[i],
)
)
m_htmls = []
for i in range(2):
text = micro[i] if i < len(micro) else ""
m_htmls.append(
_card_html(
category_key,
"m",
f"{m_prefix} {i+1}",
text,
delays_m[i],
)
)
return (*q_htmls, *m_htmls, new_seen)
# ────────────────────────────────────────────────────────────────────────────────
# UI TEXT TRANSLATIONS
def get_ui_texts(lang: str) -> Dict[str, Any]:
if lang == "fr":
header = """
<div class="nv-fade">
<div class="nv-badge">NEUROVIE · FINGER</div>
<div class="nv-title">Question Studio</div>
<div class="nv-subtitle">
Questions minimalistes pour conversations riches — 4 questions et 2 micro-actions par tirage.
</div>
</div>
"""
category_choices = [
"alimentation 🍎",
"mouvement 🦘",
"cerveau 🧠",
"liens 🤝",
"bien-etre 💬",
]
theme_choices = [THEME_LABELS["fr"][k] for k in THEME_KEYS]
return {
"header_html": header,
"language_label": "Langue",
"theme_label": "Thème",
"category_label": "Catégorie",
"questions_label": "Questions",
"micro_label": "Micro-actions",
"button_text": "Générer un tirage ✨",
"category_choices": category_choices,
"category_default": "alimentation 🍎",
"theme_choices": theme_choices,
"theme_default": THEME_LABELS["fr"]["family"],
"note_text": (
"Note : les cartes s’estompent doucement avec le temps, "
"pour symboliser la mémoire qui s’efface."
),
}
else:
header = """
<div class="nv-fade">
<div class="nv-badge">NEUROVIE · FINGER</div>
<div class="nv-title">Question Studio</div>
<div class="nv-subtitle">
Minimal prompts for rich conversations — 4 questions and 2 micro-actions per draw.
</div>
</div>
"""
category_choices = [
"Nutrition 🍎",
"Movement 🦘",
"Brain 🧠",
"Connections 🤝",
"Well-being 💬",
]
theme_choices = [THEME_LABELS["en"][k] for k in THEME_KEYS]
return {
"header_html": header,
"language_label": "Language",
"theme_label": "Theme",
"category_label": "Category",
"questions_label": "Questions",
"micro_label": "Micro-actions",
"button_text": "Generate card set ✨",
"category_choices": category_choices,
"category_default": "Nutrition 🍎",
"theme_choices": theme_choices,
"theme_default": THEME_LABELS["en"]["family"],
"note_text": (
"Note: the cards gently fade over time, "
"to echo how memories can fade."
),
}
def update_ui_language(lang: str):
t = get_ui_texts(lang)
return (
t["header_html"],
f"<div class='nv-label nv-fade'>{t['language_label']}</div>",
f"<div class='nv-label nv-fade'>{t['theme_label']}</div>",
f"<div class='nv-label nv-fade'>{t['category_label']}</div>",
f"<div class='nv-label nv-fade'>{t['questions_label']}</div>",
f"<div class='nv-label nv-fade'>{t['micro_label']}</div>",
gr.update(choices=t["theme_choices"], value=t["theme_default"]),
gr.update(choices=t["category_choices"], value=t["category_default"]),
gr.update(value=t["button_text"]),
f"<div class='nv-note'>{t['note_text']}</div>",
)
# ────────────────────────────────────────────────────────────────────────────────
# GRADIO APP
with gr.Blocks(title="Neurovie – Question Studio") as demo:
# Inline the CSS content from style.css
if CUSTOM_CSS:
gr.HTML(f"<style>{CUSTOM_CSS}</style>")
seen_state = gr.State([]) # per-session list of seen questions
ui_texts = get_ui_texts("fr")
with gr.Column(elem_classes="nv-shell"):
header = gr.HTML(ui_texts["header_html"])
# Settings
# Language box
with gr.Column(elem_classes="nv-section"):
lang_label_html = gr.HTML(
f"<div class='nv-label nv-fade'>{ui_texts['language_label']}</div>"
)
lang = gr.Radio(
choices=["fr", "en"],
value="fr",
show_label=False,
elem_classes="nv-pills",
)
# Theme box
with gr.Column(elem_classes="nv-section"):
theme_label_html = gr.HTML(
f"<div class='nv-label nv-fade'>{ui_texts['theme_label']}</div>"
)
theme = gr.Radio(
choices=ui_texts["theme_choices"],
value=ui_texts["theme_default"],
show_label=False,
elem_classes="nv-pills",
)
with gr.Column(elem_classes="nv-section"):
category_label_html = gr.HTML(f"<div class='nv-label nv-fade'>{ui_texts['category_label']}</div>")
category = gr.Radio(
choices=ui_texts["category_choices"],
value=ui_texts["category_default"],
show_label=False,
elem_classes="nv-pills",
)
btn = gr.Button(ui_texts["button_text"])
# Question & micro-action cards
with gr.Row(elem_classes="nv-section"):
with gr.Column():
questions_label_html = gr.HTML(f"<div class='nv-label nv-fade'>{ui_texts['questions_label']}</div>")
with gr.Column(elem_classes="nv-card-grid"):
q1 = gr.HTML()
q2 = gr.HTML()
q3 = gr.HTML()
q4 = gr.HTML()
with gr.Column():
micro_label_html = gr.HTML(f"<div class='nv-label nv-fade'>{ui_texts['micro_label']}</div>")
with gr.Column(elem_classes="nv-card-grid"):
m1 = gr.HTML()
m2 = gr.HTML()
# Small explanatory note under the cards
note_html = gr.HTML(
f"<div class='nv-note'>{ui_texts['note_text']}</div>"
)
# Update labels & category choices when language changes
lang.change(
fn=update_ui_language,
inputs=[lang],
outputs=[
header,
lang_label_html,
theme_label_html,
category_label_html,
questions_label_html,
micro_label_html,
theme,
category,
btn,
note_html,
],
show_progress=False
)
btn.click(
update_cards,
[lang, category, theme, seen_state],
[q1, q2, q3, q4, m1, m2, seen_state],
show_progress=False, # hide Gradio built-in progress indicator
)
if __name__ == "__main__":
demo.launch(ssr_mode=False)
|