File size: 5,000 Bytes
8ccc555 498b1f8 8ccc555 498b1f8 b3aa6d6 94976d3 b3aa6d6 94976d3 8ccc555 498b1f8 67230d8 94976d3 67230d8 94976d3 498b1f8 8ccc555 498b1f8 8ccc555 67230d8 8ccc555 94976d3 8ccc555 498b1f8 67230d8 8ccc555 94976d3 67230d8 94976d3 498b1f8 94976d3 498b1f8 67230d8 94976d3 498b1f8 94976d3 eef0eb0 94976d3 498b1f8 94976d3 67230d8 94976d3 498b1f8 8ccc555 6f0c072 498b1f8 6625dd9 67230d8 498b1f8 67230d8 8ccc555 498b1f8 94976d3 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 |
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, blog_link):
try:
tone_str = ", ".join(tones)
print(f"[build_prompt] Using tones: {tone_str} for platform: {platform}")
# Add a friendly invitation to the end of the generated post
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}
---
And by the way, if you're curious about my fermentation experiments or want to join in on the fun, feel free to check out my blog! I've got all sorts of tips, tricks, and beginner-friendly recipes to help you start your own fermentation journey. {blog_link} – hope to see you there!
"""
except Exception as e:
print(f"[build_prompt] Error: {e}")
return ""
# ---------------------------
# Function to call Gemini
# ---------------------------
def generate_post(api_key, text, tones, platform, blog_link):
try:
headers = {"Content-Type": "application/json"}
prompt = build_prompt(text, tones, platform, blog_link)
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, blog_link):
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, blog_link)
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")
blog_link_input = gr.Textbox(label="Enter Your Blog Link", placeholder="Insert your blog link here...")
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, blog_link_input], outputs=output_box)
# ---------------------------
# Launch App
# ---------------------------
demo.launch()
|