PeterPinetree commited on
Commit
c2bc11b
·
verified ·
1 Parent(s): f7eb49a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +157 -41
app.py CHANGED
@@ -1,10 +1,9 @@
1
  import gradio as gr
2
  import os
3
  from huggingface_hub import InferenceClient, __version__ as hf_version
 
4
  from typing import Generator, Dict, List, Tuple, Optional
5
  import logging # Added logging for better debugging
6
- from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
7
- import torch
8
 
9
  # Configure logging with DEBUG level and add version info
10
  logging.basicConfig(
@@ -13,12 +12,9 @@ logging.basicConfig(
13
  )
14
  logging.debug(f"Using huggingface_hub version: {hf_version}")
15
 
16
-
17
  # Get token from environment variable
18
- hf_token = os.environ.get("QWEN_BOT_TOKEN")
19
- if not hf_token:
20
- raise ValueError("Hugging Face token not found. Please set QWEN_BOT_TOKEN in the Hugging Face Secrets.")
21
- client = InferenceClient("Qwen/Qwen2.5-72B-Instruct", token=hf_token)
22
 
23
  # Story genres with genre-specific example prompts
24
  GENRE_EXAMPLES = {
@@ -220,45 +216,165 @@ custom_css = """
220
  }
221
  """
222
 
223
- app = Flask(__name__)
224
-
225
- @app.route("/api/respond", methods=["POST"])
226
- def respond_api():
227
- data = request.json
228
- message = data.get("message", "")
229
- chat_history = data.get("chat_history", [])
230
- genre = data.get("genre", "fantasy")
231
- use_full_memory = data.get("use_full_memory", True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
232
 
233
- # Generate system prompt
234
- system_prompt = f"You are an interactive storyteller creating an immersive {genre} choose-your-own-adventure story."
 
 
 
 
 
 
 
 
235
 
236
- # Combine chat history and user message
237
- input_text = system_prompt + "\n" + "\n".join(
238
- [f"User: {msg}\nBot: {resp}" for msg, resp in chat_history]
239
- ) + f"\nUser: {message}\nBot:"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
240
 
241
- try:
242
- # Generate response using Hugging Face Inference API
243
- logging.debug("Generating response via Inference API...")
244
- response = client.text_generation(input_text, max_new_tokens=1024, temperature=0.7, top_p=0.95)
245
- bot_message = response["generated_text"].split("Bot:")[-1].strip()
 
 
 
246
 
247
- # Update chat history
248
- updated_history = chat_history + [(message, bot_message)]
249
- return jsonify({"bot_message": bot_message, "updated_history": updated_history})
250
- except Exception as e:
251
- logging.error(f"Error generating response: {e}")
252
- return jsonify({"error": str(e)}), 500
253
 
254
- @app.route("/api/genres", methods=["GET"])
255
- def get_genres():
256
- return jsonify(list(GENRE_EXAMPLES.keys()))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
257
 
258
- @app.route("/api/examples", methods=["GET"])
259
- def get_examples():
260
- genre = request.args.get("genre", "fantasy")
261
- return jsonify(get_examples_for_genre(genre))
 
 
 
 
 
 
 
 
 
262
 
 
263
  if __name__ == "__main__":
264
- app.run(host="0.0.0.0", port=5000)
 
1
  import gradio as gr
2
  import os
3
  from huggingface_hub import InferenceClient, __version__ as hf_version
4
+ import random
5
  from typing import Generator, Dict, List, Tuple, Optional
6
  import logging # Added logging for better debugging
 
 
7
 
8
  # Configure logging with DEBUG level and add version info
9
  logging.basicConfig(
 
12
  )
13
  logging.debug(f"Using huggingface_hub version: {hf_version}")
14
 
 
15
  # Get token from environment variable
16
+ hf_token = os.environ.get("HF_TOKEN")
17
+ client = InferenceClient("HuggingFaceH4/zephyr-7b-beta", token=hf_token)
 
 
18
 
19
  # Story genres with genre-specific example prompts
20
  GENRE_EXAMPLES = {
 
216
  }
217
  """
218
 
219
+ with gr.Blocks(theme=gr.themes.Soft(), css=custom_css) as demo:
220
+ # Header section with improved instructions
221
+ gr.Markdown("""
222
+ # 🔮 AI Story Studio
223
+ **Collaborate with AI to craft your own adventure, one scene at a time.**
224
+ Pick a genre, start with a prompt or write your own, and guide the story with your choices.
225
+ > **Tip:** The more detail you provide, the deeper the story becomes.
226
+ """)
227
+
228
+ wizard_avatar = get_storyteller_avatar_url()
229
+
230
+ with gr.Row():
231
+ with gr.Column(scale=3):
232
+ # Chat window + user input - USING LIST FORMAT
233
+ chatbot = gr.Chatbot(
234
+ height=400,
235
+ bubble_full_width=True,
236
+ show_copy_button=True,
237
+ avatar_images=(None, wizard_avatar),
238
+ container=True,
239
+ scale=1,
240
+ min_width=800,
241
+ value=[], # Empty list for messages
242
+ render=True
243
+ )
244
+ msg = gr.Textbox(
245
+ placeholder="Describe your next move...",
246
+ container=False,
247
+ scale=4,
248
+ )
249
+
250
+ with gr.Row():
251
+ submit = gr.Button("Continue Story", variant="primary")
252
+ clear = gr.Button("Start New Adventure")
253
+
254
+ with gr.Column(scale=1):
255
+ gr.Markdown("## Adventure Settings")
256
+ genre = gr.Dropdown(
257
+ choices=list(GENRE_EXAMPLES.keys()),
258
+ label="Story Genre",
259
+ info="Choose the theme of your next adventure",
260
+ value="fantasy"
261
+ )
262
+ full_memory = gr.Checkbox(
263
+ label="Full Story Memory",
264
+ value=True,
265
+ info="When enabled, the AI tries to remember the entire story. If disabled, only the last few exchanges are used."
266
+ )
267
+
268
+ gr.Markdown("## Story Starters")
269
+
270
+ # Create three placeholder buttons for story starters
271
+ starter_btn1 = gr.Button("Starter 1", scale=1, min_width=250, elem_classes="compact-btn")
272
+ starter_btn2 = gr.Button("Starter 2", scale=1, min_width=250, elem_classes="compact-btn")
273
+ starter_btn3 = gr.Button("Starter 3", scale=1, min_width=250, elem_classes="compact-btn")
274
+ starter_buttons = [starter_btn1, starter_btn2, starter_btn3]
275
 
276
+ # Simplified update function
277
+ def update_starter_buttons(selected_genre):
278
+ examples = get_examples_for_genre(selected_genre)
279
+ results = []
280
+ for i in range(3):
281
+ if i < len(examples):
282
+ results.append(examples[i])
283
+ else:
284
+ results.append("")
285
+ return tuple(results)
286
 
287
+ # New direct handler for starter clicks
288
+ def use_starter(starter_text: str, history: List[Tuple[str, str]], selected_genre: str, memory_flag: bool) -> Tuple[str, List[Tuple[str, str]]]:
289
+ """Handle starter button clicks with proper message formatting"""
290
+ if not starter_text:
291
+ return "", history
292
+
293
+ try:
294
+ # Use the respond function for consistent handling
295
+ _, updated_history = respond(
296
+ message=starter_text,
297
+ chat_history=history,
298
+ genre=selected_genre,
299
+ use_full_memory=memory_flag
300
+ )
301
+ return "", updated_history
302
+
303
+ except Exception as e:
304
+ error_msg = f"Story magic temporarily interrupted. Please try again. (Error: {str(e)})"
305
+ return "", list(history) + [(starter_text, error_msg)]
306
 
307
+ # Simplified button connections
308
+ for starter_button in starter_buttons:
309
+ starter_button.click(
310
+ fn=use_starter,
311
+ inputs=[starter_button, chatbot, genre, full_memory],
312
+ outputs=[msg, chatbot],
313
+ queue=True
314
+ )
315
 
316
+ # Update buttons when genre changes
317
+ genre.change(
318
+ fn=update_starter_buttons,
319
+ inputs=[genre],
320
+ outputs=starter_buttons
321
+ )
322
 
323
+ # Handler for user input
324
+ msg.submit(
325
+ fn=respond,
326
+ inputs=[msg, chatbot, genre, full_memory],
327
+ outputs=[msg, chatbot]
328
+ )
329
+ submit.click(
330
+ fn=respond,
331
+ inputs=[msg, chatbot, genre, full_memory],
332
+ outputs=[msg, chatbot]
333
+ )
334
+
335
+ # Clear the chatbot for a new adventure
336
+ clear.click(lambda: [], None, chatbot, queue=False)
337
+ clear.click(lambda: "", None, msg, queue=False)
338
+
339
+ # "Download My Story" row with improved layout
340
+ with gr.Row(equal_height=True): # Force equal height for all children
341
+ # Use Column for the button to control width
342
+ with gr.Column(scale=4):
343
+ save_btn = gr.Button("Download My Story", variant="secondary", size="lg")
344
+
345
+ # Use Column for the file output with matching height
346
+ with gr.Column(scale=1):
347
+ story_output = gr.File(
348
+ label=None, # Remove the label that adds extra height
349
+ file_count="single",
350
+ file_types=[".md"],
351
+ interactive=False,
352
+ visible=True,
353
+ elem_classes="compact-file-output" # Optional: for custom CSS styling
354
+ )
355
+
356
+ # Connect the save button to the save_story function
357
+ save_btn.click(
358
+ fn=save_story,
359
+ inputs=[chatbot],
360
+ outputs=story_output,
361
+ queue=False # Process immediately
362
+ )
363
 
364
+ # Initialize buttons with default fantasy genre examples
365
+ initial_examples = get_examples_for_genre("fantasy")
366
+ initial_button_data = tuple(
367
+ initial_examples[i] if i < len(initial_examples) else ""
368
+ for i in range(3)
369
+ )
370
+
371
+ # Update button text on page load
372
+ demo.load(
373
+ fn=lambda: initial_button_data,
374
+ outputs=starter_buttons,
375
+ queue=False
376
+ )
377
 
378
+ # Run the app
379
  if __name__ == "__main__":
380
+ demo.launch(server_name="0.0.0.0", server_port=7860)