azeus
commited on
Commit
Β·
dab360e
1
Parent(s):
3599259
freeform haiku
Browse files
app.py
CHANGED
@@ -1,138 +1,130 @@
|
|
1 |
import streamlit as st
|
2 |
from transformers import pipeline
|
3 |
-
import nltk
|
4 |
-
from nltk.corpus import cmudict
|
5 |
import random
|
6 |
-
import torch
|
7 |
|
8 |
-
# Download required NLTK data
|
9 |
-
nltk.download('cmudict')
|
10 |
-
d = cmudict.dict()
|
11 |
|
12 |
-
|
13 |
-
class HaikuGenerator:
|
14 |
def __init__(self):
|
15 |
-
# Initialize different language models
|
16 |
self.models = {
|
17 |
-
"BERT": pipeline('fill-mask', model='bert-base-uncased'),
|
18 |
-
"RoBERTa": pipeline('fill-mask', model='roberta-base'),
|
19 |
"GPT2": pipeline('text-generation', model='gpt2'),
|
20 |
-
"
|
|
|
21 |
}
|
22 |
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
for
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
lines.append(' '.join(current_line))
|
88 |
|
89 |
return lines
|
90 |
|
91 |
|
92 |
def main():
|
93 |
-
st.title("π Character Haiku Generator")
|
94 |
-
st.write("
|
95 |
|
96 |
# Initialize generator
|
97 |
-
generator =
|
98 |
|
99 |
# Input fields
|
100 |
-
|
|
|
|
|
101 |
|
102 |
-
# Four traits/characteristics
|
103 |
-
cols = st.columns(4)
|
104 |
traits = []
|
|
|
105 |
for i, col in enumerate(cols):
|
106 |
-
trait = col.text_input(f"Trait
|
107 |
if trait:
|
108 |
traits.append(trait)
|
109 |
|
110 |
-
#
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
|
|
136 |
|
137 |
|
138 |
if __name__ == "__main__":
|
|
|
1 |
import streamlit as st
|
2 |
from transformers import pipeline
|
|
|
|
|
3 |
import random
|
|
|
4 |
|
|
|
|
|
|
|
5 |
|
6 |
+
class FreeFormHaikuGenerator:
|
|
|
7 |
def __init__(self):
|
|
|
8 |
self.models = {
|
|
|
|
|
9 |
"GPT2": pipeline('text-generation', model='gpt2'),
|
10 |
+
"BERT": pipeline('fill-mask', model='bert-base-uncased'),
|
11 |
+
"RoBERTa": pipeline('fill-mask', model='roberta-base')
|
12 |
}
|
13 |
|
14 |
+
self.style_prompts = {
|
15 |
+
"Minimalist": "Write a short profound observation about",
|
16 |
+
"Emotional": "Express deep feelings about",
|
17 |
+
"Nature": "Describe the natural essence of",
|
18 |
+
"Urban": "Capture a city moment with",
|
19 |
+
"Surreal": "Create a dreamlike scene with"
|
20 |
+
}
|
21 |
+
|
22 |
+
def generate_associations(self, word, model_name):
|
23 |
+
"""Generate associated words and phrases using different models."""
|
24 |
+
if model_name == "GPT2":
|
25 |
+
prompt = f"{word} makes me think of"
|
26 |
+
response = self.models[model_name](prompt,
|
27 |
+
max_length=20,
|
28 |
+
num_return_sequences=3,
|
29 |
+
temperature=0.9)
|
30 |
+
return [r['generated_text'].split()[-1] for r in response]
|
31 |
+
|
32 |
+
else: # BERT or RoBERTa
|
33 |
+
mask_token = "[MASK]" if model_name == "BERT" else "<mask>"
|
34 |
+
prompts = [
|
35 |
+
f"The {word} is like {mask_token}",
|
36 |
+
f"{word} reminds me of {mask_token}",
|
37 |
+
f"{word} feels {mask_token}"
|
38 |
+
]
|
39 |
+
associations = []
|
40 |
+
for prompt in prompts:
|
41 |
+
result = self.models[model_name](prompt)
|
42 |
+
associations.extend([r['token_str'] for r in result[:2]])
|
43 |
+
return associations
|
44 |
+
|
45 |
+
def create_freeform_haiku(self, name, traits, model_name, style):
|
46 |
+
"""Create a free-form haiku based on character traits and selected style."""
|
47 |
+
# Generate word associations for each trait
|
48 |
+
word_pool = []
|
49 |
+
for trait in [name] + traits:
|
50 |
+
word_pool.extend(self.generate_associations(trait, model_name))
|
51 |
+
|
52 |
+
# Create base prompt for the style
|
53 |
+
base_prompt = f"{self.style_prompts[style]} {name} who is {', '.join(traits)}"
|
54 |
+
|
55 |
+
if model_name == "GPT2":
|
56 |
+
# Generate three short phrases for our haiku
|
57 |
+
lines = []
|
58 |
+
for i in range(3):
|
59 |
+
prompt = f"{base_prompt}. Line {i + 1}:"
|
60 |
+
response = self.models[model_name](prompt,
|
61 |
+
max_length=30,
|
62 |
+
temperature=0.9,
|
63 |
+
num_return_sequences=1)
|
64 |
+
# Extract a meaningful phrase from the response
|
65 |
+
generated_text = response[0]['generated_text'].split('\n')[0]
|
66 |
+
clean_line = ' '.join(generated_text.split()[-4:]) # Take last 4 words
|
67 |
+
lines.append(clean_line)
|
68 |
+
else:
|
69 |
+
# For BERT/RoBERTa, construct lines using masked predictions
|
70 |
+
lines = []
|
71 |
+
random.shuffle(word_pool)
|
72 |
+
for i in range(3):
|
73 |
+
if i == 0:
|
74 |
+
line = f"{name} {random.choice(word_pool)}"
|
75 |
+
else:
|
76 |
+
line = f"{random.choice(word_pool)} {random.choice(word_pool)}"
|
77 |
+
lines.append(line.strip())
|
|
|
78 |
|
79 |
return lines
|
80 |
|
81 |
|
82 |
def main():
|
83 |
+
st.title("π Free-Form Character Haiku Generator")
|
84 |
+
st.write("Breaking traditional rules to create unique, AI-generated haiku!")
|
85 |
|
86 |
# Initialize generator
|
87 |
+
generator = FreeFormHaikuGenerator()
|
88 |
|
89 |
# Input fields
|
90 |
+
col1, col2 = st.columns([1, 2])
|
91 |
+
with col1:
|
92 |
+
name = st.text_input("Character Name")
|
93 |
|
|
|
|
|
94 |
traits = []
|
95 |
+
cols = st.columns(4)
|
96 |
for i, col in enumerate(cols):
|
97 |
+
trait = col.text_input(f"{'Trait' if i < 2 else 'Hobby' if i == 2 else 'Physical'} {i + 1}")
|
98 |
if trait:
|
99 |
traits.append(trait)
|
100 |
|
101 |
+
# Style and model selection
|
102 |
+
col1, col2 = st.columns(2)
|
103 |
+
with col1:
|
104 |
+
style = st.selectbox("Choose Style",
|
105 |
+
list(generator.style_prompts.keys()))
|
106 |
+
with col2:
|
107 |
+
model = st.selectbox("Choose AI Model",
|
108 |
+
["GPT2", "BERT", "RoBERTa"])
|
109 |
+
|
110 |
+
if name and len(traits) == 4 and st.button("Generate Free-Form Haiku"):
|
111 |
+
st.subheader("Your Generated Haiku:")
|
112 |
+
|
113 |
+
with st.spinner(f"Crafting a {style} haiku using {model}..."):
|
114 |
+
haiku_lines = generator.create_freeform_haiku(name, traits, model, style)
|
115 |
+
|
116 |
+
# Display haiku with styling
|
117 |
+
st.markdown("---")
|
118 |
+
for line in haiku_lines:
|
119 |
+
st.markdown(f"*{line}*")
|
120 |
+
st.markdown("---")
|
121 |
+
|
122 |
+
# Add some context
|
123 |
+
st.caption(f"Style: {style} | Model: {model}")
|
124 |
+
|
125 |
+
# Option to regenerate
|
126 |
+
if st.button("Generate Another Version"):
|
127 |
+
st.experimental_rerun()
|
128 |
|
129 |
|
130 |
if __name__ == "__main__":
|