Ozgur Unlu
commited on
Commit
·
b4eab22
1
Parent(s):
a8e55be
made fixes
Browse files
app.py
CHANGED
@@ -6,8 +6,138 @@ from datetime import datetime, timedelta
|
|
6 |
import requests
|
7 |
from bs4 import BeautifulSoup
|
8 |
|
9 |
-
#
|
10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
11 |
|
12 |
def create_interface():
|
13 |
print("Loading models...")
|
@@ -63,77 +193,89 @@ def create_interface():
|
|
63 |
return f"An error occurred: {str(e)}"
|
64 |
|
65 |
# Create input components
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
# Output component
|
79 |
-
output = gr.Textbox(label="Generated Content", lines=10)
|
80 |
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
⏳ Note: First generation might take 3-5 minutes due to model loading.
|
97 |
-
Subsequent generations will be faster!""",
|
98 |
-
theme="default",
|
99 |
-
examples=[
|
100 |
-
[
|
101 |
-
"EcoBottle",
|
102 |
-
"Sustainable water bottle made from recycled ocean plastic",
|
103 |
-
"Environmentally conscious young professionals",
|
104 |
-
"100% recycled materials, Insulated design, Leak-proof",
|
105 |
-
"Helps clean oceans, Keeps drinks cold for 24 hours",
|
106 |
-
"Twitter",
|
107 |
-
"professional"
|
108 |
-
]
|
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 |
-
return
|
135 |
|
136 |
# Launch the app
|
137 |
if __name__ == "__main__":
|
138 |
-
|
139 |
-
|
|
|
6 |
import requests
|
7 |
from bs4 import BeautifulSoup
|
8 |
|
9 |
+
# Download required NLTK data
|
10 |
+
try:
|
11 |
+
nltk.data.find('tokenizers/punkt')
|
12 |
+
except LookupError:
|
13 |
+
nltk.download('punkt')
|
14 |
+
|
15 |
+
# Global variables to cache models
|
16 |
+
CACHED_MODELS = {}
|
17 |
+
|
18 |
+
# Initialize models and tokenizers
|
19 |
+
def load_models():
|
20 |
+
global CACHED_MODELS
|
21 |
+
|
22 |
+
if CACHED_MODELS:
|
23 |
+
return (
|
24 |
+
CACHED_MODELS['generator_tokenizer'],
|
25 |
+
CACHED_MODELS['generator'],
|
26 |
+
CACHED_MODELS['sentiment_analyzer'],
|
27 |
+
CACHED_MODELS['content_checker']
|
28 |
+
)
|
29 |
+
|
30 |
+
try:
|
31 |
+
# Use a smaller text generation model
|
32 |
+
generator_model = "distilgpt2" # Smaller than opt-350m
|
33 |
+
generator_tokenizer = AutoTokenizer.from_pretrained(generator_model)
|
34 |
+
generator = AutoModelForCausalLM.from_pretrained(generator_model)
|
35 |
+
|
36 |
+
# Sentiment analysis
|
37 |
+
sentiment_analyzer = pipeline(
|
38 |
+
"sentiment-analysis",
|
39 |
+
model="finiteautomata/bertweet-base-sentiment-analysis"
|
40 |
+
)
|
41 |
+
|
42 |
+
# Content safety checker
|
43 |
+
content_checker = pipeline(
|
44 |
+
"text-classification",
|
45 |
+
model="facebook/roberta-hate-speech-dynabench-r4-target"
|
46 |
+
)
|
47 |
+
|
48 |
+
# Cache the models
|
49 |
+
CACHED_MODELS['generator_tokenizer'] = generator_tokenizer
|
50 |
+
CACHED_MODELS['generator'] = generator
|
51 |
+
CACHED_MODELS['sentiment_analyzer'] = sentiment_analyzer
|
52 |
+
CACHED_MODELS['content_checker'] = content_checker
|
53 |
+
|
54 |
+
return generator_tokenizer, generator, sentiment_analyzer, content_checker
|
55 |
+
except Exception as e:
|
56 |
+
print(f"Error loading models: {str(e)}")
|
57 |
+
raise
|
58 |
+
|
59 |
+
def generate_content(
|
60 |
+
product_name,
|
61 |
+
product_description,
|
62 |
+
target_audience,
|
63 |
+
key_features,
|
64 |
+
unique_benefits,
|
65 |
+
platform,
|
66 |
+
tone,
|
67 |
+
generator_tokenizer,
|
68 |
+
generator,
|
69 |
+
sentiment_analyzer,
|
70 |
+
content_checker
|
71 |
+
):
|
72 |
+
char_limit = 280 if platform == "Twitter" else 500
|
73 |
+
|
74 |
+
prompt = f"""Write a {platform} post:
|
75 |
+
Product: {product_name}
|
76 |
+
Description: {product_description}
|
77 |
+
Target: {target_audience}
|
78 |
+
Features: {key_features}
|
79 |
+
Benefits: {unique_benefits}
|
80 |
+
Tone: {tone}
|
81 |
+
|
82 |
+
Write a compelling {platform} post in {tone} tone that highlights the product benefits:"""
|
83 |
+
|
84 |
+
try:
|
85 |
+
# Generate initial content
|
86 |
+
inputs = generator_tokenizer(prompt, return_tensors="pt", max_length=256, truncation=True)
|
87 |
+
outputs = generator.generate(
|
88 |
+
inputs["input_ids"],
|
89 |
+
max_length=char_limit,
|
90 |
+
num_return_sequences=2, # Reduced from 3 to 2 for speed
|
91 |
+
temperature=0.7,
|
92 |
+
top_p=0.9,
|
93 |
+
do_sample=True,
|
94 |
+
pad_token_id=generator_tokenizer.eos_token_id
|
95 |
+
)
|
96 |
+
|
97 |
+
generated_texts = [generator_tokenizer.decode(output, skip_special_tokens=True) for output in outputs]
|
98 |
+
|
99 |
+
# Filter and analyze content
|
100 |
+
filtered_content = []
|
101 |
+
for text in generated_texts:
|
102 |
+
# Clean up text
|
103 |
+
text = text.replace(prompt, "").strip()
|
104 |
+
if len(text) < 10: # Skip very short texts
|
105 |
+
continue
|
106 |
+
|
107 |
+
# Truncate to character limit if needed
|
108 |
+
text = text[:char_limit]
|
109 |
+
|
110 |
+
# Check sentiment
|
111 |
+
try:
|
112 |
+
sentiment = sentiment_analyzer(text)[0]
|
113 |
+
except:
|
114 |
+
sentiment = {'label': 'unknown', 'score': 0.0}
|
115 |
+
|
116 |
+
# Check content safety
|
117 |
+
try:
|
118 |
+
safety_check = content_checker(text)[0]
|
119 |
+
except:
|
120 |
+
safety_check = {'label': 'unknown', 'score': 0.0}
|
121 |
+
|
122 |
+
# More lenient filtering
|
123 |
+
filtered_content.append({
|
124 |
+
'text': text,
|
125 |
+
'sentiment': sentiment['label'],
|
126 |
+
'safety_score': f"{float(safety_check.get('score', 0)):.2f}"
|
127 |
+
})
|
128 |
+
|
129 |
+
return filtered_content if filtered_content else [{
|
130 |
+
'text': generated_texts[0].replace(prompt, "").strip()[:char_limit],
|
131 |
+
'sentiment': 'not analyzed',
|
132 |
+
'safety_score': 'not analyzed'
|
133 |
+
}]
|
134 |
+
except Exception as e:
|
135 |
+
print(f"Error in content generation: {str(e)}")
|
136 |
+
return [{
|
137 |
+
'text': 'Error generating content. Please try again.',
|
138 |
+
'sentiment': 'error',
|
139 |
+
'safety_score': 'error'
|
140 |
+
}]
|
141 |
|
142 |
def create_interface():
|
143 |
print("Loading models...")
|
|
|
193 |
return f"An error occurred: {str(e)}"
|
194 |
|
195 |
# Create input components
|
196 |
+
with gr.Blocks() as demo:
|
197 |
+
gr.Markdown("# Ethimar - AI Marketing Content Generator")
|
198 |
+
gr.Markdown("Generate ethical marketing content with AI-powered insights.\n⏳ Note: First generation might take 3-5 minutes due to model loading. Subsequent generations will be faster!")
|
199 |
+
|
200 |
+
with gr.Row():
|
201 |
+
fill_button = gr.Button(
|
202 |
+
"Fill the form with sample data",
|
203 |
+
variant="primary",
|
204 |
+
scale=1,
|
205 |
+
size="sm"
|
206 |
+
)
|
|
|
|
|
|
|
207 |
|
208 |
+
with gr.Column():
|
209 |
+
product_name = gr.Textbox(label="Product Name", placeholder="Enter product name")
|
210 |
+
product_description = gr.Textbox(label="Product Description", lines=3, placeholder="Brief description of your product")
|
211 |
+
target_audience = gr.Textbox(label="Target Audience", placeholder="Who is this product for?")
|
212 |
+
key_features = gr.Textbox(label="Key Features", lines=2, placeholder="Main features of your product")
|
213 |
+
unique_benefits = gr.Textbox(label="Unique Benefits", lines=2, placeholder="What makes your product special?")
|
214 |
+
platform = gr.Radio(
|
215 |
+
choices=["Twitter", "Instagram"],
|
216 |
+
label="Platform",
|
217 |
+
value="Twitter"
|
218 |
+
)
|
219 |
+
tone = gr.Textbox(label="Tone", placeholder="e.g., professional, casual, friendly")
|
220 |
+
|
221 |
+
submit_button = gr.Button("Generate Content", variant="primary")
|
222 |
+
output = gr.Textbox(label="Generated Content", lines=10)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
223 |
|
224 |
+
# Connect the buttons to functions
|
225 |
+
fill_button.click(
|
226 |
+
fn=fill_sample_data,
|
227 |
+
outputs=[
|
228 |
+
product_name,
|
229 |
+
product_description,
|
230 |
+
target_audience,
|
231 |
+
key_features,
|
232 |
+
unique_benefits,
|
233 |
+
platform,
|
234 |
+
tone
|
235 |
+
]
|
236 |
+
)
|
237 |
+
|
238 |
+
submit_button.click(
|
239 |
+
fn=process_input,
|
240 |
+
inputs=[
|
241 |
+
product_name,
|
242 |
+
product_description,
|
243 |
+
target_audience,
|
244 |
+
key_features,
|
245 |
+
unique_benefits,
|
246 |
+
platform,
|
247 |
+
tone
|
248 |
+
],
|
249 |
+
outputs=output
|
250 |
+
)
|
251 |
+
|
252 |
+
# Add examples
|
253 |
+
gr.Examples(
|
254 |
+
examples=[
|
255 |
+
[
|
256 |
+
"EcoBottle",
|
257 |
+
"Sustainable water bottle made from recycled ocean plastic",
|
258 |
+
"Environmentally conscious young professionals",
|
259 |
+
"100% recycled materials, Insulated design, Leak-proof",
|
260 |
+
"Helps clean oceans, Keeps drinks cold for 24 hours",
|
261 |
+
"Twitter",
|
262 |
+
"professional"
|
263 |
+
]
|
264 |
+
],
|
265 |
+
inputs=[
|
266 |
+
product_name,
|
267 |
+
product_description,
|
268 |
+
target_audience,
|
269 |
+
key_features,
|
270 |
+
unique_benefits,
|
271 |
+
platform,
|
272 |
+
tone
|
273 |
+
]
|
274 |
+
)
|
275 |
|
276 |
+
return demo
|
277 |
|
278 |
# Launch the app
|
279 |
if __name__ == "__main__":
|
280 |
+
demo = create_interface()
|
281 |
+
demo.launch()
|