jsakshi commited on
Commit
3d3e23c
·
verified ·
1 Parent(s): 751285d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +110 -76
app.py CHANGED
@@ -167,117 +167,151 @@ if __name__ == "__main__":
167
  import gradio as gr
168
  import os
169
  import time
170
- import tempfile
171
- import zipfile
172
  import requests
173
  import re
174
- from pathlib import Path
175
- from PIL import Image
176
- from io import BytesIO
177
  from dotenv import load_dotenv
 
178
 
179
- # Load environment variables
180
  load_dotenv()
181
 
182
- class MultiAIBlogger:
183
  def __init__(self):
184
  self.hf_token = os.getenv("HF_TOKEN")
 
185
  self.headers = {"Authorization": f"Bearer {self.hf_token}"}
 
 
 
 
186
 
187
- # Configure models
188
- self.text_url = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.2"
189
- self.image_url = "https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-xl-base-1.0"
190
 
191
- def generate_blog(self, topic):
192
- # Generate text content
193
- text_prompt = f"""Create a comprehensive blog post about {topic} including:
194
- - SEO-optimized title
195
- - 3-5 sections with subtitles
196
- - 2-4 image placeholders [IMAGE:description]
197
- - Bullet points and statistics
198
- - Conclusion with call-to-action
199
- Use markdown formatting"""
200
 
201
- text_response = requests.post(
202
- self.text_url,
 
 
 
203
  headers=self.headers,
204
- json={"inputs": text_prompt, "parameters": {"max_length": 2000}}
 
 
 
205
  )
 
 
 
 
 
206
 
207
- if text_response.status_code != 200:
208
- return f"Text generation failed: {text_response.text}", None
209
-
210
- raw_content = text_response.json()[0]['generated_text']
211
-
212
- # Generate images
213
- image_descriptions = re.findall(r'\[IMAGE:(.*?)\]', raw_content)
214
- images = {}
215
- temp_dir = tempfile.mkdtemp()
216
-
217
- for idx, desc in enumerate(image_descriptions):
218
- img_prompt = f"Blog image: {desc}, digital art, 8k resolution, trending on artstation"
219
- img_response = requests.post(
220
- self.image_url,
221
  headers=self.headers,
222
- json={"inputs": img_prompt}
 
 
 
 
 
 
 
223
  )
 
 
224
 
225
- if img_response.status_code == 200:
226
- image = Image.open(BytesIO(img_response.content))
227
- img_path = Path(temp_dir) / f"image_{idx+1}.png"
228
- image.save(img_path)
229
- images[desc] = str(img_path)
230
- raw_content = raw_content.replace(f"[IMAGE:{desc}]", f"![{desc}](image_{idx+1}.png)")
231
- time.sleep(1) # Rate limit protection
232
 
233
- # Create zip package
234
- zip_path = self.create_package(raw_content, temp_dir)
235
- return raw_content, zip_path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
236
 
237
- def create_package(self, content, temp_dir):
238
- # Save markdown
239
- md_path = Path(temp_dir) / "blog.md"
240
- with open(md_path, "w") as f:
241
- f.write(content)
242
-
243
- # Create zip file
244
- zip_path = "blog_package.zip"
245
- with zipfile.ZipFile(zip_path, "w") as zipf:
246
- for file in Path(temp_dir).iterdir():
247
- zipf.write(file, file.name)
248
-
249
- return zip_path
250
 
251
- # Initialize blogger
252
- blogger = MultiAIBlogger()
253
 
254
- # Gradio interface
255
  with gr.Blocks(theme=gr.themes.Soft()) as app:
256
- gr.Markdown("# 🚀 AI Blog Creator")
257
 
258
  with gr.Row():
259
  with gr.Column():
260
  topic_input = gr.Textbox(label="Blog Topic", placeholder="Enter your topic...")
261
- generate_btn = gr.Button("Generate Blog", variant="primary")
262
 
263
  with gr.Column():
264
- gr.Markdown("## Preview & Download")
265
- content_preview = gr.Markdown(label="Blog Preview")
266
- download_output = gr.File(label="Download Package")
267
- status = gr.Textbox(label="Generation Status", interactive=False)
268
 
269
- def process_blog(topic):
270
  try:
271
- content, package = blogger.generate_blog(topic)
272
- return content, package, "Generation complete!"
 
 
 
 
273
  except Exception as e:
274
- return "", None, f"Error: {str(e)}"
275
 
276
  generate_btn.click(
277
- fn=process_blog,
278
  inputs=topic_input,
279
- outputs=[content_preview, download_output, status],
280
- api_name="generate_blog"
281
  )
282
 
283
  if __name__ == "__main__":
 
167
  import gradio as gr
168
  import os
169
  import time
 
 
170
  import requests
171
  import re
172
+ from datetime import datetime
 
 
173
  from dotenv import load_dotenv
174
+ from huggingface_hub import HfApi, Repository
175
 
 
176
  load_dotenv()
177
 
178
+ class BlogCreator:
179
  def __init__(self):
180
  self.hf_token = os.getenv("HF_TOKEN")
181
+ self.api = HfApi(token=self.hf_token)
182
  self.headers = {"Authorization": f"Bearer {self.hf_token}"}
183
+
184
+ def generate_blog(self, topic):
185
+ # Generate blog content
186
+ blog_text = self._generate_text(topic)
187
 
188
+ # Generate images
189
+ image_urls = self._generate_images(blog_text)
 
190
 
191
+ # Create hosted space
192
+ space_url = self._create_hosted_blog(topic, blog_text, image_urls)
 
 
 
 
 
 
 
193
 
194
+ return blog_text, space_url
195
+
196
+ def _generate_text(self, topic):
197
+ response = requests.post(
198
+ "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.2",
199
  headers=self.headers,
200
+ json={
201
+ "inputs": f"Write a comprehensive blog about {topic} with markdown formatting and 3 image placeholders [IMAGE1], [IMAGE2], [IMAGE3]",
202
+ "parameters": {"max_length": 2000}
203
+ }
204
  )
205
+ return response.json()[0]['generated_text']
206
+
207
+ def _generate_images(self, content):
208
+ image_prompts = re.findall(r'\[IMAGE\d+\]', content)
209
+ image_urls = []
210
 
211
+ for idx, _ in enumerate(image_prompts):
212
+ response = requests.post(
213
+ "https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-xl-base-1.0",
 
 
 
 
 
 
 
 
 
 
 
214
  headers=self.headers,
215
+ json={"inputs": f"Professional blog image about {content[:100]}, digital art, 4k"}
216
+ )
217
+ img_url = f"https://huggingface.co/datasets/username/blogs/raw/main/image_{idx}.png"
218
+ self.api.upload_file(
219
+ path_or_fileobj=response.content,
220
+ path_in_repo=f"image_{idx}.png",
221
+ repo_id="username/blogs",
222
+ repo_type="dataset"
223
  )
224
+ image_urls.append(img_url)
225
+ time.sleep(1)
226
 
227
+ return image_urls
 
 
 
 
 
 
228
 
229
+ def _create_hosted_blog(self, topic, content, image_urls):
230
+ # Create formatted HTML
231
+ repo_name = f"blog-{topic.lower().replace(' ', '-')}-{int(time.time())}"
232
+ html_content = f"""
233
+ <!DOCTYPE html>
234
+ <html>
235
+ <head>
236
+ <title>{topic}</title>
237
+ <style>
238
+ body {{ max-width: 800px; margin: 0 auto; padding: 20px; font-family: Arial, sans-serif; }}
239
+ img {{ width: 100%; border-radius: 10px; margin: 20px 0; }}
240
+ h1 {{ color: #2c3e50; }}
241
+ .header {{ text-align: center; padding: 40px 0; }}
242
+ </style>
243
+ </head>
244
+ <body>
245
+ <div class="header">
246
+ <h1>{topic}</h1>
247
+ <p>Generated on {datetime.now().strftime("%B %d, %Y")}</p>
248
+ </div>
249
+ {self._format_content(content, image_urls)}
250
+ </body>
251
+ </html>
252
+ """
253
+
254
+ # Create and host Space
255
+ self.api.create_repo(
256
+ repo_id=repo_name,
257
+ repo_type="space",
258
+ space_sdk="static"
259
+ )
260
+
261
+ self.api.upload_file(
262
+ path_or_fileobj=html_content.encode(),
263
+ path_in_repo="index.html",
264
+ repo_id=f"username/{repo_name}",
265
+ repo_type="space"
266
+ )
267
+
268
+ return f"https://huggingface.co/spaces/username/{repo_name}"
269
 
270
+ def _format_content(self, content, image_urls):
271
+ # Replace image placeholders with actual URLs
272
+ for idx, url in enumerate(image_urls):
273
+ content = content.replace(f"[IMAGE{idx+1}]", f'<img src="{url}" alt="Blog Image {idx+1}">')
274
+
275
+ # Convert markdown to HTML
276
+ content = content.replace("\n", "<br>")
277
+ content = re.sub(r"### (.*?)", r"<h3>\1</h3>", content)
278
+ content = re.sub(r"## (.*?)", r"<h2>\1</h2>", content)
279
+ content = re.sub(r"\*\*(.*?)\*\*", r"<strong>\1</strong>", content)
280
+
281
+ return content
 
282
 
283
+ # Initialize blog creator
284
+ creator = BlogCreator()
285
 
 
286
  with gr.Blocks(theme=gr.themes.Soft()) as app:
287
+ gr.Markdown("# 🌐 AI Blog Publisher")
288
 
289
  with gr.Row():
290
  with gr.Column():
291
  topic_input = gr.Textbox(label="Blog Topic", placeholder="Enter your topic...")
292
+ generate_btn = gr.Button("Generate & Publish", variant="primary")
293
 
294
  with gr.Column():
295
+ gr.Markdown("## Generated Content")
296
+ blog_preview = gr.Markdown()
297
+ space_link = gr.Markdown("**Hosted Blog URL:** Waiting for generation...")
298
+ status = gr.Textbox(label="Status")
299
 
300
+ def process_request(topic):
301
  try:
302
+ blog_text, url = creator.generate_blog(topic)
303
+ return (
304
+ blog_text,
305
+ f"**Hosted Blog URL:** [Click to View]({url})",
306
+ "✅ Blog published successfully!"
307
+ )
308
  except Exception as e:
309
+ return "", "Error generating blog", str(e)
310
 
311
  generate_btn.click(
312
+ fn=process_request,
313
  inputs=topic_input,
314
+ outputs=[blog_preview, space_link, status]
 
315
  )
316
 
317
  if __name__ == "__main__":