rui3000 commited on
Commit
2eb899a
ยท
verified ยท
1 Parent(s): bb5919c

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -273
app.py DELETED
@@ -1,273 +0,0 @@
1
- # RPS_SIMPLE_DEMO/app.py
2
- import gradio as gr
3
- import uuid
4
- import httpx
5
- import os
6
- #from RockPaperScissor.repositories import CombinedStorage
7
-
8
- # FastAPI imports
9
- from fastapi import FastAPI, Request
10
- from fastapi.responses import RedirectResponse
11
- from RockPaperScissor.routes import game_router
12
- from RockPaperScissor.services.service_instance import game_service
13
- from RockPaperScissor.services.LLM_service import LLMService
14
-
15
- # --- Game Constants and Types ---
16
- from enum import Enum
17
-
18
- class Move(Enum):
19
- ROCK = "rock"
20
- PAPER = "paper"
21
- SCISSORS = "scissors"
22
-
23
- class GameResult(Enum):
24
- PLAYER_WIN = "player_win"
25
- AI_WIN = "ai_win"
26
- DRAW = "draw"
27
-
28
- # --- Gradio Interface ---
29
- class RockPaperScissorsUI:
30
- def __init__(self, game_service):
31
- self.game_service = game_service
32
- self.session_id = None # Will be set from State
33
- self.ai_models = list(self.game_service.ai_models.keys())
34
- self.ai_descriptions = {
35
- "random": "Random AI: Makes completely random moves.",
36
- "adaptive_markov": "Adaptive Markov AI: Uses entropy-weighted Markov and frequency models to predict your next move."
37
- }
38
- self.last_move = None
39
-
40
- async def reset_session(self, session_id: str):
41
- # Use environment variable for base URL, fallback to localhost
42
- base_url = os.getenv("HF_SPACE_URL", "http://localhost:7860")
43
- async with httpx.AsyncClient() as client:
44
- response = await client.post(
45
- f"{base_url}/api/game/end",
46
- json={"session_id": session_id}
47
- )
48
- print("[DEBUG] /api/game/end response:", response.text)
49
- # Optionally, also clear the session in-memory (if needed)
50
- await self.game_service.clear_session(session_id)
51
- return {"status": "ok"}
52
-
53
- def create_interface(self):
54
- with gr.Blocks(theme=gr.themes.Soft(), title="Rock Paper Scissors ๐ŸŽฎ") as demo:
55
- gr.Markdown("# ๐Ÿชจ๐Ÿ“„โœ‚๏ธ Rock Paper Scissors")
56
-
57
- with gr.Row():
58
- with gr.Column(scale=1):
59
- gr.Markdown("### ๐ŸŽฎ Game Setup")
60
- ai_dropdown = gr.Dropdown(
61
- choices=self.ai_models,
62
- value=self.ai_models[0],
63
- label="Select AI Opponent"
64
- )
65
- ai_description = gr.Markdown(self.ai_descriptions[self.ai_models[0]])
66
-
67
- with gr.Row():
68
- rock_btn = gr.Button("๐Ÿชจ Rock", variant="secondary", elem_classes=["move-btn"])
69
- paper_btn = gr.Button("๐Ÿ“„ Paper", variant="secondary", elem_classes=["move-btn"])
70
- scissors_btn = gr.Button("โœ‚๏ธ Scissors", variant="secondary", elem_classes=["move-btn"])
71
- # Add End Game button
72
- end_btn = gr.Button("End Game", variant="stop", elem_id="end-game-btn")
73
- # Add Help button
74
- help_btn = gr.Button("๐Ÿ’ก Get Help", variant="primary", elem_id="help-btn")
75
-
76
- with gr.Column(scale=2):
77
- gr.Markdown("### ๐Ÿ“Š Game Statistics")
78
- stats_display = gr.Markdown()
79
- result_display = gr.Markdown("Make your move!")
80
- end_result_display = gr.Markdown(visible=False)
81
- help_display = gr.Markdown(visible=False)
82
-
83
- ai_dropdown.change(
84
- fn=self.update_ai_description,
85
- inputs=[ai_dropdown],
86
- outputs=[ai_description]
87
- )
88
-
89
- # Use a Gradio State to store the session ID
90
- move_state = gr.State("")
91
- session_id_state = gr.State("")
92
-
93
- async def play_rock(ai_type, session_id):
94
- if not session_id:
95
- session_id = f"session_{uuid.uuid4()}"
96
- self.session_id = session_id
97
- stats, result = await self.play_round(ai_type, "rock")
98
- return stats, result, session_id
99
- async def play_paper(ai_type, session_id):
100
- if not session_id:
101
- session_id = f"session_{uuid.uuid4()}"
102
- self.session_id = session_id
103
- stats, result = await self.play_round(ai_type, "paper")
104
- return stats, result, session_id
105
- async def play_scissors(ai_type, session_id):
106
- if not session_id:
107
- session_id = f"session_{uuid.uuid4()}"
108
- self.session_id = session_id
109
- stats, result = await self.play_round(ai_type, "scissors")
110
- return stats, result, session_id
111
-
112
- # Add a hidden HTML block with JS to auto-save on tab close
113
- gr.HTML("""
114
- <script>
115
- // Store session ID in localStorage whenever it changes
116
- window.setRpsSessionId = function(session_id) {
117
- if (session_id) {
118
- localStorage.setItem('rps_session_id', session_id);
119
- }
120
- };
121
- // On tab close, send session end to backend
122
- window.onbeforeunload = function() {
123
- let session_id = localStorage.getItem('rps_session_id');
124
- if (session_id) {
125
- navigator.sendBeacon("/game/end", JSON.stringify({session_id: session_id}));
126
- }
127
- };
128
- </script>
129
- """)
130
-
131
- # Inject JS to click End Game button on tab close
132
- gr.HTML("""
133
- <script>
134
- window.onbeforeunload = function() {
135
- var btn = document.getElementById('end-game-btn');
136
- if (btn) {
137
- btn.click();
138
- }
139
- };
140
- </script>
141
- """)
142
-
143
- # After each move, update localStorage with the session ID
144
- def update_session_id_js(session_id):
145
- return f"window.setRpsSessionId('{session_id}');"
146
-
147
- rock_btn.click(
148
- fn=play_rock,
149
- inputs=[ai_dropdown, session_id_state],
150
- outputs=[stats_display, result_display, session_id_state],
151
- js=update_session_id_js
152
- )
153
- paper_btn.click(
154
- fn=play_paper,
155
- inputs=[ai_dropdown, session_id_state],
156
- outputs=[stats_display, result_display, session_id_state],
157
- js=update_session_id_js
158
- )
159
- scissors_btn.click(
160
- fn=play_scissors,
161
- inputs=[ai_dropdown, session_id_state],
162
- outputs=[stats_display, result_display, session_id_state],
163
- js=update_session_id_js
164
- )
165
-
166
- # End Game button logic
167
- async def end_game(session_id):
168
- if not session_id:
169
- return "No session to end. Play a round first!"
170
- result = await self.reset_session(session_id)
171
- return f"End Game: {result['status']} - {result.get('message', '')}"
172
-
173
- end_btn.click(
174
- fn=end_game,
175
- inputs=[session_id_state],
176
- outputs=[end_result_display],
177
- )
178
- end_result_display.visible = True
179
-
180
- # Help button logic
181
- async def get_help():
182
- try:
183
- # Use environment variable for base URL, fallback to localhost
184
- base_url = os.getenv("HF_SPACE_URL", "http://localhost:7860")
185
- async with httpx.AsyncClient() as client:
186
- response = await client.get(f"{base_url}/api/help")
187
- if response.status_code == 200:
188
- data = response.json()
189
- return data.get("suggestion", "No suggestion available.")
190
- else:
191
- return "Sorry, I'm having trouble getting help right now."
192
- except Exception as e:
193
- return f"Error getting help: {str(e)}"
194
-
195
- help_btn.click(
196
- fn=get_help,
197
- inputs=[],
198
- outputs=[help_display]
199
- )
200
-
201
- return demo
202
-
203
- def update_ai_description(self, ai_type: str) -> str:
204
- return self.ai_descriptions[ai_type]
205
-
206
- async def play_round(self, ai_type: str, move: str):
207
- if not self.session_id:
208
- return "Internal Error: Session ID missing in play_round.", "Error"
209
- result = await self.game_service.play_round(self.session_id, move, ai_type)
210
- stats = result["stats"]
211
- stats_text = f"""
212
- ### Game Statistics
213
- - Total Rounds: {stats['total_rounds']}
214
- - Player Wins: {stats['player_wins']} ({stats['player_win_rate']})
215
- - AI Wins: {stats['ai_wins']} ({stats['ai_win_rate']})
216
- - Draws: {stats['draws']}
217
-
218
- ### Move Distribution
219
- - Rock: {stats['rock_percent']}
220
- - Paper: {stats['paper_percent']}
221
- - Scissors: {stats['scissors_percent']}
222
- """
223
- result_text = f"""
224
- ### Round Result
225
- You played: {result['player_move'].upper()}
226
- AI played: {result['ai_move'].upper()}
227
- Result: {result['result'].replace('_', ' ').title()}
228
- """
229
- return stats_text, result_text
230
-
231
- async def clear_session(self, session_id: str):
232
- await self.game_service.clear_session(session_id)
233
- return {"status": "ok"}
234
-
235
- # Create FastAPI app
236
- from fastapi import FastAPI
237
- app = FastAPI()
238
-
239
- # Initialize LLM Service
240
- llm_service = LLMService(
241
- game_service=game_service,
242
- hf_model_name="Qwen/Qwen3-0.6B",
243
- hf_api_token=os.getenv("HF_API_TOKEN")
244
- )
245
-
246
- # Add help endpoint
247
- @app.get("/api/help")
248
- async def get_help():
249
- print("Help endpoint called") # Debug
250
- try:
251
- suggestion = await llm_service.generate_response("who are you")
252
- print("LLM response:", suggestion) # Debug
253
- return {"suggestion": suggestion}
254
- except Exception as e:
255
- print("Error in help endpoint:", e) # Debug
256
- return {"error": str(e), "suggestion": "Sorry, I'm having trouble generating a suggestion right now."}
257
-
258
- # Create Gradio interface
259
- ui = RockPaperScissorsUI(game_service)
260
- demo = ui.create_interface()
261
-
262
- # Mount Gradio app
263
- app.include_router(game_router, prefix="/api/game")
264
- app = gr.mount_gradio_app(app, demo, path="/")
265
-
266
- # Initialize the app
267
- @app.on_event("startup")
268
- async def startup_event():
269
- await game_service.initialize()
270
-
271
- @app.on_event("shutdown")
272
- async def shutdown_event():
273
- await llm_service.close()