mroccuper's picture
Update app.py
eef0eb0 verified
raw
history blame
4.53 kB
import gradio as gr
from bs4 import BeautifulSoup
import json
import requests
# ---------------------------
# Tone Options
# ---------------------------
TONE_OPTIONS = ["Friendly", "Humanized", "Engaging", "Funny", "Emotional"]
# ---------------------------
# Function to extract main content from HTML
# ---------------------------
def extract_main_content(html_text):
try:
soup = BeautifulSoup(html_text, "html.parser")
article = soup.find("article") or soup.body
text = article.get_text(separator="\n", strip=True) if article else ""
print("[extract_main_content] Successfully extracted main content.")
return text
except Exception as e:
print(f"[extract_main_content] Error: {e}")
return ""
# ---------------------------
# Prompt builder
# ---------------------------
def build_prompt(text, tones, platform):
try:
tone_str = ", ".join(tones)
print(f"[build_prompt] Using tones: {tone_str} for platform: {platform}")
return f"""
You are a skilled content writer. Based on the content below, generate a post for {platform}.
The post should feel like someone sharing a personal experience or story related to the topic.
Make it {tone_str.lower()}, natural, and relatable. Include a catchy title to hook readers, and a body that encourages responses.
---
{text}
---
Return in this format:
Title: <catchy title>
Body:
<post body text>
"""
except Exception as e:
print(f"[build_prompt] Error: {e}")
return ""
# ---------------------------
# Function to call Gemini
# ---------------------------
def generate_post(api_key, text, tones, platform):
try:
headers = {"Content-Type": "application/json"}
prompt = build_prompt(text, tones, platform)
data = {
"contents": [{"parts": [{"text": prompt}]}]
}
print("[generate_post] Sending request to Gemini API...")
response = requests.post(
f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-pro:generateContent?key={api_key}",
headers=headers,
data=json.dumps(data)
)
print(f"[generate_post] Response status code: {response.status_code}")
result = response.json()
print(f"[generate_post] Response JSON: {result}")
return result["candidates"][0]["content"]["parts"][0]["text"]
except Exception as e:
print(f"[generate_post] Error: {e}")
return "Error generating content. Check your API key or prompt."
# ---------------------------
# Gradio UI
# ---------------------------
def app_interface(html_file, tones, platform_choice, api_key):
try:
if not html_file:
return "Please upload an HTML blog post."
print("[app_interface] Reading HTML file...")
if hasattr(html_file, "name"):
with open(html_file.name, "r", encoding="utf-8") as f:
html_content = f.read()
else:
html_bytes = html_file.read()
html_content = html_bytes.decode("utf-8")
main_text = extract_main_content(html_content)
if not main_text:
return "Couldn't extract content from file. Ensure it's a valid HTML blog post."
print("[app_interface] Generating post...")
output = generate_post(api_key, main_text, tones, platform_choice)
return output
except Exception as e:
print(f"[app_interface] Error: {e}")
return "Unexpected error occurred. Please check the logs."
# Gradio Blocks UI
with gr.Blocks() as demo:
gr.Markdown("# Reddit & Quora Post Generator 🧠")
gr.Markdown("Upload your HTML blog post and get ready-to-publish content for Reddit or Quora, written in a human, friendly tone.")
with gr.Row():
html_input = gr.File(label="Upload HTML Blog Post", file_types=[".html"])
tone_checkboxes = gr.CheckboxGroup(label="Choose Tones", choices=TONE_OPTIONS, value=["Friendly", "Humanized"])
platform_radio = gr.Radio(label="Target Platform", choices=["Reddit", "Quora"], value="Reddit")
api_key_input = gr.Textbox(label="Enter Your Gemini API Key", type="password")
generate_button = gr.Button("Generate Post")
output_box = gr.Textbox(label="Generated Post", lines=20, interactive=True)
generate_button.click(app_interface, inputs=[html_input, tone_checkboxes, platform_radio, api_key_input], outputs=output_box)
# ---------------------------
# Launch App
# ---------------------------
demo.launch()