admin08077 commited on
Commit
62802cb
·
verified ·
1 Parent(s): 559e3a4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -128
app.py CHANGED
@@ -6,88 +6,50 @@ import time
6
  import re
7
 
8
  # --- Load Gemini API key securely ---
 
9
  GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
10
  if not GEMINI_API_KEY:
11
- raise ValueError("❌ GEMINI_API_KEY not found. Set it in Hugging Face Secrets.")
12
 
13
- # --- Initialize the client (no configure method!) ---
14
  client = genai.Client()
15
 
 
 
 
 
 
 
 
 
16
  # --- UI Customization: Bright Neon Trippy Blending ---
17
  cyberpunk_css = """
18
  @import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700&display=swap');
19
-
20
  :root {
21
- --neon-pink: #ff00ff;
22
- --neon-cyan: #00ffff;
23
- --neon-green: #39ff14;
24
- --bg-color-1: #1a001a;
25
- --bg-color-2: #0d001a;
26
  --border-glow: 0 0 5px var(--neon-cyan), 0 0 10px var(--neon-cyan), 0 0 20px var(--neon-pink), 0 0 30px var(--neon-pink);
27
- --text-glow: 0 0 3px var(--neon-green);
28
- }
29
-
30
- .gradio-container {
31
- background: linear-gradient(45deg, var(--bg-color-1), var(--bg-color-2));
32
- font-family: 'Orbitron', sans-serif;
33
- }
34
-
35
- h1, h2, .gr-label {
36
- color: var(--neon-cyan);
37
- text-shadow: 0 0 5px var(--neon-cyan), 0 0 10px var(--neon-cyan);
38
- text-align: center;
39
- }
40
-
41
- .gr-button {
42
- background: transparent;
43
- color: var(--neon-green);
44
- border: 2px solid var(--neon-green);
45
- border-radius: 5px;
46
- box-shadow: 0 0 5px var(--neon-green), 0 0 10px var(--neon-green) inset;
47
- transition: all 0.3s ease;
48
- }
49
-
50
- .gr-button:hover {
51
- background: var(--neon-green);
52
- color: var(--bg-color-2);
53
- box-shadow: 0 0 10px var(--neon-green), 0 0 20px var(--neon-green), 0 0 30px var(--neon-green);
54
- }
55
-
56
- .chatbot {
57
- background-color: rgba(13, 0, 26, 0.8);
58
- border: 1px solid var(--neon-pink);
59
- box-shadow: var(--border-glow);
60
  }
61
-
62
- /* Styling for the new 'messages' format */
63
- [data-testid="bot-message-container"] .avatar-container { background-color: var(--neon-pink); box-shadow: var(--border-glow); }
64
- [data-testid="user-message-container"] .avatar-container { background-color: var(--neon-cyan); box-shadow: var(--border-glow); }
65
-
66
-
67
- .gr-dropdown, .gr-radio {
68
- border: 1px solid var(--neon-cyan) !important;
69
- background-color: var(--bg-color-2) !important;
70
- color: var(--neon-cyan) !important;
71
- }
72
-
73
  footer { display: none !important; }
74
  """
75
 
76
  # --- Helper function to parse LLM lists ---
77
  def parse_list_from_llm(text_response):
78
- """Cleans up numbered/bulleted lists from Gemini response."""
79
  lines = text_response.strip().split('\n')
80
  cleaned_lines = [re.sub(r'^\d+[\.\)]\s*|^\*\s*', '', line).strip() for line in lines]
81
  return [line for line in cleaned_lines if line]
82
 
83
  # --- Core Application Logic ---
84
-
85
  def generate_topics():
86
- """Calls Gemini to generate 20 debate topics using the correct API method."""
87
  prompt = "Generate a list of exactly 20 specific, debatable topics related to the future of coding, banking, and artificial intelligence. The topics should be concise and provocative. Format as a numbered list."
88
  try:
89
- # CORRECTED API CALL
90
- model = client.get_model("models/gemini-1.5-flash")
91
  response = model.generate_content(prompt)
92
  topics = parse_list_from_llm(response.text)
93
  return {
@@ -100,14 +62,11 @@ def generate_topics():
100
  return {topics_state: [], topic_dropdown: gr.Dropdown(visible=False), generate_topics_btn: gr.Button(visible=True)}
101
 
102
  def generate_questions(selected_topic):
103
- """Calls Gemini to generate 20 questions for the selected topic."""
104
  if not selected_topic:
105
  return {question_dropdown: gr.Dropdown(value=None, visible=False)}
106
-
107
  prompt = f"For the debate topic '{selected_topic}', generate a list of exactly 20 thought-provoking starting questions or controversial statements to kick off the debate. Format as a numbered list."
108
  try:
109
- # CORRECTED API CALL
110
- model = client.get_model("models/gemini-1.5-flash")
111
  response = model.generate_content(prompt)
112
  questions = parse_list_from_llm(response.text)
113
  return {
@@ -119,98 +78,78 @@ def generate_questions(selected_topic):
119
  return {questions_state: [], question_dropdown: gr.Dropdown(visible=False)}
120
 
121
  def enable_debate_button(selected_question):
122
- """Makes the debate button visible once a question is chosen."""
123
  return {start_debate_btn: gr.Button(visible=bool(selected_question))}
124
 
125
  def run_debate(topic, question):
126
- """Main function to run the 20-turn debate between two AI agents."""
127
  if not topic or not question:
128
  gr.Warning("Topic and Question must be selected before starting.")
129
  return [], []
130
 
131
- # --- Use the modern client.chats.create() for robust session management ---
132
- agent_a_persona = "You are Agent A, a tech optimist and futurist. You see the best in new technology. Your goal is to argue for the positive aspects of the debate topic. Keep your responses concise and impactful."
133
- agent_b_persona = "You are Agent B, a cautious skeptic and ethicist. You critically examine the potential downsides and risks of new technology. Your goal is to argue for the negative or cautionary aspects of the debate topic. Keep your responses concise and impactful."
134
-
135
- agent_a_chat = client.chats.create(model="gemini-1.5-flash", context=agent_a_persona)
136
- agent_b_chat = client.chats.create(model="gemini-1.5-flash", context=agent_b_persona)
137
 
138
- # UPDATED to use the new 'messages' format (list of dictionaries)
139
- current_history = [{"role": "user", "name": "SYSTEM", "content": f"**DEBATE TOPIC:** {topic}\n\n**STARTING QUESTION:** {question}"}]
140
  yield current_history, current_history
141
 
142
  last_response = question
143
 
144
- for i in range(10): # 10 turns for each agent = 20 total messages
145
  try:
146
- time.sleep(1) # Small delay for realism
147
- # --- Agent A's Turn (Optimist) ---
148
  response_a = agent_a_chat.send_message(f"Based on the last statement ('{last_response}'), provide your optimistic counter-argument.")
149
- current_history.append({"role": "assistant", "name": "Agent A (Optimist)", "content": response_a.text})
150
  last_response = response_a.text
151
  yield current_history, current_history
152
 
153
  time.sleep(1)
154
- # --- Agent B's Turn (Skeptic) ---
155
  response_b = agent_b_chat.send_message(f"Based on Agent A's last statement ('{last_response}'), provide your skeptical counter-argument.")
156
- current_history.append({"role": "assistant", "name": "Agent B (Skeptic)", "content": response_b.text})
157
  last_response = response_b.text
158
  yield current_history, current_history
159
 
160
  except Exception as e:
161
  error_message = f"⚠️ An error occurred during the debate: {e}"
162
- current_history.append({"role": "user", "name": "SYSTEM", "content": error_message})
163
  yield current_history, current_history
164
  break
165
 
166
- current_history.append({"role": "user", "name": "SYSTEM", "content": "--- DEBATE CONCLUDED ---"})
167
  yield {chatbot: current_history, debate_log_state: current_history, save_row: gr.Row(visible=True)}
168
 
169
 
170
  def save_as_json(log):
171
- """Saves the debate log to a JSON file. Now handles dictionary format."""
172
  filepath = "debate_log.json"
 
 
173
  with open(filepath, "w") as f:
174
- # The log is already a list of dictionaries, perfect for JSON.
175
- json.dump(log, f, indent=2)
176
  return gr.File(value=filepath, label="Download JSON")
177
 
178
 
179
  def save_as_html(log):
180
- """Saves the debate log to a styled HTML file. Now handles dictionary format."""
181
  filepath = "debate_log.html"
182
- html_style = """
183
- <style>
184
- body { font-family: sans-serif; background-color: #111; color: #eee; }
185
- .container { max-width: 800px; margin: auto; padding: 20px; }
186
- .message { margin-bottom: 1em; padding: 1em; border-radius: 8px; }
187
- .system { background-color: #333; text-align: center; font-weight: bold; border-left: 5px solid #888;}
188
- .assistant { background-color: #023020; border-left: 5px solid #39ff14; }
189
- .assistant.skeptic { background-color: #30022b; border-left: 5px solid #ff00ff; }
190
- .speaker { font-weight: bold; margin-bottom: 0.5em; display: block; color: #00ffff;}
191
- </style>
192
- """
193
  html_content = f"<html><head><title>Debate Log</title>{html_style}</head><body><div class='container'><h1>Debate Log</h1>"
194
 
195
  for entry in log:
196
  speaker_name = entry.get("name", "Unknown")
197
  message_content = entry.get("content", "")
 
198
 
199
  css_class = entry.get("role", "system")
200
- if "Skeptic" in speaker_name:
201
- css_class += " skeptic"
202
 
203
  safe_message = gr.Markdown(message_content).value.replace('\n', '<br>')
204
- html_content += f'<div class="message {css_class}"><span class="speaker">{speaker_name}</span>{safe_message}</div>'
205
 
206
  html_content += "</div></body></html>"
207
- with open(filepath, "w", encoding='utf-8') as f:
208
- f.write(html_content)
209
  return gr.File(value=filepath, label="Download HTML")
210
 
211
 
212
  def reset_all():
213
- """Resets the entire UI to its initial state."""
214
  return {
215
  chatbot: [], debate_log_state: [], topics_state: [], questions_state: [],
216
  generate_topics_btn: gr.Button(visible=True),
@@ -244,44 +183,21 @@ with gr.Blocks(theme=gr.themes.Base(), css=cyberpunk_css, title="AI DEBATE SIMUL
244
  reset_btn = gr.Button("Start New Debate (Reset All)", variant="stop")
245
 
246
  with gr.Column(scale=3):
 
247
  chatbot = gr.Chatbot(
248
  label="Debate Arena",
249
- # UPDATED: type='messages' is the new standard
250
  type="messages",
251
- # UPDATED: Use a dictionary for named avatars
252
- avatar_images={
253
- "Agent A (Optimist)": "https://i.imgur.com/2GMV9y7.png", # Neon Green Bot
254
- "Agent B (Skeptic)": "https://i.imgur.com/KzX3T21.png", # Neon Pink Bot
255
- "SYSTEM": "https://i.imgur.com/z3uxLzT.png" # System/Cog Icon
256
- },
257
  height=700
258
  )
259
 
260
- # --- Event Handling Logic ---
261
  generate_topics_btn.click(fn=generate_topics, inputs=None, outputs=[topics_state, topic_dropdown, generate_topics_btn])
262
  topic_dropdown.change(fn=generate_questions, inputs=topic_dropdown, outputs=[questions_state, question_dropdown])
263
  question_dropdown.change(fn=enable_debate_button, inputs=question_dropdown, outputs=[start_debate_btn])
264
-
265
- start_debate_btn.click(
266
- fn=lambda: {
267
- generate_topics_btn: gr.Button(visible=False), topic_dropdown: gr.Dropdown(interactive=False),
268
- question_dropdown: gr.Dropdown(interactive=False), start_debate_btn: gr.Button(visible=False),
269
- },
270
- inputs=None,
271
- outputs=[generate_topics_btn, topic_dropdown, question_dropdown, start_debate_btn]
272
- ).then(
273
- fn=run_debate,
274
- inputs=[topic_dropdown, question_dropdown],
275
- outputs=[chatbot, debate_log_state, save_row]
276
- )
277
-
278
  save_json_btn.click(save_as_json, inputs=debate_log_state, outputs=download_file)
279
  save_html_btn.click(save_as_html, inputs=debate_log_state, outputs=download_file)
280
-
281
- reset_btn.click(fn=reset_all, inputs=None, outputs=[
282
- chatbot, debate_log_state, topics_state, questions_state, generate_topics_btn,
283
- topic_dropdown, question_dropdown, start_debate_btn, save_row, download_file
284
- ])
285
 
286
  # --- Launch the App ---
287
  if __name__ == "__main__":
 
6
  import re
7
 
8
  # --- Load Gemini API key securely ---
9
+ # Make sure to set the GEMINI_API_KEY in your Hugging Face Space Secrets
10
  GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
11
  if not GEMINI_API_KEY:
12
+ raise ValueError("❌ GEMINI_API_KEY not found. Please set it in your Hugging Face Space Secrets.")
13
 
14
+ # --- Configure the client (Best Practice) ---
15
  client = genai.Client()
16
 
17
+ # --- Define Avatars for reuse ---
18
+ AVATAR_IMAGES = {
19
+ "Agent A (Optimist)": "https://i.imgur.com/2GMV9y7.png", # Neon Green Bot
20
+ "Agent B (Skeptic)": "https://i.imgur.com/KzX3T21.png", # Neon Pink Bot
21
+ "SYSTEM": "https://i.imgur.com/z3uxLzT.png" # System/Cog Icon
22
+ }
23
+
24
+
25
  # --- UI Customization: Bright Neon Trippy Blending ---
26
  cyberpunk_css = """
27
  @import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700&display=swap');
 
28
  :root {
29
+ --neon-pink: #ff00ff; --neon-cyan: #00ffff; --neon-green: #39ff14;
30
+ --bg-color-1: #1a001a; --bg-color-2: #0d001a;
 
 
 
31
  --border-glow: 0 0 5px var(--neon-cyan), 0 0 10px var(--neon-cyan), 0 0 20px var(--neon-pink), 0 0 30px var(--neon-pink);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  }
33
+ .gradio-container { background: linear-gradient(45deg, var(--bg-color-1), var(--bg-color-2)); font-family: 'Orbitron', sans-serif; }
34
+ h1, h2, .gr-label { color: var(--neon-cyan); text-shadow: 0 0 5px var(--neon-cyan), 0 0 10px var(--neon-cyan); text-align: center; }
35
+ .gr-button { background: transparent; color: var(--neon-green); border: 2px solid var(--neon-green); border-radius: 5px; box-shadow: 0 0 5px var(--neon-green), 0 0 10px var(--neon-green) inset; transition: all 0.3s ease; }
36
+ .gr-button:hover { background: var(--neon-green); color: var(--bg-color-2); box-shadow: 0 0 10px var(--neon-green), 0 0 20px var(--neon-green), 0 0 30px var(--neon-green); }
37
+ .chatbot { background-color: rgba(13, 0, 26, 0.8); border: 1px solid var(--neon-pink); box-shadow: var(--border-glow); }
38
+ .gr-dropdown, .gr-radio { border: 1px solid var(--neon-cyan) !important; background-color: var(--bg-color-2) !important; color: var(--neon-cyan) !important; }
 
 
 
 
 
 
39
  footer { display: none !important; }
40
  """
41
 
42
  # --- Helper function to parse LLM lists ---
43
  def parse_list_from_llm(text_response):
 
44
  lines = text_response.strip().split('\n')
45
  cleaned_lines = [re.sub(r'^\d+[\.\)]\s*|^\*\s*', '', line).strip() for line in lines]
46
  return [line for line in cleaned_lines if line]
47
 
48
  # --- Core Application Logic ---
 
49
  def generate_topics():
 
50
  prompt = "Generate a list of exactly 20 specific, debatable topics related to the future of coding, banking, and artificial intelligence. The topics should be concise and provocative. Format as a numbered list."
51
  try:
52
+ model = genai.GenerativeModel("gemini-2.5-pro")
 
53
  response = model.generate_content(prompt)
54
  topics = parse_list_from_llm(response.text)
55
  return {
 
62
  return {topics_state: [], topic_dropdown: gr.Dropdown(visible=False), generate_topics_btn: gr.Button(visible=True)}
63
 
64
  def generate_questions(selected_topic):
 
65
  if not selected_topic:
66
  return {question_dropdown: gr.Dropdown(value=None, visible=False)}
 
67
  prompt = f"For the debate topic '{selected_topic}', generate a list of exactly 20 thought-provoking starting questions or controversial statements to kick off the debate. Format as a numbered list."
68
  try:
69
+ model = genai.GenerativeModel("gemini-2.5-pro")
 
70
  response = model.generate_content(prompt)
71
  questions = parse_list_from_llm(response.text)
72
  return {
 
78
  return {questions_state: [], question_dropdown: gr.Dropdown(visible=False)}
79
 
80
  def enable_debate_button(selected_question):
 
81
  return {start_debate_btn: gr.Button(visible=bool(selected_question))}
82
 
83
  def run_debate(topic, question):
 
84
  if not topic or not question:
85
  gr.Warning("Topic and Question must be selected before starting.")
86
  return [], []
87
 
88
+ model = genai.GenerativeModel("gemini-2.5-pro")
89
+ agent_a_chat = model.start_chat(history=[{'role':'user', 'parts': ["You are Agent A, a tech optimist and futurist. You see the best in new technology. Your goal is to argue for the positive aspects of the debate topic. Keep your responses concise and impactful."]}, {'role': 'model', 'parts': ["Understood. I will champion the optimistic view."]}])
90
+ agent_b_chat = model.start_chat(history=[{'role':'user', 'parts': ["You are Agent B, a cautious skeptic and ethicist. You critically examine the potential downsides and risks of new technology. Your goal is to argue for the negative or cautionary aspects of the debate topic. Keep your responses concise and impactful."]}, {'role': 'model', 'parts': ["Understood. I will argue the skeptical position."]}])
 
 
 
91
 
92
+ # FIXED: Embed avatar URL directly in each message
93
+ current_history = [{"role": "user", "name": "SYSTEM", "content": f"**DEBATE TOPIC:** {topic}\n\n**STARTING QUESTION:** {question}", "avatar_url": AVATAR_IMAGES["SYSTEM"]}]
94
  yield current_history, current_history
95
 
96
  last_response = question
97
 
98
+ for i in range(10):
99
  try:
100
+ time.sleep(1)
 
101
  response_a = agent_a_chat.send_message(f"Based on the last statement ('{last_response}'), provide your optimistic counter-argument.")
102
+ current_history.append({"role": "assistant", "name": "Agent A (Optimist)", "content": response_a.text, "avatar_url": AVATAR_IMAGES["Agent A (Optimist)"]})
103
  last_response = response_a.text
104
  yield current_history, current_history
105
 
106
  time.sleep(1)
 
107
  response_b = agent_b_chat.send_message(f"Based on Agent A's last statement ('{last_response}'), provide your skeptical counter-argument.")
108
+ current_history.append({"role": "assistant", "name": "Agent B (Skeptic)", "content": response_b.text, "avatar_url": AVATAR_IMAGES["Agent B (Skeptic)"]})
109
  last_response = response_b.text
110
  yield current_history, current_history
111
 
112
  except Exception as e:
113
  error_message = f"⚠️ An error occurred during the debate: {e}"
114
+ current_history.append({"role": "user", "name": "SYSTEM", "content": error_message, "avatar_url": AVATAR_IMAGES["SYSTEM"]})
115
  yield current_history, current_history
116
  break
117
 
118
+ current_history.append({"role": "user", "name": "SYSTEM", "content": "--- DEBATE CONCLUDED ---", "avatar_url": AVATAR_IMAGES["SYSTEM"]})
119
  yield {chatbot: current_history, debate_log_state: current_history, save_row: gr.Row(visible=True)}
120
 
121
 
122
  def save_as_json(log):
 
123
  filepath = "debate_log.json"
124
+ # We can remove the avatar_url for a cleaner JSON log if desired
125
+ clean_log = [{k: v for k, v in entry.items() if k != 'avatar_url'} for entry in log]
126
  with open(filepath, "w") as f:
127
+ json.dump(clean_log, f, indent=2)
 
128
  return gr.File(value=filepath, label="Download JSON")
129
 
130
 
131
  def save_as_html(log):
 
132
  filepath = "debate_log.html"
133
+ html_style = """<style> body { font-family: sans-serif; background-color: #111; color: #eee; } .container { max-width: 800px; margin: auto; padding: 20px; } .message { display: flex; align-items: flex-start; margin-bottom: 1em; padding: 1em; border-radius: 8px; } .avatar { width: 40px; height: 40px; border-radius: 50%; margin-right: 15px; } .content { flex: 1; } .system { background-color: #333; } .assistant { background-color: #023020; } .assistant.skeptic { background-color: #30022b; } .speaker { font-weight: bold; margin-bottom: 0.5em; display: block; color: #00ffff;} </style>"""
 
 
 
 
 
 
 
 
 
 
134
  html_content = f"<html><head><title>Debate Log</title>{html_style}</head><body><div class='container'><h1>Debate Log</h1>"
135
 
136
  for entry in log:
137
  speaker_name = entry.get("name", "Unknown")
138
  message_content = entry.get("content", "")
139
+ avatar_url = entry.get("avatar_url")
140
 
141
  css_class = entry.get("role", "system")
142
+ if "Skeptic" in speaker_name: css_class += " skeptic"
 
143
 
144
  safe_message = gr.Markdown(message_content).value.replace('\n', '<br>')
145
+ html_content += f'<div class="message {css_class}"><img src="{avatar_url}" class="avatar"><div class="content"><span class="speaker">{speaker_name}</span>{safe_message}</div></div>'
146
 
147
  html_content += "</div></body></html>"
148
+ with open(filepath, "w", encoding='utf-8') as f: f.write(html_content)
 
149
  return gr.File(value=filepath, label="Download HTML")
150
 
151
 
152
  def reset_all():
 
153
  return {
154
  chatbot: [], debate_log_state: [], topics_state: [], questions_state: [],
155
  generate_topics_btn: gr.Button(visible=True),
 
183
  reset_btn = gr.Button("Start New Debate (Reset All)", variant="stop")
184
 
185
  with gr.Column(scale=3):
186
+ # FIXED: Removed the problematic avatar_images parameter
187
  chatbot = gr.Chatbot(
188
  label="Debate Arena",
 
189
  type="messages",
 
 
 
 
 
 
190
  height=700
191
  )
192
 
193
+ # Event handlers remain the same
194
  generate_topics_btn.click(fn=generate_topics, inputs=None, outputs=[topics_state, topic_dropdown, generate_topics_btn])
195
  topic_dropdown.change(fn=generate_questions, inputs=topic_dropdown, outputs=[questions_state, question_dropdown])
196
  question_dropdown.change(fn=enable_debate_button, inputs=question_dropdown, outputs=[start_debate_btn])
197
+ start_debate_btn.click(fn=lambda: { generate_topics_btn: gr.Button(visible=False), topic_dropdown: gr.Dropdown(interactive=False), question_dropdown: gr.Dropdown(interactive=False), start_debate_btn: gr.Button(visible=False), }, inputs=None, outputs=[generate_topics_btn, topic_dropdown, question_dropdown, start_debate_btn]).then(fn=run_debate, inputs=[topic_dropdown, question_dropdown], outputs=[chatbot, debate_log_state, save_row])
 
 
 
 
 
 
 
 
 
 
 
 
 
198
  save_json_btn.click(save_as_json, inputs=debate_log_state, outputs=download_file)
199
  save_html_btn.click(save_as_html, inputs=debate_log_state, outputs=download_file)
200
+ reset_btn.click(fn=reset_all, inputs=None, outputs=[chatbot, debate_log_state, topics_state, questions_state, generate_topics_btn, topic_dropdown, question_dropdown, start_debate_btn, save_row, download_file])
 
 
 
 
201
 
202
  # --- Launch the App ---
203
  if __name__ == "__main__":