Kezovic commited on
Commit
0afa2d5
·
verified ·
1 Parent(s): 0127a4a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +16 -154
app.py CHANGED
@@ -3,51 +3,31 @@ from llama_cpp import Llama
3
  from huggingface_hub import hf_hub_download
4
  import time
5
 
6
- # --- Configuration ---
7
  MODEL_REPO = "Kezovic/iris-q4gguf-nitrallora"
8
  MODEL_FILE = "Llama-3.2-1B-Instruct.Q4_K_M.gguf"
9
  CONTEXT_WINDOW = 2048
10
  MAX_NEW_TOKENS = 400
11
  TEMPERATURE = 1.5
12
 
13
- # --- Model Loading ---
14
- llm_generator = None
15
- llm_analyst = None
16
-
17
- def load_llm():
18
- global llm_generator, llm_analyst
19
- llm = None
20
- print("Downloading model...")
21
- try:
22
- model_path = hf_hub_download(repo_id=MODEL_REPO, filename=MODEL_FILE)
23
-
24
- # Function to create a Llama instance
25
- def create_llama_instance():
26
- return Llama(
27
  model_path=model_path,
28
  n_ctx=CONTEXT_WINDOW,
29
  n_threads=2,
30
  verbose=False,
31
  min_p = 0.1
32
- )
33
-
34
- # 1. Load Generator LLM
35
- print("Loading LLM Generator instance...")
36
- llm_generator = create_llama_instance()
37
- print("LLM Generator loaded.")
38
-
39
- # 2. Load Analyst LLM
40
- print("Loading LLM Analyst instance...")
41
- llm_analyst = create_llama_instance()
42
- print("LLM Analyst loaded.")
43
 
44
- print("Both models loaded successfully!")
45
- except Exception as e:
46
- print(f"Error loading model: {e}")
47
 
48
- load_llm()
49
 
50
- # --- Persona and Format Maps (Hardened Constraints) ---
51
  persona_map = {
52
  "Grumpy Pirate": "You are a grumpy and annoyed pirate captain. Use salty nautical slang, complain about the sea and use 'Arrr' and 'matey'.",
53
  "Philosopher": "You are a philosopher. Use metaphors and reflective musings about the human condition.",
@@ -57,7 +37,6 @@ persona_map = {
57
  }
58
 
59
  format_map = {
60
-
61
  "Free Verse": "Write in Free Verse about the topic. Focus on vivid imagery and emotion.",
62
  "Ballad": "Write a Ballad about the topic. It should tell a narrative story with a clear beginning, middle, and end. Use four-line stanzas (quatrains) and a simple rhyme scheme like A-B-C-B. Keep the language simple and musical.",
63
  "Ode": "Write an Ode about the topic. Use elevated, expressive language to praise or celebrate the subject. Focus on strong emotion, rich imagery, and admiration.",
@@ -66,19 +45,8 @@ format_map = {
66
  "Epic": "Write an Epic about the topic. Use grand, dramatic language."
67
  }
68
 
69
- # --- Refinement Instruction Map ---
70
- REFINEMENT_INSTRUCTIONS = {
71
- "Make it Shorter": "Rewrite the poem to be significantly shorter, reducing the line count by at least 3 lines, while keeping the core meaning.",
72
- "Use Flowery Language": "Rewrite the poem using highly elaborate, decorative, and verbose language with many adjectives and metaphors.",
73
- "Make it More Intense": "Rewrite the poem with greater emotional intensity. Use stronger, more dramatic vocabulary and imagery.",
74
- "Add a Title": "Rewrite the poem and include an original, appropriate title at the very beginning, followed by the poem text.",
75
- "Be More Humorous": "Rewrite the poem to be more light-hearted and humorous. Add a punchline or witty observation."
76
- }
77
-
78
-
79
- # --- Prompt Construction Helper Function (Simplified) ---
80
  def build_poem_prompt(voice_instruction, constraint_instruction, format_type, topic):
81
- """Constructs a simple, direct prompt for initial poem generation."""
82
  full_instruction = (
83
  f"Instruction:\n"
84
  f"{voice_instruction}\n"
@@ -87,12 +55,7 @@ def build_poem_prompt(voice_instruction, constraint_instruction, format_type, to
87
  )
88
  return full_instruction
89
 
90
- # --- LLM Function: Step 1 (Generate Poem) ---
91
  def generate_poem(format_type, persona, topic, progress=gr.Progress()):
92
- if not llm_generator:
93
- return "Error: Generator model not loaded."
94
- if not topic:
95
- return "Please enter a topic!"
96
 
97
  progress(0, desc="Consulting the Muse...")
98
  time.sleep(0.2)
@@ -114,12 +77,7 @@ def generate_poem(format_type, persona, topic, progress=gr.Progress()):
114
  progress(1.0, desc="Poem draft complete!")
115
  return poem_text
116
 
117
- # --- LLM Function: Step 2 (Analyze Poem - SIMPLIFIED) ---
118
  def analyze_poem(poem_text, progress=gr.Progress()):
119
- if not llm_analyst:
120
- return "Error: Analyst model not loaded."
121
- if not poem_text or poem_text.startswith("Error:"):
122
- return "Please generate a valid poem first!"
123
 
124
  progress(0, desc="Analyzing style for literary match...")
125
  time.sleep(0.2)
@@ -140,50 +98,10 @@ def analyze_poem(poem_text, progress=gr.Progress()):
140
  progress(1.0, desc="Analysis complete!")
141
  return poet_suggestion
142
 
143
- # --- LLM Function: Step 3 (Refine Poem - MODIFIED SIGNATURE FOR GRADIO) ---
144
- # NOTE: This function now accepts an *explicit* instruction string, which Gradio will bind.
145
- def refine_poem(poem_text, refinement_instruction, progress=gr.Progress()):
146
- if not llm_generator:
147
- return "Error: Generator model not loaded."
148
- if not poem_text or poem_text.startswith("Error:"):
149
- return "Please generate a valid poem first before refining it!"
150
-
151
- progress(0, desc=f"Applying refinement: {refinement_instruction}...")
152
- time.sleep(0.2)
153
-
154
- # Combined instruction for refinement
155
- refinement_prompt = (
156
- f"You are a highly disciplined creative writer. Your task is to revise the following poem based ONLY on the REVISION INSTRUCTION.\n"
157
- f"REVISION INSTRUCTION: {refinement_instruction}\n"
158
- f"Your output must contain ONLY the revised poem text, nothing else.\n\n"
159
- f"ORIGINAL POEM:\n{poem_text}\n\n"
160
- f"REVISED POEM: "
161
- )
162
-
163
- output = llm_generator(
164
- prompt=refinement_prompt,
165
- max_tokens=MAX_NEW_TOKENS,
166
- temperature=TEMPERATURE,
167
- stop=["ORIGINAL POEM:", "\n\n\n"],
168
- echo=False
169
- )
170
-
171
- # Clean up output
172
- revised_poem_text = output['choices'][0]['text'].strip()
173
-
174
- # Simple check to remove the REVISED POEM: marker if the model echoes it
175
- if revised_poem_text.startswith("REVISED POEM:"):
176
- revised_poem_text = revised_poem_text[len("REVISED POEM:"):].strip()
177
-
178
- progress(1.0, desc="Refinement complete!")
179
- return revised_poem_text
180
-
181
- # --- UI Layout ---
182
  with gr.Blocks(title="The Poetry Workshop", theme=gr.themes.Soft()) as demo:
183
- gr.Markdown("# 🖋️ The Poetry Workshop - Collaborative Analyst")
184
  gr.Markdown("Generate a poem based on a topic and persona, then use the separate buttons to analyze or refine the output.")
185
 
186
- ## 📝 Poem Generation Controls
187
  with gr.Group():
188
  with gr.Row(equal_height=True):
189
  gr.Markdown("### I want to write a ")
@@ -212,12 +130,11 @@ with gr.Blocks(title="The Poetry Workshop", theme=gr.themes.Soft()) as demo:
212
  show_label=False,
213
  scale=5
214
  )
215
- generate_btn = gr.Button("Create Poem Draft", variant="primary", scale=1)
216
 
217
  gr.Markdown("---")
218
 
219
- ## 🔍 Analysis Section
220
- analyze_btn = gr.Button("🔍 Analyze This Poem", variant="secondary")
221
 
222
  with gr.Row():
223
  output_display = gr.Textbox(
@@ -228,7 +145,7 @@ with gr.Blocks(title="The Poetry Workshop", theme=gr.themes.Soft()) as demo:
228
  )
229
 
230
  poet_suggestion_display = gr.Textbox(
231
- label="Literary Analysis: Suggested Poet",
232
  lines=12,
233
  interactive=False,
234
  placeholder="Click 'Analyze This Poem' to run the LLM analysis."
@@ -236,72 +153,17 @@ with gr.Blocks(title="The Poetry Workshop", theme=gr.themes.Soft()) as demo:
236
 
237
  gr.Markdown("---")
238
 
239
- ## ⚙️ Poem Refinement Section
240
- with gr.Group():
241
- gr.Markdown("### Refine Poem")
242
- gr.Markdown("Click a button below to automatically revise the current poem in the **'Your Poem'** box.")
243
-
244
- # NOTE: Buttons are created but we will reference them explicitly below
245
- buttons_refinement = {}
246
- with gr.Row():
247
- for label in REFINEMENT_INSTRUCTIONS.keys():
248
- # Store the button object in the dictionary for later reference
249
- buttons_refinement[label] = gr.Button(label, scale=1, variant="light")
250
-
251
- # --- Event Handling ---
252
-
253
- # 1. Initial Generation
254
  generate_btn.click(
255
  fn=generate_poem,
256
  inputs=[format_dropdown, persona_dropdown, topic_input],
257
  outputs=[output_display]
258
  )
259
 
260
- # 2. Analysis
261
  analyze_btn.click(
262
  fn=analyze_poem,
263
  inputs=[output_display],
264
  outputs=poet_suggestion_display
265
  )
266
 
267
- # 3. Refinement Events (Rewritten to remove lambda)
268
-
269
- # Create explicit functions for each button click, passing the desired instruction
270
-
271
- # Make it Shorter
272
- buttons_refinement["Make it Shorter"].click(
273
- fn=refine_poem,
274
- inputs=[output_display, gr.State(REFINEMENT_INSTRUCTIONS["Make it Shorter"])],
275
- outputs=[output_display]
276
- )
277
-
278
- # Use Flowery Language
279
- buttons_refinement["Use Flowery Language"].click(
280
- fn=refine_poem,
281
- inputs=[output_display, gr.State(REFINEMENT_INSTRUCTIONS["Use Flowery Language"])],
282
- outputs=[output_display]
283
- )
284
-
285
- # Make it More Intense
286
- buttons_refinement["Make it More Intense"].click(
287
- fn=refine_poem,
288
- inputs=[output_display, gr.State(REFINEMENT_INSTRUCTIONS["Make it More Intense"])],
289
- outputs=[output_display]
290
- )
291
-
292
- # Add a Title
293
- buttons_refinement["Add a Title"].click(
294
- fn=refine_poem,
295
- inputs=[output_display, gr.State(REFINEMENT_INSTRUCTIONS["Add a Title"])],
296
- outputs=[output_display]
297
- )
298
-
299
- # Be More Humorous
300
- buttons_refinement["Be More Humorous"].click(
301
- fn=refine_poem,
302
- inputs=[output_display, gr.State(REFINEMENT_INSTRUCTIONS["Be More Humorous"])],
303
- outputs=[output_display]
304
- )
305
-
306
  if __name__ == "__main__":
307
  demo.launch()
 
3
  from huggingface_hub import hf_hub_download
4
  import time
5
 
 
6
  MODEL_REPO = "Kezovic/iris-q4gguf-nitrallora"
7
  MODEL_FILE = "Llama-3.2-1B-Instruct.Q4_K_M.gguf"
8
  CONTEXT_WINDOW = 2048
9
  MAX_NEW_TOKENS = 400
10
  TEMPERATURE = 1.5
11
 
12
+ def create_llama_instance():
13
+ return Llama(
 
 
 
 
 
 
 
 
 
 
 
 
14
  model_path=model_path,
15
  n_ctx=CONTEXT_WINDOW,
16
  n_threads=2,
17
  verbose=False,
18
  min_p = 0.1
19
+ )
20
+
21
+ def load_llm():
22
+
23
+ model_path = hf_hub_download(repo_id=MODEL_REPO, filename=MODEL_FILE)
24
+ llm_generator = create_llama_instance()
25
+ llm_analyst = create_llama_instance()
 
 
 
 
26
 
27
+ return llm_generator, llm_analyst
 
 
28
 
29
+ llm_generator, llm_analyst = load_llm()
30
 
 
31
  persona_map = {
32
  "Grumpy Pirate": "You are a grumpy and annoyed pirate captain. Use salty nautical slang, complain about the sea and use 'Arrr' and 'matey'.",
33
  "Philosopher": "You are a philosopher. Use metaphors and reflective musings about the human condition.",
 
37
  }
38
 
39
  format_map = {
 
40
  "Free Verse": "Write in Free Verse about the topic. Focus on vivid imagery and emotion.",
41
  "Ballad": "Write a Ballad about the topic. It should tell a narrative story with a clear beginning, middle, and end. Use four-line stanzas (quatrains) and a simple rhyme scheme like A-B-C-B. Keep the language simple and musical.",
42
  "Ode": "Write an Ode about the topic. Use elevated, expressive language to praise or celebrate the subject. Focus on strong emotion, rich imagery, and admiration.",
 
45
  "Epic": "Write an Epic about the topic. Use grand, dramatic language."
46
  }
47
 
 
 
 
 
 
 
 
 
 
 
 
48
  def build_poem_prompt(voice_instruction, constraint_instruction, format_type, topic):
49
+
50
  full_instruction = (
51
  f"Instruction:\n"
52
  f"{voice_instruction}\n"
 
55
  )
56
  return full_instruction
57
 
 
58
  def generate_poem(format_type, persona, topic, progress=gr.Progress()):
 
 
 
 
59
 
60
  progress(0, desc="Consulting the Muse...")
61
  time.sleep(0.2)
 
77
  progress(1.0, desc="Poem draft complete!")
78
  return poem_text
79
 
 
80
  def analyze_poem(poem_text, progress=gr.Progress()):
 
 
 
 
81
 
82
  progress(0, desc="Analyzing style for literary match...")
83
  time.sleep(0.2)
 
98
  progress(1.0, desc="Analysis complete!")
99
  return poet_suggestion
100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  with gr.Blocks(title="The Poetry Workshop", theme=gr.themes.Soft()) as demo:
102
+ gr.Markdown("# The Poetry Workshop - Collaborative Analyst")
103
  gr.Markdown("Generate a poem based on a topic and persona, then use the separate buttons to analyze or refine the output.")
104
 
 
105
  with gr.Group():
106
  with gr.Row(equal_height=True):
107
  gr.Markdown("### I want to write a ")
 
130
  show_label=False,
131
  scale=5
132
  )
133
+ generate_btn = gr.Button("Create Poem Draft", variant="primary", scale=1)
134
 
135
  gr.Markdown("---")
136
 
137
+ analyze_btn = gr.Button("Analyze This Poem", variant="secondary")
 
138
 
139
  with gr.Row():
140
  output_display = gr.Textbox(
 
145
  )
146
 
147
  poet_suggestion_display = gr.Textbox(
148
+ label="Literary Analysis",
149
  lines=12,
150
  interactive=False,
151
  placeholder="Click 'Analyze This Poem' to run the LLM analysis."
 
153
 
154
  gr.Markdown("---")
155
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
  generate_btn.click(
157
  fn=generate_poem,
158
  inputs=[format_dropdown, persona_dropdown, topic_input],
159
  outputs=[output_display]
160
  )
161
 
 
162
  analyze_btn.click(
163
  fn=analyze_poem,
164
  inputs=[output_display],
165
  outputs=poet_suggestion_display
166
  )
167
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168
  if __name__ == "__main__":
169
  demo.launch()