Spaces:
Build error
Build error
Download app.py from Student3331/Text_to_Image: direct link, hf CLI and curl.
- Browser
- Download file 1.47 kB
-
https://huggingface.co/spaces/Student3331/Text_to_Image/resolve/main/app.py
- Command line
-
hf download hf://spaces/Student3331/Text_to_Image/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Student3331/Text_to_Image/resolve/main/app.py
1.47 kB
| import streamlit as st | |
| import openai | |
| import requests | |
| from PIL import Image | |
| from io import BytesIO | |
| # Set up OpenAI API key | |
| openai.api_key = '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' | |
| def generate_image_from_text(prompt: str): | |
| try: | |
| # Request to OpenAI API to generate the image from the prompt | |
| response = openai.Image.create( | |
| prompt=prompt, | |
| n=1, | |
| size="1024x1024", # You can change the image size | |
| response_format="url" # You can also choose 'b64_json' to get base64 encoded images | |
| ) | |
| # Extract the image URL | |
| image_url = response['data'][0]['url'] | |
| # Download the image using the URL | |
| img_response = requests.get(image_url) | |
| img = Image.open(BytesIO(img_response.content)) | |
| return img, image_url | |
| except Exception as e: | |
| st.error(f"An error occurred: {e}") | |
| return None, None | |
| def main(): | |
| st.title("Text to Image Generator") | |
| # User input for text prompt | |
| prompt = st.text_input("Enter a description for the image:") | |
| if prompt: | |
| st.write(f"Generating image for: {prompt}") | |
| img, img_url = generate_image_from_text(prompt) | |
| if img: | |
| st.image(img, caption="Generated Image", use_column_width=True) | |
| st.write(f"Image generated from the prompt: {img_url}") | |
| else: | |
| st.error("Failed to generate image.") | |
| if __name__ == "__main__": | |
| main() | |