Update app.py
Browse files
app.py
CHANGED
|
@@ -1,11 +1,54 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
import os
|
| 4 |
-
import
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
-
|
| 11 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Flask, request, jsonify
|
| 2 |
+
from flask_cors import CORS
|
| 3 |
import os
|
| 4 |
+
from huggingface_hub import InferenceClient
|
| 5 |
+
from io import BytesIO
|
| 6 |
+
from PIL import Image
|
| 7 |
+
import gradio as gr # Import Gradio
|
| 8 |
|
| 9 |
+
# Initialize the Flask app
|
| 10 |
+
myapp = Flask(__name__)
|
| 11 |
+
CORS(myapp) # Enable CORS for all routes
|
| 12 |
+
|
| 13 |
+
# Initialize the InferenceClient with your Hugging Face token
|
| 14 |
+
HF_TOKEN = os.environ.get("HF_TOKEN") # Ensure to set your Hugging Face token in the environment
|
| 15 |
+
client = InferenceClient(token=HF_TOKEN)
|
| 16 |
+
|
| 17 |
+
# Function to generate an image from a text prompt
|
| 18 |
+
def generate_image(prompt, seed=1, model="prompthero/openjourney-v4"):
|
| 19 |
+
try:
|
| 20 |
+
# Generate the image using Hugging Face's inference API
|
| 21 |
+
result_image = client.text_to_image(prompt=prompt, seed=seed, model=model)
|
| 22 |
+
return result_image
|
| 23 |
+
except Exception as e:
|
| 24 |
+
print(f"Error generating image: {str(e)}")
|
| 25 |
+
return None
|
| 26 |
|
| 27 |
+
# Gradio interface function
|
| 28 |
+
def gradio_interface(prompt, seed, model_name):
|
| 29 |
+
image = generate_image(prompt, seed, model_name)
|
| 30 |
+
|
| 31 |
+
if image:
|
| 32 |
+
img_byte_arr = BytesIO()
|
| 33 |
+
image.save(img_byte_arr, format='PNG') # Convert the image to PNG
|
| 34 |
+
img_byte_arr.seek(0) # Move to the start of the byte stream
|
| 35 |
+
return img_byte_arr # Return the image as bytes
|
| 36 |
+
else:
|
| 37 |
+
return "Failed to generate image"
|
| 38 |
+
|
| 39 |
+
# Set up the Gradio interface
|
| 40 |
+
gr.Interface(
|
| 41 |
+
fn=gradio_interface,
|
| 42 |
+
inputs=[
|
| 43 |
+
gr.Textbox(label="Prompt", placeholder="Enter a text prompt", lines=2),
|
| 44 |
+
gr.Number(label="Seed", value=1, precision=0),
|
| 45 |
+
gr.Textbox(label="Model Name", value="prompthero/openjourney-v4", placeholder="Enter model name"),
|
| 46 |
+
],
|
| 47 |
+
outputs="image",
|
| 48 |
+
title="Image Generation with Hugging Face",
|
| 49 |
+
description="Enter a prompt, seed, and model name to generate an image."
|
| 50 |
+
).launch() # Launch the Gradio interface
|
| 51 |
+
|
| 52 |
+
# Add this block to make sure your app runs when called
|
| 53 |
+
if __name__ == "__main__":
|
| 54 |
+
myapp.run(host='0.0.0.0', port=7860) # Run directly if needed for testing
|