JaeSwift's picture
Update app.py
0b8c5fb verified
raw
history blame
4.86 kB
import gradio as gr
import requests
import urllib.parse
from PIL import Image, ImageDraw, ImageFont
# RapidAPI Credentials and API Endpoint
API_KEY = "2e427e3d07mshba1bdb10cb6eb30p12d12fjsn215dd7746115" # Replace with your actual API key
API_HOST = "horoscopes-ai.p.rapidapi.com"
API_URL_TEMPLATE = "https://horoscopes-ai.p.rapidapi.com/get_horoscope/{sign}/{period}/general/en"
# Function to Fetch Horoscope and Create Twitter Share Link
def get_horoscope(sign, period="today"):
url = API_URL_TEMPLATE.format(sign=sign, period=period)
headers = {
"x-rapidapi-key": API_KEY,
"x-rapidapi-host": API_HOST
}
try:
response = requests.get(url, headers=headers)
response.raise_for_status()
# Parse JSON response and retrieve the horoscope text
data = response.json()
horoscope_text = data.get("general", ["No horoscope available"])[0]
# Prepare the Twitter share link
share_text = f"Here's my horoscope for {sign.capitalize()} on {period.capitalize()}:\n{horoscope_text}"
encoded_text = urllib.parse.quote(share_text) # URL-encode the text
twitter_share_url = f"https://twitter.com/intent/tweet?text={encoded_text}"
# Return both the horoscope and the Twitter link
return horoscope_text, twitter_share_url
except requests.exceptions.RequestException as e:
return f"Error retrieving horoscope: {e}", None
# Function to Generate Image from Horoscope Text
def generate_horoscope_image(text):
# Define image size and background color
width, height = 800, 400
background_color = "lightblue"
# Create a blank image with background color
image = Image.new("RGB", (width, height), color=background_color)
draw = ImageDraw.Draw(image)
# Set font and text color
try:
# Use a default PIL font if no custom font is available
font = ImageFont.truetype("arial.ttf", size=20)
except IOError:
font = ImageFont.load_default()
text_color = "black"
padding = 20
# Wrap text to fit within the image width
lines = []
words = text.split()
while words:
line = ''
while words and (draw.textlength(line + words[0], font=font) <= width - padding * 2):
line += (words.pop(0) + ' ')
lines.append(line)
# Calculate text position for centered alignment
total_text_height = sum([draw.textbbox((0, 0), line, font=font)[3] - draw.textbbox((0, 0), line, font=font)[1] for line in lines])
y_text = (height - total_text_height) // 2
# Draw each line of text
for line in lines:
text_width = draw.textlength(line, font=font)
x_text = (width - text_width) // 2 # Center align
draw.text((x_text, y_text), line, font=font, fill=text_color)
y_text += draw.textbbox((0, 0), line, font=font)[3] - draw.textbbox((0, 0), line, font=font)[1]
# Save image to file
image_path = "/tmp/horoscope_image.png"
image.save(image_path)
return image_path
# Gradio Interface Setup
with gr.Blocks() as demo:
gr.Markdown("<center><h1>Daily Horoscope by Enemy AI</h1></center>")
gr.Markdown("Select your zodiac sign and period to receive your personalized horoscope.")
# Input dropdowns for sign and period
sign_dropdown = gr.Dropdown(label="Select Your Zodiac Sign", choices=[
"aries", "taurus", "gemini", "cancer", "leo", "virgo",
"libra", "scorpio", "sagittarius", "capricorn", "aquarius", "pisces"
])
period_dropdown = gr.Dropdown(label="Select Period", choices=["today", "tomorrow", "yesterday"], value="today")
# Textbox to display the horoscope
horoscope_output = gr.Textbox(label="Your Horoscope")
# Link to share on Twitter
twitter_link = gr.HTML()
# Image output for download
horoscope_image = gr.Image(label="Downloadable Horoscope Image")
# Button to trigger the API call
btn_get_horoscope = gr.Button("Get Horoscope")
# Define the click event
def on_click(sign, period):
horoscope_text, twitter_share_url = get_horoscope(sign, period)
twitter_button_html = f'<a href="{twitter_share_url}" target="_blank" style="color: white; background-color: #1DA1F2; padding: 10px; border-radius: 5px; text-decoration: none;">Share on Twitter</a>'
# Generate horoscope image and return path for download
image_path = generate_horoscope_image(horoscope_text)
return horoscope_text, twitter_button_html, image_path
# Set up click action to update outputs
btn_get_horoscope.click(fn=on_click, inputs=[sign_dropdown, period_dropdown], outputs=[horoscope_output, twitter_link, horoscope_image])
if __name__ == "__main__":
demo.launch(server_name="0.0.0.0")