BryanBradfo commited on
Commit
64e02f6
·
verified ·
1 Parent(s): 1f6febe

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -66
app.py CHANGED
@@ -1,40 +1,7 @@
1
- import sys
2
- from types import ModuleType
3
- import os
4
-
5
- # ==========================================
6
- # 🛡️ ZONE DE PATCH (NE PAS TOUCHER)
7
- # ==========================================
8
  import gradio as gr
9
- from gradio.components.base import Component
10
-
11
- # 1. Patch i18n (Le module manquant)
12
- if not hasattr(gr, "i18n"):
13
- mock_i18n = ModuleType("gradio.i18n")
14
- mock_i18n.I18nData = str
15
- sys.modules["gradio.i18n"] = mock_i18n
16
- gr.i18n = mock_i18n
17
-
18
- # 2. Patch Component.__init__ (L'argument inconnu)
19
- # On sauvegarde l'initialisation originale de Gradio
20
- original_init = Component.__init__
21
-
22
- def patched_init(self, *args, **kwargs):
23
- # Si on trouve l'argument fautif 'preserved_by_key', on le retire (pop)
24
- # avant de passer la main au vrai Gradio.
25
- kwargs.pop("preserved_by_key", None)
26
- original_init(self, *args, **kwargs)
27
-
28
- # On remplace l'init officiel par notre version tolérante
29
- Component.__init__ = patched_init
30
- print("✅ Patchs de compatibilité appliqués avec succès.")
31
-
32
- # ==========================================
33
- # ♟️ DÉBUT DE L'APPLICATION
34
- # ==========================================
35
-
36
  from gradio_chessboard import Chessboard
37
  import chess
 
38
  from openai import OpenAI
39
  from elevenlabs.client import ElevenLabs
40
  from chess_tools import analyze_position
@@ -50,14 +17,13 @@ eleven_client = ElevenLabs(api_key=ELEVEN_API_KEY) if ELEVEN_API_KEY else None
50
  SYSTEM_PROMPT = """
51
  Tu es Garry, un Grand Maître d'échecs légendaire.
52
  Tu commentes la partie en direct pour un débutant.
53
- 1. Analyse le déséquilibre matériel et l'ouverture.
54
- 2. Si le joueur est en échec ou fait une erreur, sois critique avec humour.
55
- 3. Si le coup est bon, sois impressionné.
56
- 4. Reste très court (2 phrases max) pour l'audio.
57
  """
58
 
59
  def generate_voice(text):
60
- """Génère l'audio via ElevenLabs"""
61
  if not eleven_client or not text: return None
62
  try:
63
  audio_stream = eleven_client.generate(
@@ -71,65 +37,54 @@ def generate_voice(text):
71
  f.write(chunk)
72
  return path
73
  except Exception as e:
74
- print(f"Erreur ElevenLabs: {e}")
75
  return None
76
 
77
  def process_move(fen):
78
- """Cerveau de l'agent"""
79
  if not fen: return "", None
80
 
81
- # 1. Analyse Technique
82
  analysis = analyze_position(fen)
83
 
84
- # 2. Génération du Commentaire
85
- commentary = "Analyse en cours..."
86
  if openai_client:
87
  try:
88
  response = openai_client.chat.completions.create(
89
  model="gpt-4o-mini",
90
  messages=[
91
  {"role": "system", "content": SYSTEM_PROMPT},
92
- {"role": "user", "content": f"Analyse : {str(analysis)}"}
93
  ]
94
  )
95
  commentary = response.choices[0].message.content
96
  except Exception as e:
97
  commentary = f"Erreur IA: {e}"
98
  else:
99
- commentary = "Veuillez configurer les clés API (OpenAI/ElevenLabs)."
100
 
101
- # 3. Génération Audio
102
  audio_path = generate_voice(commentary)
103
-
104
  return commentary, audio_path
105
 
106
- # --- Interface Gradio ---
 
107
  with gr.Blocks(title="ChessCoach AI") as demo:
108
- gr.Markdown(
109
- """
110
- # ♟️ ChessCoach AI
111
- ### Votre Grand Maître Personnel (Powered by MCP)
112
- Jouez les Blancs. L'IA analyse votre position et vous coache vocalement.
113
- """
114
- )
115
 
116
  with gr.Row():
117
- with gr.Column(scale=2):
118
  board = Chessboard(
119
  label="Plateau",
120
  value=chess.STARTING_FEN,
121
  game_mode=True,
122
- interactive=True,
123
- elem_id="chessboard"
124
  )
125
 
126
- with gr.Column(scale=1):
127
- gr.Markdown("### 🎙️ Coach Garry")
128
- coach_output = gr.Textbox(label="Analyse", interactive=False, lines=3)
129
  audio_output = gr.Audio(label="Voix", autoplay=True, interactive=False)
130
-
131
- with gr.Accordion("🔍 Données MCP", open=False):
132
- debug_json = gr.JSON(label="État Technique")
133
 
134
  def game_loop(fen):
135
  text, audio = process_move(fen)
@@ -138,5 +93,7 @@ with gr.Blocks(title="ChessCoach AI") as demo:
138
 
139
  board.move(fn=game_loop, inputs=[board], outputs=[coach_output, audio_output, debug_json])
140
 
 
 
141
  if __name__ == "__main__":
142
- demo.launch()
 
 
 
 
 
 
 
 
1
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  from gradio_chessboard import Chessboard
3
  import chess
4
+ import os
5
  from openai import OpenAI
6
  from elevenlabs.client import ElevenLabs
7
  from chess_tools import analyze_position
 
17
  SYSTEM_PROMPT = """
18
  Tu es Garry, un Grand Maître d'échecs légendaire.
19
  Tu commentes la partie en direct pour un débutant.
20
+ 1. Reçois l'analyse JSON.
21
+ 2. Si erreur grave (Matériel/Echec), sois critique et drôle.
22
+ 3. Si bon coup, sois bref et approbateur.
23
+ 4. MAXIMUM 2 phrases courtes.
24
  """
25
 
26
  def generate_voice(text):
 
27
  if not eleven_client or not text: return None
28
  try:
29
  audio_stream = eleven_client.generate(
 
37
  f.write(chunk)
38
  return path
39
  except Exception as e:
40
+ print(f"ElevenLabs Error: {e}")
41
  return None
42
 
43
  def process_move(fen):
 
44
  if not fen: return "", None
45
 
46
+ # 1. Analyse (MCP)
47
  analysis = analyze_position(fen)
48
 
49
+ # 2. LLM
50
+ commentary = "..."
51
  if openai_client:
52
  try:
53
  response = openai_client.chat.completions.create(
54
  model="gpt-4o-mini",
55
  messages=[
56
  {"role": "system", "content": SYSTEM_PROMPT},
57
+ {"role": "user", "content": f"Analyse: {str(analysis)}"}
58
  ]
59
  )
60
  commentary = response.choices[0].message.content
61
  except Exception as e:
62
  commentary = f"Erreur IA: {e}"
63
  else:
64
+ commentary = "Clés API manquantes."
65
 
66
+ # 3. Audio
67
  audio_path = generate_voice(commentary)
 
68
  return commentary, audio_path
69
 
70
+ # --- Interface ---
71
+ # Pas de paramètre 'theme' pour éviter les conflits, on reste simple.
72
  with gr.Blocks(title="ChessCoach AI") as demo:
73
+ gr.Markdown("# ♟️ ChessCoach AI (MCP Agent)")
 
 
 
 
 
 
74
 
75
  with gr.Row():
76
+ with gr.Column():
77
  board = Chessboard(
78
  label="Plateau",
79
  value=chess.STARTING_FEN,
80
  game_mode=True,
81
+ interactive=True
 
82
  )
83
 
84
+ with gr.Column():
85
+ coach_output = gr.Textbox(label="Coach Garry", interactive=False)
 
86
  audio_output = gr.Audio(label="Voix", autoplay=True, interactive=False)
87
+ debug_json = gr.JSON(label="Données MCP")
 
 
88
 
89
  def game_loop(fen):
90
  text, audio = process_move(fen)
 
93
 
94
  board.move(fn=game_loop, inputs=[board], outputs=[coach_output, audio_output, debug_json])
95
 
96
+ # --- LA LIGNE CRUCIALE ---
97
+ # ssr_mode=False est OBLIGATOIRE pour gradio_chessboard sur Gradio 5
98
  if __name__ == "__main__":
99
+ demo.launch(ssr_mode=False)