Spaces:
Sleeping
Sleeping
Rename app.py to story_to_comic.py
Browse files- app.py +0 -68
- story_to_comic.py +145 -0
app.py
DELETED
@@ -1,68 +0,0 @@
|
|
1 |
-
import gradio as gr
|
2 |
-
import requests
|
3 |
-
import base64
|
4 |
-
import os
|
5 |
-
import time
|
6 |
-
|
7 |
-
# Get your Hugging Face access token from the secrets
|
8 |
-
HUGGING_FACE_API_KEY = os.getenv("onteddu") # Ensure your access token is properly set
|
9 |
-
|
10 |
-
def generate_images_from_text(text):
|
11 |
-
# Generate an image using Hugging Face's API
|
12 |
-
headers = {
|
13 |
-
"Authorization": f"Bearer {HUGGING_FACE_API_KEY}"
|
14 |
-
}
|
15 |
-
|
16 |
-
response = requests.post(
|
17 |
-
"https://api-inference.huggingface.co/models/brushpenbob/flux-midjourney-anime", # Correct model name
|
18 |
-
headers=headers,
|
19 |
-
json={"inputs": text}
|
20 |
-
)
|
21 |
-
|
22 |
-
if response.status_code == 200:
|
23 |
-
# The API response contains the image as raw binary data
|
24 |
-
image_data = response.content
|
25 |
-
|
26 |
-
# Convert the image to Base64 for embedding in HTML
|
27 |
-
base64_image = base64.b64encode(image_data).decode('utf-8')
|
28 |
-
return f"data:image/png;base64,{base64_image}"
|
29 |
-
else:
|
30 |
-
print(f"Error generating image: {response.text}")
|
31 |
-
return None
|
32 |
-
|
33 |
-
def generate_comic(short_story):
|
34 |
-
sentences = short_story.split('. ')
|
35 |
-
images = []
|
36 |
-
|
37 |
-
for sentence in sentences:
|
38 |
-
if sentence.strip():
|
39 |
-
try:
|
40 |
-
# Generate one image for each sentence
|
41 |
-
image_data = generate_images_from_text(sentence)
|
42 |
-
if image_data:
|
43 |
-
images.append(image_data)
|
44 |
-
|
45 |
-
# Sleep for a short duration to avoid hitting rate limits
|
46 |
-
time.sleep(2) # Adjust this time if needed
|
47 |
-
|
48 |
-
except Exception as e:
|
49 |
-
print(f"Error generating image: {e}")
|
50 |
-
|
51 |
-
# Create comic HTML with reduced image sizes and panel layout
|
52 |
-
comic_html = '<div style="display: flex; flex-wrap: wrap;">'
|
53 |
-
for img in images:
|
54 |
-
comic_html += f'<div style="flex: 1; margin: 5px;"><img src="{img}" style="max-width: 300px; max-height: 300px;" /></div>'
|
55 |
-
comic_html += '</div>'
|
56 |
-
|
57 |
-
return comic_html
|
58 |
-
|
59 |
-
# Gradio interface
|
60 |
-
iface = gr.Interface(
|
61 |
-
fn=generate_comic,
|
62 |
-
inputs=gr.Textbox(label="Your Short Story", lines=10, placeholder="Enter your short story here..."),
|
63 |
-
outputs=gr.HTML(label="Generated Comic"),
|
64 |
-
title="Narrative to Comic Generator",
|
65 |
-
description="Enter a short story, and the app will generate a comic-style storybook with images and dialogues."
|
66 |
-
)
|
67 |
-
|
68 |
-
iface.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
story_to_comic.py
ADDED
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import requests
|
3 |
+
import gradio as gr
|
4 |
+
import nltk
|
5 |
+
from nltk.tokenize import sent_tokenize
|
6 |
+
from io import BytesIO
|
7 |
+
from PIL import Image
|
8 |
+
import base64
|
9 |
+
|
10 |
+
# Ensure NLTK's punkt tokenizer is downloaded
|
11 |
+
nltk.download('punkt')
|
12 |
+
|
13 |
+
# Function to generate image from a prompt using Hugging Face's API
|
14 |
+
def generate_image(prompt, api_key, model="stabilityai/stable-diffusion-2"):
|
15 |
+
"""
|
16 |
+
Generates an image from a text prompt using Hugging Face's Inference API.
|
17 |
+
|
18 |
+
Args:
|
19 |
+
prompt (str): The text prompt to generate the image.
|
20 |
+
api_key (str): Hugging Face API key for authentication.
|
21 |
+
model (str): The Hugging Face model to use for generation.
|
22 |
+
|
23 |
+
Returns:
|
24 |
+
Image object if successful, None otherwise.
|
25 |
+
"""
|
26 |
+
API_URL = f"https://api-inference.huggingface.co/models/{model}"
|
27 |
+
headers = {"Authorization": f"Bearer {api_key}"}
|
28 |
+
|
29 |
+
payload = {
|
30 |
+
"inputs": prompt,
|
31 |
+
"options": {
|
32 |
+
"use_gpu": True # Optional: Use GPU if available
|
33 |
+
}
|
34 |
+
}
|
35 |
+
|
36 |
+
response = requests.post(API_URL, headers=headers, json=payload, stream=True)
|
37 |
+
|
38 |
+
if response.status_code == 200:
|
39 |
+
try:
|
40 |
+
# Hugging Face returns the image directly
|
41 |
+
image = Image.open(BytesIO(response.content))
|
42 |
+
return image
|
43 |
+
except Exception as e:
|
44 |
+
print(f"Error processing image: {e}")
|
45 |
+
return None
|
46 |
+
else:
|
47 |
+
print(f"Error {response.status_code}: {response.text}")
|
48 |
+
return None
|
49 |
+
|
50 |
+
# Main function to process the story and generate images
|
51 |
+
def story_to_comic(story, api_key):
|
52 |
+
"""
|
53 |
+
Processes the input story, generates comic-style images for each sentence,
|
54 |
+
and returns them for display.
|
55 |
+
|
56 |
+
Args:
|
57 |
+
story (str): The input short story.
|
58 |
+
api_key (str): Hugging Face API key for authentication.
|
59 |
+
|
60 |
+
Returns:
|
61 |
+
List of images or error message.
|
62 |
+
"""
|
63 |
+
if not api_key:
|
64 |
+
return "π Hugging Face API key is required. Please enter your API key."
|
65 |
+
|
66 |
+
# Split the story into sentences
|
67 |
+
sentences = sent_tokenize(story)
|
68 |
+
|
69 |
+
if not sentences:
|
70 |
+
return "β No valid sentences found in the input story."
|
71 |
+
|
72 |
+
images = []
|
73 |
+
for idx, sentence in enumerate(sentences, 1):
|
74 |
+
# Customize the prompt for comic-style images
|
75 |
+
prompt = f"A vibrant comic-style illustration of: {sentence}"
|
76 |
+
print(f"Generating image for sentence {idx}: {sentence}")
|
77 |
+
|
78 |
+
image = generate_image(prompt, api_key)
|
79 |
+
if image:
|
80 |
+
# Convert PIL Image to a format compatible with Gradio Gallery
|
81 |
+
buffered = BytesIO()
|
82 |
+
image.save(buffered, format="PNG")
|
83 |
+
img_str = base64.b64encode(buffered.getvalue()).decode()
|
84 |
+
img_data = f"data:image/png;base64,{img_str}"
|
85 |
+
images.append([img_data]) # Each image should be in its own list for Gallery
|
86 |
+
else:
|
87 |
+
# Placeholder for failed image generation
|
88 |
+
images.append([None])
|
89 |
+
|
90 |
+
return images
|
91 |
+
|
92 |
+
# Gradio Interface
|
93 |
+
def create_interface():
|
94 |
+
"""
|
95 |
+
Creates and returns the Gradio interface.
|
96 |
+
"""
|
97 |
+
with gr.Blocks() as demo:
|
98 |
+
gr.Markdown("# π Story to Comic Generator")
|
99 |
+
gr.Markdown(
|
100 |
+
"""
|
101 |
+
**Enter a short story**, and this tool will generate a **comic-style image** for each sentence in your story.
|
102 |
+
"""
|
103 |
+
)
|
104 |
+
|
105 |
+
with gr.Row():
|
106 |
+
with gr.Column(scale=1):
|
107 |
+
story_input = gr.Textbox(
|
108 |
+
label="π Enter Your Short Story",
|
109 |
+
placeholder="Once upon a time in a land far away...",
|
110 |
+
lines=10
|
111 |
+
)
|
112 |
+
api_key_input = gr.Textbox(
|
113 |
+
label="π Hugging Face API Key",
|
114 |
+
placeholder="Enter your Hugging Face API key here",
|
115 |
+
type="password"
|
116 |
+
)
|
117 |
+
generate_button = gr.Button("π¨ Generate Comic")
|
118 |
+
with gr.Column(scale=2):
|
119 |
+
gallery = gr.Gallery(
|
120 |
+
label="π Generated Comic Panels",
|
121 |
+
show_label=True,
|
122 |
+
columns=[1],
|
123 |
+
object_fit="contain",
|
124 |
+
height="auto"
|
125 |
+
).style(grid=[1], height="auto")
|
126 |
+
|
127 |
+
generate_button.click(
|
128 |
+
fn=story_to_comic,
|
129 |
+
inputs=[story_input, api_key_input],
|
130 |
+
outputs=gallery
|
131 |
+
)
|
132 |
+
|
133 |
+
gr.Markdown(
|
134 |
+
"""
|
135 |
+
---
|
136 |
+
**Need a Hugging Face API Key?**
|
137 |
+
Visit [Hugging Face Tokens](https://huggingface.co/settings/tokens) to create one.
|
138 |
+
"""
|
139 |
+
)
|
140 |
+
|
141 |
+
return demo
|
142 |
+
|
143 |
+
if __name__ == "__main__":
|
144 |
+
demo = create_interface()
|
145 |
+
demo.launch()
|