AI_story / app.py
geethareddy's picture
Update app.py
e0786d1 verified
import gradio as gr
import requests
import base64
import os
import time
# Get your Hugging Face access token from the secrets
HUGGING_FACE_API_KEY = os.getenv("onteddu") # Ensure your access token is properly set
def generate_images_from_text(text):
# Generate an image using Hugging Face's API
headers = {
"Authorization": f"Bearer {HUGGING_FACE_API_KEY}"
}
response = requests.post(
"https://api-inference.huggingface.co/models/black-forest-labs/FLUX.1-schnell", # Correct model name
headers=headers,
json={"inputs": text}
)
if response.status_code == 200:
# The API response contains the image as raw binary data
image_data = response.content
# Convert the image to Base64 for embedding in HTML
base64_image = base64.b64encode(image_data).decode('utf-8')
return f"data:image/png;base64,{base64_image}"
else:
print(f"Error generating image: {response.text}")
return None
def generate_comic(short_story):
sentences = short_story.split('. ')
images = []
for sentence in sentences:
if sentence.strip():
try:
# Generate one image for each sentence
image_data = generate_images_from_text(sentence)
if image_data:
images.append(image_data)
# Sleep for a short duration to avoid hitting rate limits
time.sleep(2) # Adjust this time if needed
except Exception as e:
print(f"Error generating image: {e}")
# Create comic HTML with reduced image sizes and panel layout
comic_html = '<div style="display: flex; flex-wrap: wrap;">'
for img in images:
comic_html += f'<div style="flex: 1; margin: 5px;"><img src="{img}" style="max-width: 300px; max-height: 300px;" /></div>'
comic_html += '</div>'
return comic_html
# Gradio interface
iface = gr.Interface(
fn=generate_comic,
inputs=gr.Textbox(label="Your Short Story", lines=10, placeholder="Enter your short story here..."),
outputs=gr.HTML(label="Generated Comic"),
title="Narrative to Comic Generator",
description="Enter a short story, and the app will generate a comic-style storybook with images and dialogues."
)
iface.launch()