ZainabFatimaa commited on
Commit
3e15764
·
verified ·
1 Parent(s): f903acf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -54
app.py CHANGED
@@ -1,15 +1,19 @@
1
  import gradio as gr
2
- from transformers import pipeline, set_seed
 
3
 
4
- # Load a safer, creative chat model
5
- generator = pipeline(
6
- "text-generation",
7
- model="Qwen/Qwen1.5-1.8B-Chat",
8
- device=-1
9
- )
10
 
11
  set_seed(42)
12
 
 
 
 
 
 
 
 
 
13
  def get_actions(theme):
14
  return {
15
  "Fantasy": [
@@ -29,66 +33,86 @@ def get_actions(theme):
29
  ],
30
  }[theme]
31
 
32
- def generate_story(prompt):
33
- output = generator(
34
- prompt,
35
- max_new_tokens=350, # LONGER story
36
- temperature=0.95, # creative but safe
 
 
 
 
 
 
37
  top_p=0.9,
38
- repetition_penalty=1.12,
39
  do_sample=True,
40
- eos_token_id=generator.tokenizer.eos_token_id,
 
 
 
 
 
41
  )
42
- return output[0]["generated_text"].strip()
 
43
 
44
  def start_story(name, theme):
45
- prompt = f"""
46
- You are a gentle, imaginative storyteller.
47
-
48
- STRICT RULES:
49
- - Write ONLY the story
50
- - Do NOT ask questions
51
- - Do NOT ask for feedback
52
- - No violence, threats, or fear
53
- - Keep the tone cozy, adventurous, and magical
54
- - Stay strictly in the {theme} genre
55
-
56
- STORY:
57
- Begin a vivid and creative {theme} story.
58
- The main character is named {name}.
59
- Use rich descriptions, warm emotions, and wonder.
60
- """
61
-
62
- story = generate_story(prompt)
 
 
 
 
 
63
  return story, gr.update(choices=get_actions(theme), visible=True), ""
64
 
65
  def next_step(name, theme, action):
66
  if not action:
67
  return "Please select an action to continue the story.", ""
68
 
69
- prompt = f"""
70
- You are continuing a story.
71
-
72
- STRICT RULES:
73
- - ONLY continue the story
74
- - No questions or feedback requests
75
- - No violence, threats, or dark themes
76
- - Keep it imaginative, light, and engaging
77
- - Stay in the {theme} genre
78
-
79
- STORY CONTEXT:
80
- The main character is {name}.
81
- {name} chooses to {action}.
82
-
83
- Continue the story with rich detail and a sense of wonder.
84
- """
85
-
86
- story = generate_story(prompt)
 
 
 
87
  return story, ""
88
 
89
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="indigo")) as demo:
90
- gr.Markdown("# 📖 Cozy Infinite AI Story Generator")
91
- gr.Markdown("Creative, gentle, and endlessly imaginative stories ✨")
92
 
93
  with gr.Row():
94
  with gr.Column():
@@ -97,7 +121,7 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="indigo")) as demo:
97
  start_btn = gr.Button("🚀 Start Story")
98
 
99
  with gr.Column():
100
- story_out = gr.Textbox(label="Story", lines=12, interactive=False)
101
  action_choice = gr.Dropdown(label="Your Action", choices=[], visible=False)
102
  continue_btn = gr.Button("✨ Continue Story")
103
 
 
1
  import gradio as gr
2
+ from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed
3
+ import torch
4
 
5
+ MODEL_NAME = "Qwen/Qwen1.5-1.8B-Chat"
 
 
 
 
 
6
 
7
  set_seed(42)
8
 
9
+ # Load tokenizer & model correctly
10
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
11
+ model = AutoModelForCausalLM.from_pretrained(
12
+ MODEL_NAME,
13
+ torch_dtype=torch.float32,
14
+ device_map="auto"
15
+ )
16
+
17
  def get_actions(theme):
18
  return {
19
  "Fantasy": [
 
33
  ],
34
  }[theme]
35
 
36
+ def generate_story(messages):
37
+ # Apply proper chat template
38
+ input_ids = tokenizer.apply_chat_template(
39
+ messages,
40
+ return_tensors="pt"
41
+ ).to(model.device)
42
+
43
+ output_ids = model.generate(
44
+ input_ids,
45
+ max_new_tokens=400, # LONG story
46
+ temperature=0.95, # creative but calm
47
  top_p=0.9,
48
+ repetition_penalty=1.1,
49
  do_sample=True,
50
+ eos_token_id=tokenizer.eos_token_id,
51
+ )
52
+
53
+ output = tokenizer.decode(
54
+ output_ids[0][input_ids.shape[-1]:],
55
+ skip_special_tokens=True
56
  )
57
+
58
+ return output.strip()
59
 
60
  def start_story(name, theme):
61
+ messages = [
62
+ {
63
+ "role": "system",
64
+ "content": (
65
+ "You are a gentle, imaginative storyteller.\n"
66
+ "Write ONLY the story.\n"
67
+ "Never ask questions.\n"
68
+ "Never request feedback.\n"
69
+ "No violence, threats, or dark content.\n"
70
+ "Keep the tone cozy, magical, and adventurous."
71
+ )
72
+ },
73
+ {
74
+ "role": "user",
75
+ "content": (
76
+ f"Begin a vivid {theme} story.\n"
77
+ f"The main character is named {name}.\n"
78
+ "Use rich descriptions and warm emotions."
79
+ )
80
+ }
81
+ ]
82
+
83
+ story = generate_story(messages)
84
  return story, gr.update(choices=get_actions(theme), visible=True), ""
85
 
86
  def next_step(name, theme, action):
87
  if not action:
88
  return "Please select an action to continue the story.", ""
89
 
90
+ messages = [
91
+ {
92
+ "role": "system",
93
+ "content": (
94
+ "You are continuing a cozy, imaginative story.\n"
95
+ "Write ONLY the story.\n"
96
+ "No violence or threatening language."
97
+ )
98
+ },
99
+ {
100
+ "role": "user",
101
+ "content": (
102
+ f"The story is set in a {theme} world.\n"
103
+ f"The main character is {name}.\n"
104
+ f"{name} chooses to {action}.\n"
105
+ "Continue the story with wonder and detail."
106
+ )
107
+ }
108
+ ]
109
+
110
+ story = generate_story(messages)
111
  return story, ""
112
 
113
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="indigo")) as demo:
114
+ gr.Markdown("# 📖 Cozy Creative Story Generator")
115
+ gr.Markdown("Safe, imaginative, long-form storytelling ✨")
116
 
117
  with gr.Row():
118
  with gr.Column():
 
121
  start_btn = gr.Button("🚀 Start Story")
122
 
123
  with gr.Column():
124
+ story_out = gr.Textbox(label="Story", lines=14, interactive=False)
125
  action_choice = gr.Dropdown(label="Your Action", choices=[], visible=False)
126
  continue_btn = gr.Button("✨ Continue Story")
127