Ozgur Unlu commited on
Commit
d4b3687
·
1 Parent(s): 69cb436

more fixes, disabled text generator and using templates now

Browse files
Files changed (1) hide show
  1. app.py +70 -62
app.py CHANGED
@@ -71,55 +71,72 @@ def generate_content(
71
  ):
72
  char_limit = 280 if platform == "Twitter" else 500
73
 
74
- # Simpler, more direct prompt
75
- prompt = f"""Marketing post for {platform}:
76
-
77
- {product_name} helps {target_audience} by {unique_benefits}. {product_description}. Features include {key_features}.
78
-
79
- Marketing post in {tone} tone:
80
- """
81
 
82
- try:
83
- # Generate content with stricter parameters
84
- inputs = generator_tokenizer(prompt, return_tensors="pt", max_length=128, truncation=True)
85
- outputs = generator.generate(
86
- inputs["input_ids"],
87
- max_length=char_limit // 2, # Keep it concise
88
- num_return_sequences=2,
89
- temperature=0.9,
90
- top_p=0.85,
91
- do_sample=True,
92
- pad_token_id=generator_tokenizer.eos_token_id,
93
- no_repeat_ngram_size=2,
94
- min_length=30,
95
- repetition_penalty=1.2
96
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
 
98
- generated_texts = [generator_tokenizer.decode(output, skip_special_tokens=True) for output in outputs]
 
 
99
 
100
- # Process and clean the generated content
 
 
 
 
 
 
 
 
 
 
 
 
101
  filtered_content = []
102
- for text in generated_texts:
103
- # Extract only the part after "Marketing post in {tone} tone:"
104
- try:
105
- post = text.split("Marketing post in")[-1].split("tone:")[-1].strip()
106
- except:
107
- post = text
108
-
109
- # Basic cleaning
110
- post = ' '.join(post.split()) # Remove extra whitespace
111
-
112
- # Skip if the post is too short or contains prompt artifacts
113
- if len(post) < 20 or "Marketing post" in post or "tone:" in post:
114
- continue
115
-
116
- # Ensure it starts with product name if it's not already included
117
- if product_name not in post:
118
- post = f"{product_name}: {post}"
119
-
120
- # Ensure there's a call to action
121
- if "learn more" not in post.lower() and len(post) + 15 <= char_limit:
122
- post += " Learn more today!"
123
 
124
  # Check sentiment and safety
125
  try:
@@ -127,7 +144,7 @@ Marketing post in {tone} tone:
127
  safety_check = content_checker(post)[0]
128
 
129
  filtered_content.append({
130
- 'text': post[:char_limit],
131
  'sentiment': sentiment['label'],
132
  'safety_score': f"{float(safety_check.get('score', 0)):.2f}"
133
  })
@@ -135,25 +152,16 @@ Marketing post in {tone} tone:
135
  print(f"Error in content analysis: {str(e)}")
136
  continue
137
 
138
- # If no valid content was generated, use a structured fallback
139
- if not filtered_content:
140
- benefit = unique_benefits.split(',')[0].strip()
141
- feature = key_features.split(',')[0].strip()
142
-
143
- fallback_post = f"{product_name}: {product_description} {benefit}. Featuring {feature}. Perfect for {target_audience}. Learn more today!"
144
-
145
- filtered_content.append({
146
- 'text': fallback_post[:char_limit],
147
- 'sentiment': 'positive',
148
- 'safety_score': '1.00'
149
- })
150
-
151
- return filtered_content
152
-
153
  except Exception as e:
154
  print(f"Error in content generation: {str(e)}")
155
  return [{
156
- 'text': f"{product_name}: {product_description[:100]}... Learn more today!",
157
  'sentiment': 'neutral',
158
  'safety_score': '1.00'
159
  }]
 
71
  ):
72
  char_limit = 280 if platform == "Twitter" else 500
73
 
74
+ # Split features and benefits into lists
75
+ features = [f.strip() for f in key_features.split(',')]
76
+ benefits = [b.strip() for b in unique_benefits.split(',')]
 
 
 
 
77
 
78
+ # Create marketing message templates based on tone
79
+ intro_phrases = {
80
+ 'professional': [
81
+ f"Introducing {product_name}:",
82
+ f"Discover {product_name}:",
83
+ f"Meet {product_name}:",
84
+ ],
85
+ 'casual': [
86
+ f"Check out {product_name}!",
87
+ f"Say hello to {product_name}!",
88
+ f"Get ready for {product_name}!",
89
+ ],
90
+ 'friendly': [
91
+ f"You'll love {product_name}!",
92
+ f"Experience {product_name}!",
93
+ f"We're excited to present {product_name}!",
94
+ ]
95
+ }
96
+
97
+ # Use professional tone as default if tone not found
98
+ selected_tone = tone.lower() if tone.lower() in intro_phrases else 'professional'
99
+
100
+ import random
101
+
102
+ def create_post():
103
+ # Start with a random intro
104
+ post = random.choice(intro_phrases[selected_tone])
105
+
106
+ # Add main description
107
+ post += f" {product_description}"
108
+
109
+ # Add a key feature and benefit
110
+ feature = random.choice(features)
111
+ benefit = random.choice(benefits)
112
+
113
+ if len(post) + len(feature) + len(benefit) + 10 < char_limit:
114
+ post += f" Featuring {feature}."
115
+ post += f" {benefit}."
116
 
117
+ # Add target audience if space allows
118
+ if len(post) + len(target_audience) + 15 < char_limit:
119
+ post += f" Perfect for {target_audience}."
120
 
121
+ # Add call to action
122
+ if platform == "Twitter":
123
+ if len(post) + 30 < char_limit:
124
+ post += " Learn more at our website!"
125
+ else: # Instagram
126
+ if len(post) + 20 < char_limit:
127
+ post += f"\n\n#{product_name.replace(' ', '')}"
128
+
129
+ return post.strip()
130
+
131
+ try:
132
+ # Generate multiple versions
133
+ posts = [create_post() for _ in range(2)]
134
  filtered_content = []
135
+
136
+ for post in posts:
137
+ # Verify length
138
+ if len(post) > char_limit:
139
+ post = post[:char_limit-3] + "..."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
 
141
  # Check sentiment and safety
142
  try:
 
144
  safety_check = content_checker(post)[0]
145
 
146
  filtered_content.append({
147
+ 'text': post,
148
  'sentiment': sentiment['label'],
149
  'safety_score': f"{float(safety_check.get('score', 0)):.2f}"
150
  })
 
152
  print(f"Error in content analysis: {str(e)}")
153
  continue
154
 
155
+ return filtered_content if filtered_content else [{
156
+ 'text': create_post(),
157
+ 'sentiment': 'positive',
158
+ 'safety_score': '1.00'
159
+ }]
160
+
 
 
 
 
 
 
 
 
 
161
  except Exception as e:
162
  print(f"Error in content generation: {str(e)}")
163
  return [{
164
+ 'text': f"Introducing {product_name}: {product_description[:100]}... Learn more!",
165
  'sentiment': 'neutral',
166
  'safety_score': '1.00'
167
  }]