itsalissonsilva commited on
Commit
aec5662
·
verified ·
1 Parent(s): 514ad06

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -16
app.py CHANGED
@@ -2,11 +2,11 @@ import gradio as gr
2
  import os
3
  from openai import OpenAI
4
 
5
- # Load API key from Hugging Face secret
6
  api_key = os.getenv("OPENAI_API_KEY")
7
  client = OpenAI(api_key=api_key)
8
 
9
- # Initial state
10
  initial_scenario = "You wake up in a strange forest. Paths lead in all directions."
11
  default_choices = [
12
  "Walk north into the dense forest.",
@@ -15,7 +15,7 @@ default_choices = [
15
  "Move west where the land rises."
16
  ]
17
 
18
- # System prompt for role instruction
19
  system_prompt = {
20
  "role": "system",
21
  "content": (
@@ -25,18 +25,20 @@ system_prompt = {
25
  )
26
  }
27
 
28
- # Initialize history
29
  history = [system_prompt, {"role": "user", "content": initial_scenario}]
30
  story_log = initial_scenario
31
 
32
 
33
  def parse_choices_from_response(text):
 
34
  lines = text.strip().split("\n")
35
  options = [line.strip() for line in lines if line.strip().startswith(("1.", "2.", "3.", "4."))]
36
  return options[:4] if options else default_choices
37
 
38
 
39
  def update_story(player_input):
 
40
  global story_log
41
 
42
  history.append({"role": "user", "content": f"> {player_input}"})
@@ -54,7 +56,10 @@ def update_story(player_input):
54
  story_log += f"\n\nYou: {player_input}\n{continuation}"
55
  new_choices = parse_choices_from_response(continuation)
56
 
57
- return story_log, new_choices
 
 
 
58
 
59
 
60
  def handle_button(choice_text):
@@ -63,7 +68,7 @@ def handle_button(choice_text):
63
 
64
  def handle_custom_input(text_input):
65
  if not text_input.strip():
66
- return story_log, default_choices
67
  return update_story(text_input.strip())
68
 
69
 
@@ -71,27 +76,31 @@ def restart_game():
71
  global history, story_log
72
  history = [system_prompt, {"role": "user", "content": initial_scenario}]
73
  story_log = initial_scenario
74
- return story_log, default_choices
75
 
76
 
 
77
  with gr.Blocks() as app:
78
  gr.Markdown("## 🌲 Text-Based RPG Adventure")
 
79
  story_display = gr.Textbox(value=initial_scenario, lines=20, interactive=False, label="Your Story")
80
 
81
  with gr.Row():
82
- choice_btns = [gr.Button(choice) for choice in default_choices]
 
 
 
83
 
84
  custom_input = gr.Textbox(lines=1, placeholder="Or type your action here...", label="Your Action")
85
  restart_btn = gr.Button("🔄 Restart Game")
86
 
87
- # Link button events
88
- for btn in choice_btns:
89
- btn.click(fn=handle_button, inputs=btn, outputs=[story_display, *choice_btns])
90
-
91
- # Link custom text input
92
- custom_input.submit(fn=handle_custom_input, inputs=custom_input, outputs=[story_display, *choice_btns])
93
 
94
- # Restart
95
- restart_btn.click(fn=restart_game, inputs=None, outputs=[story_display, *choice_btns])
96
 
97
  app.launch()
 
2
  import os
3
  from openai import OpenAI
4
 
5
+ # Load API key from environment variable
6
  api_key = os.getenv("OPENAI_API_KEY")
7
  client = OpenAI(api_key=api_key)
8
 
9
+ # Initial game scenario and default choices
10
  initial_scenario = "You wake up in a strange forest. Paths lead in all directions."
11
  default_choices = [
12
  "Walk north into the dense forest.",
 
15
  "Move west where the land rises."
16
  ]
17
 
18
+ # System prompt to guide the assistant behavior
19
  system_prompt = {
20
  "role": "system",
21
  "content": (
 
25
  )
26
  }
27
 
28
+ # Global story and history state
29
  history = [system_prompt, {"role": "user", "content": initial_scenario}]
30
  story_log = initial_scenario
31
 
32
 
33
  def parse_choices_from_response(text):
34
+ """Extract numbered options from the assistant's response"""
35
  lines = text.strip().split("\n")
36
  options = [line.strip() for line in lines if line.strip().startswith(("1.", "2.", "3.", "4."))]
37
  return options[:4] if options else default_choices
38
 
39
 
40
  def update_story(player_input):
41
+ """Add user input, get AI response, update story and extract new choices"""
42
  global story_log
43
 
44
  history.append({"role": "user", "content": f"> {player_input}"})
 
56
  story_log += f"\n\nYou: {player_input}\n{continuation}"
57
  new_choices = parse_choices_from_response(continuation)
58
 
59
+ while len(new_choices) < 4:
60
+ new_choices.append("...")
61
+
62
+ return [story_log] + new_choices[:4]
63
 
64
 
65
  def handle_button(choice_text):
 
68
 
69
  def handle_custom_input(text_input):
70
  if not text_input.strip():
71
+ return [story_log] + default_choices
72
  return update_story(text_input.strip())
73
 
74
 
 
76
  global history, story_log
77
  history = [system_prompt, {"role": "user", "content": initial_scenario}]
78
  story_log = initial_scenario
79
+ return [story_log] + default_choices
80
 
81
 
82
+ # Gradio UI
83
  with gr.Blocks() as app:
84
  gr.Markdown("## 🌲 Text-Based RPG Adventure")
85
+
86
  story_display = gr.Textbox(value=initial_scenario, lines=20, interactive=False, label="Your Story")
87
 
88
  with gr.Row():
89
+ btn1 = gr.Button(default_choices[0])
90
+ btn2 = gr.Button(default_choices[1])
91
+ btn3 = gr.Button(default_choices[2])
92
+ btn4 = gr.Button(default_choices[3])
93
 
94
  custom_input = gr.Textbox(lines=1, placeholder="Or type your action here...", label="Your Action")
95
  restart_btn = gr.Button("🔄 Restart Game")
96
 
97
+ # Bind buttons to handlers
98
+ btn1.click(fn=handle_button, inputs=btn1, outputs=[story_display, btn1, btn2, btn3, btn4])
99
+ btn2.click(fn=handle_button, inputs=btn2, outputs=[story_display, btn1, btn2, btn3, btn4])
100
+ btn3.click(fn=handle_button, inputs=btn3, outputs=[story_display, btn1, btn2, btn3, btn4])
101
+ btn4.click(fn=handle_button, inputs=btn4, outputs=[story_display, btn1, btn2, btn3, btn4])
 
102
 
103
+ custom_input.submit(fn=handle_custom_input, inputs=custom_input, outputs=[story_display, btn1, btn2, btn3, btn4])
104
+ restart_btn.click(fn=restart_game, inputs=None, outputs=[story_display, btn1, btn2, btn3, btn4])
105
 
106
  app.launch()