Update app.py
Browse files
app.py
CHANGED
|
@@ -4,12 +4,11 @@ from huggingface_hub import hf_hub_download
|
|
| 4 |
import time
|
| 5 |
|
| 6 |
# --- Configuration ---
|
| 7 |
-
MODEL_REPO = "Kezovic/iris-q4gguf-
|
| 8 |
-
MODEL_FILE = "
|
| 9 |
CONTEXT_WINDOW = 2048
|
| 10 |
MAX_NEW_TOKENS = 400
|
| 11 |
-
TEMPERATURE = 0.7
|
| 12 |
-
# Note: min_p = 0.1 is kept as requested in the configuration from the previous prompt
|
| 13 |
|
| 14 |
# --- Model Loading ---
|
| 15 |
llm = None
|
|
@@ -50,14 +49,12 @@ format_map = {
|
|
| 50 |
# --- Prompt Construction Helper Function (Simplified) ---
|
| 51 |
def build_poem_prompt(voice_instruction, constraint_instruction, format_type, topic):
|
| 52 |
"""Constructs a simple, direct prompt for initial poem generation."""
|
| 53 |
-
|
| 54 |
# Combined, prioritized instruction block for maximum clarity
|
| 55 |
full_instruction = (
|
| 56 |
f"You are a highly disciplined creative writer. {voice_instruction} "
|
| 57 |
f"You must write a {format_type} about '{topic}'.\n"
|
| 58 |
f"STRICT FORMAT RULE: {constraint_instruction}\n"
|
| 59 |
-
f"Your output must contain ONLY the poem, nothing else. Do NOT include a title.\n
|
| 60 |
-
f"BEGIN POEM: " # Simple, clear marker for generation start
|
| 61 |
)
|
| 62 |
return full_instruction
|
| 63 |
|
|
@@ -70,26 +67,27 @@ def generate_poem(format_type, persona, topic, progress=gr.Progress()):
|
|
| 70 |
return "Error: Model not loaded."
|
| 71 |
if not topic:
|
| 72 |
return "Please enter a topic!"
|
| 73 |
-
|
| 74 |
# --- POEM GENERATION ---
|
| 75 |
progress(0.2, desc=f"Summoning {persona} and drafting poem...")
|
| 76 |
selected_voice = persona_map.get(persona, "You are a helpful assistant.")
|
| 77 |
selected_constraint = format_map.get(format_type, "Write a poem.")
|
| 78 |
|
| 79 |
full_poem_prompt = build_poem_prompt(selected_voice, selected_constraint, format_type, topic)
|
| 80 |
-
|
| 81 |
output = llm(
|
| 82 |
prompt=full_poem_prompt,
|
| 83 |
max_tokens=MAX_NEW_TOKENS,
|
| 84 |
temperature=TEMPERATURE,
|
| 85 |
-
stop
|
|
|
|
| 86 |
echo=False
|
| 87 |
)
|
| 88 |
|
| 89 |
# Clean up output
|
| 90 |
poem_text = output['choices'][0]['text'].strip()
|
| 91 |
-
|
| 92 |
-
|
|
|
|
| 93 |
|
| 94 |
progress(1.0, desc="Poem draft complete!")
|
| 95 |
# NOTE: Only returns the poem output
|
|
@@ -101,52 +99,44 @@ def analyze_poem(poem_text, progress=gr.Progress()):
|
|
| 101 |
return "Error: Model not loaded."
|
| 102 |
if not poem_text or poem_text.startswith("Error:") or poem_text.startswith("Please enter"):
|
| 103 |
return "Please generate a valid poem first!"
|
| 104 |
-
|
| 105 |
progress(0, desc="Analyzing style for literary match...")
|
| 106 |
time.sleep(0.2)
|
| 107 |
-
|
| 108 |
# Secondary prompt for the analysis task - MINIMALIST QUESTION
|
|
|
|
| 109 |
poet_prompt = (
|
| 110 |
f"You are a literary analyst. Your task is to analyze the POEM below and identify the single most appropriate "
|
| 111 |
f"REAL, historical poet whose style and themes match the poem. Do NOT suggest fictional characters.\n"
|
| 112 |
-
f"Format your answer ONLY as: Poet Name: [Name] - Justification: [Reason].\n\n"
|
| 113 |
-
f"POEM:\n{poem_text}\n
|
| 114 |
-
f"ANALYSIS: " # Simple marker for generation start
|
| 115 |
)
|
| 116 |
|
| 117 |
output_poet = llm(
|
| 118 |
prompt=poet_prompt,
|
| 119 |
max_tokens=80, # Keep this response short
|
| 120 |
temperature=0.4,
|
| 121 |
-
stop
|
|
|
|
| 122 |
echo=False
|
| 123 |
)
|
| 124 |
|
| 125 |
# Clean up the output using simple string manipulation
|
| 126 |
poet_suggestion = output_poet['choices'][0]['text'].strip()
|
| 127 |
|
| 128 |
-
# Clean up
|
| 129 |
-
if "
|
| 130 |
-
poet_suggestion = poet_suggestion[
|
| 131 |
|
| 132 |
-
if "Poet Name:" in poet_suggestion:
|
| 133 |
-
poet_suggestion = poet_suggestion.replace("Poet Name:", "").replace(" - Justification:", ":").strip()
|
| 134 |
-
elif ":" in poet_suggestion:
|
| 135 |
-
pass # Accept simple Poet: Justification format
|
| 136 |
-
else:
|
| 137 |
-
# Fallback for unexpected format
|
| 138 |
-
poet_suggestion = f"Analysis failed: {poet_suggestion[:50]}..."
|
| 139 |
-
|
| 140 |
progress(1.0, desc="Analysis complete!")
|
|
|
|
| 141 |
return poet_suggestion
|
| 142 |
|
| 143 |
# --- UI Layout ---
|
| 144 |
with gr.Blocks(title="The Poetry Workshop", theme=gr.themes.Soft()) as demo:
|
| 145 |
gr.Markdown("# 🖋️ The Poetry Workshop - Collaborative Analyst")
|
| 146 |
gr.Markdown("Generate a poem based on a topic and persona, then use the separate button to analyze the output.")
|
| 147 |
-
|
| 148 |
-
# Removed state variables as they are no longer needed
|
| 149 |
-
|
| 150 |
with gr.Group():
|
| 151 |
with gr.Row(equal_height=True):
|
| 152 |
gr.Markdown("### I want to write a ")
|
|
@@ -176,12 +166,12 @@ with gr.Blocks(title="The Poetry Workshop", theme=gr.themes.Soft()) as demo:
|
|
| 176 |
scale=5
|
| 177 |
)
|
| 178 |
generate_btn = gr.Button("✨ Create Poem Draft", variant="primary", scale=1)
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
# Added Analyze Button
|
| 183 |
analyze_btn = gr.Button("🔍 Analyze This Poem", variant="secondary")
|
| 184 |
-
|
| 185 |
with gr.Row():
|
| 186 |
output_display = gr.Textbox(
|
| 187 |
label="Your Poem",
|
|
@@ -189,7 +179,7 @@ with gr.Blocks(title="The Poetry Workshop", theme=gr.themes.Soft()) as demo:
|
|
| 189 |
interactive=False,
|
| 190 |
placeholder="Your masterpiece will appear here..."
|
| 191 |
)
|
| 192 |
-
|
| 193 |
# New Textbox for the Poet Suggestion
|
| 194 |
poet_suggestion_display = gr.Textbox(
|
| 195 |
label="Literary Analysis: Suggested Poet",
|
|
@@ -197,16 +187,16 @@ with gr.Blocks(title="The Poetry Workshop", theme=gr.themes.Soft()) as demo:
|
|
| 197 |
interactive=False,
|
| 198 |
placeholder="Click 'Analyze This Poem' to run the LLM analysis."
|
| 199 |
)
|
| 200 |
-
|
| 201 |
# --- Event Handling ---
|
| 202 |
-
|
| 203 |
# 1. Initial Generation: Outputs only the poem text
|
| 204 |
generate_btn.click(
|
| 205 |
fn=generate_poem,
|
| 206 |
inputs=[format_dropdown, persona_dropdown, topic_input],
|
| 207 |
outputs=[output_display]
|
| 208 |
)
|
| 209 |
-
|
| 210 |
# 2. Analysis (New Step): Inputs only the poem text
|
| 211 |
analyze_btn.click(
|
| 212 |
fn=analyze_poem,
|
|
|
|
| 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 = 0.7 # Note: min_p = 0.1 is kept as requested in the configuration from the previous prompt
|
|
|
|
| 12 |
|
| 13 |
# --- Model Loading ---
|
| 14 |
llm = None
|
|
|
|
| 49 |
# --- Prompt Construction Helper Function (Simplified) ---
|
| 50 |
def build_poem_prompt(voice_instruction, constraint_instruction, format_type, topic):
|
| 51 |
"""Constructs a simple, direct prompt for initial poem generation."""
|
|
|
|
| 52 |
# Combined, prioritized instruction block for maximum clarity
|
| 53 |
full_instruction = (
|
| 54 |
f"You are a highly disciplined creative writer. {voice_instruction} "
|
| 55 |
f"You must write a {format_type} about '{topic}'.\n"
|
| 56 |
f"STRICT FORMAT RULE: {constraint_instruction}\n"
|
| 57 |
+
f"Your output must contain ONLY the poem, nothing else. Do NOT include a title.\n"
|
|
|
|
| 58 |
)
|
| 59 |
return full_instruction
|
| 60 |
|
|
|
|
| 67 |
return "Error: Model not loaded."
|
| 68 |
if not topic:
|
| 69 |
return "Please enter a topic!"
|
| 70 |
+
|
| 71 |
# --- POEM GENERATION ---
|
| 72 |
progress(0.2, desc=f"Summoning {persona} and drafting poem...")
|
| 73 |
selected_voice = persona_map.get(persona, "You are a helpful assistant.")
|
| 74 |
selected_constraint = format_map.get(format_type, "Write a poem.")
|
| 75 |
|
| 76 |
full_poem_prompt = build_poem_prompt(selected_voice, selected_constraint, format_type, topic)
|
|
|
|
| 77 |
output = llm(
|
| 78 |
prompt=full_poem_prompt,
|
| 79 |
max_tokens=MAX_NEW_TOKENS,
|
| 80 |
temperature=TEMPERATURE,
|
| 81 |
+
# Minimal stop sequences to prevent cutting off the poem prematurely
|
| 82 |
+
stop=["STRICT FORMAT RULE:", "\n\n\n"],
|
| 83 |
echo=False
|
| 84 |
)
|
| 85 |
|
| 86 |
# Clean up output
|
| 87 |
poem_text = output['choices'][0]['text'].strip()
|
| 88 |
+
|
| 89 |
+
# Simple post-processing to clean up any residual instruction text if the model echoes it
|
| 90 |
+
# We are trusting the instruction "Your output must contain ONLY the poem, nothing else."
|
| 91 |
|
| 92 |
progress(1.0, desc="Poem draft complete!")
|
| 93 |
# NOTE: Only returns the poem output
|
|
|
|
| 99 |
return "Error: Model not loaded."
|
| 100 |
if not poem_text or poem_text.startswith("Error:") or poem_text.startswith("Please enter"):
|
| 101 |
return "Please generate a valid poem first!"
|
| 102 |
+
|
| 103 |
progress(0, desc="Analyzing style for literary match...")
|
| 104 |
time.sleep(0.2)
|
| 105 |
+
|
| 106 |
# Secondary prompt for the analysis task - MINIMALIST QUESTION
|
| 107 |
+
# The prompt is simplified to remove conversational fluff and simply present the poem for analysis.
|
| 108 |
poet_prompt = (
|
| 109 |
f"You are a literary analyst. Your task is to analyze the POEM below and identify the single most appropriate "
|
| 110 |
f"REAL, historical poet whose style and themes match the poem. Do NOT suggest fictional characters.\n"
|
| 111 |
+
f"STRICT OUTPUT FORMAT: Format your answer ONLY as: Poet Name: [Name] - Justification: [Reason].\n\n"
|
| 112 |
+
f"POEM:\n{poem_text}\n"
|
|
|
|
| 113 |
)
|
| 114 |
|
| 115 |
output_poet = llm(
|
| 116 |
prompt=poet_prompt,
|
| 117 |
max_tokens=80, # Keep this response short
|
| 118 |
temperature=0.4,
|
| 119 |
+
# Minimal stop sequences for clean output
|
| 120 |
+
stop=["POEM:", "STRICT OUTPUT FORMAT:", "\n\n", "\n"],
|
| 121 |
echo=False
|
| 122 |
)
|
| 123 |
|
| 124 |
# Clean up the output using simple string manipulation
|
| 125 |
poet_suggestion = output_poet['choices'][0]['text'].strip()
|
| 126 |
|
| 127 |
+
# Clean up any potential instruction echo or partial output
|
| 128 |
+
if poet_suggestion.startswith("STRICT OUTPUT FORMAT:"):
|
| 129 |
+
poet_suggestion = poet_suggestion[len("STRICT OUTPUT FORMAT:"):].strip()
|
| 130 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
progress(1.0, desc="Analysis complete!")
|
| 132 |
+
|
| 133 |
return poet_suggestion
|
| 134 |
|
| 135 |
# --- UI Layout ---
|
| 136 |
with gr.Blocks(title="The Poetry Workshop", theme=gr.themes.Soft()) as demo:
|
| 137 |
gr.Markdown("# 🖋️ The Poetry Workshop - Collaborative Analyst")
|
| 138 |
gr.Markdown("Generate a poem based on a topic and persona, then use the separate button to analyze the output.")
|
| 139 |
+
|
|
|
|
|
|
|
| 140 |
with gr.Group():
|
| 141 |
with gr.Row(equal_height=True):
|
| 142 |
gr.Markdown("### I want to write a ")
|
|
|
|
| 166 |
scale=5
|
| 167 |
)
|
| 168 |
generate_btn = gr.Button("✨ Create Poem Draft", variant="primary", scale=1)
|
| 169 |
+
|
| 170 |
+
gr.Markdown("---")
|
| 171 |
+
|
| 172 |
# Added Analyze Button
|
| 173 |
analyze_btn = gr.Button("🔍 Analyze This Poem", variant="secondary")
|
| 174 |
+
|
| 175 |
with gr.Row():
|
| 176 |
output_display = gr.Textbox(
|
| 177 |
label="Your Poem",
|
|
|
|
| 179 |
interactive=False,
|
| 180 |
placeholder="Your masterpiece will appear here..."
|
| 181 |
)
|
| 182 |
+
|
| 183 |
# New Textbox for the Poet Suggestion
|
| 184 |
poet_suggestion_display = gr.Textbox(
|
| 185 |
label="Literary Analysis: Suggested Poet",
|
|
|
|
| 187 |
interactive=False,
|
| 188 |
placeholder="Click 'Analyze This Poem' to run the LLM analysis."
|
| 189 |
)
|
| 190 |
+
|
| 191 |
# --- Event Handling ---
|
| 192 |
+
|
| 193 |
# 1. Initial Generation: Outputs only the poem text
|
| 194 |
generate_btn.click(
|
| 195 |
fn=generate_poem,
|
| 196 |
inputs=[format_dropdown, persona_dropdown, topic_input],
|
| 197 |
outputs=[output_display]
|
| 198 |
)
|
| 199 |
+
|
| 200 |
# 2. Analysis (New Step): Inputs only the poem text
|
| 201 |
analyze_btn.click(
|
| 202 |
fn=analyze_poem,
|