azeus commited on
Commit
dab360e
Β·
1 Parent(s): 3599259

freeform haiku

Browse files
Files changed (1) hide show
  1. app.py +102 -110
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
- "DistilBERT": pipeline('fill-mask', model='distilbert-base-uncased')
 
21
  }
22
 
23
- def count_syllables(self, word):
24
- """Count syllables in a word using CMU dictionary."""
25
- try:
26
- return len([x for x in d[word.lower()][0] if x[-1].isdigit()])
27
- except KeyError:
28
- return len(''.join(c for c in word if c in 'aeiouAEIOU'))
29
-
30
- def get_related_words(self, word, model_name):
31
- """Get related words using different models."""
32
- if model_name in ["BERT", "RoBERTa", "DistilBERT"]:
33
- if model_name == "RoBERTa":
34
- masked_text = f"The {word} is <mask>."
35
- else:
36
- masked_text = f"The {word} is [MASK]."
37
- predictions = self.models[model_name](masked_text)
38
- return [pred['token_str'].strip() for pred in predictions]
39
- else: # GPT2
40
- prompt = f"The word {word} reminds me of"
41
- predictions = self.models[model_name](prompt, max_length=20, num_return_sequences=5)
42
- words = []
43
- for pred in predictions:
44
- text = pred['generated_text'].split()
45
- if len(text) > 6: # Get the first new word after the prompt
46
- words.append(text[6])
47
- return words
48
-
49
- def create_themed_haiku(self, character_name, traits, model_name):
50
- """Generate a themed haiku about a character using specified model."""
51
- syllable_targets = [5, 7, 5]
52
- lines = []
53
-
54
- # Create word pool from character traits and related words
55
- word_pool = set(traits)
56
- word_pool.add(character_name)
57
-
58
- for word in traits:
59
- related = self.get_related_words(word, model_name)
60
- word_pool.update(related)
61
-
62
- # Add character-specific words based on traits
63
- for trait in traits:
64
- themed_words = self.get_related_words(trait, model_name)
65
- word_pool.update(themed_words)
66
-
67
- # Generate each line ensuring character name appears
68
- for i, target in enumerate(syllable_targets):
69
- current_line = []
70
- current_syllables = 0
71
-
72
- # Ensure character name appears in one of the lines (preferably first)
73
- if i == 0 and self.count_syllables(character_name) <= target:
74
- current_line.append(character_name)
75
- current_syllables += self.count_syllables(character_name)
76
-
77
- while current_syllables < target:
78
- available_words = [w for w in word_pool
79
- if current_syllables + self.count_syllables(w) <= target]
80
- if not available_words:
81
- break
82
-
83
- word = random.choice(available_words)
84
- current_line.append(word)
85
- current_syllables += self.count_syllables(word)
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("Generate unique haikus about a character using different AI models!")
95
 
96
  # Initialize generator
97
- generator = HaikuGenerator()
98
 
99
  # Input fields
100
- character_name = st.text_input("Character Name:")
 
 
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/Characteristic {i + 1}")
107
  if trait:
108
  traits.append(trait)
109
 
110
- # Model selection
111
- model_options = ["BERT", "RoBERTa", "DistilBERT", "GPT2"]
112
- selected_models = st.multiselect(
113
- "Select AI Models to Generate Haikus",
114
- model_options,
115
- default=["BERT"]
116
- )
117
-
118
- if character_name and len(traits) == 4 and st.button("Generate Haikus"):
119
- st.subheader("Your Generated Haikus:")
120
-
121
- for model in selected_models:
122
- with st.expander(f"🎯 {model} Generated Haiku"):
123
- with st.spinner(f"Crafting haiku using {model}..."):
124
- haiku_lines = generator.create_themed_haiku(character_name, traits, model)
125
-
126
- # Display haiku with styling
127
- for line in haiku_lines:
128
- st.write(line)
129
-
130
- # Display syllable count
131
- st.caption("Syllable count verification:")
132
- for i, line in enumerate(haiku_lines):
133
- syllables = sum(generator.count_syllables(word)
134
- for word in line.split())
135
- st.caption(f"Line {i + 1}: {syllables} syllables")
 
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__":