Kvikontent commited on
Commit
3cd16d1
1 Parent(s): ffaba9f

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -0
app.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ import io
4
+ from io import BytesIO
5
+ import os
6
+ from PIL import Image
7
+
8
+ API_URL = "https://api-inference.huggingface.co/models/Kvikontent/Bulatnaya-V1"
9
+ api_key = os.environ.get('api_token')
10
+ headers = {"Authorization": f"Bearer {api_key}"}
11
+
12
+ # Define custom Exception class for better error handling
13
+ class QueryError(Exception):
14
+ pass
15
+
16
+ def query(payload):
17
+ try:
18
+ # Make sure we have valid JSON data before sending the request
19
+ assert type(payload) == dict
20
+
21
+ # Send the POST request to the API URL
22
+ response = requests.post(API_URL, headers=headers, json=payload)
23
+
24
+ # Check if the status code indicates success (HTTP Status Code 2xx)
25
+ if not str(response.status_code).startswith("2"):
26
+ raise QueryError(f"Query failed! Response status code was '{response.status_code}'")
27
+
28
+ else:
29
+ # Return the raw bytes from the response object
30
+ return response.content
31
+
32
+ except AssertionError:
33
+ print("Invalid Payload Error: Please provide a dictionary.")
34
+ except RequestException as e:
35
+ print("Request Failed: ", e)
36
+ except ConnectionError as ce:
37
+ print("Connection Error: Unable to connect to the API.", ce)
38
+ except Timeout as t:
39
+ print("Timeout Error: Request timed out while trying to reach the API.", t)
40
+ except TooManyRedirects as tmr:
41
+ print("Too Many Redirects Error: Exceeded maximum number of redirects.", tmr)
42
+ except HTTPError as he:
43
+ print("HTTP Error: Invalid HTTP response.", he)
44
+ except QueryError as qe:
45
+ print(qe)
46
+ except Exception as ex:
47
+ print("Unknown Error occurred: ", ex)
48
+
49
+ def generate_image_from_prompt(prompt_text):
50
+ gr.Info("Image generation started")
51
+ image_bytes = query({"inputs": prompt_text})
52
+ img = BytesIO(image_bytes) # Convert to BytesIO stream
53
+ pil_img = Image.open(img) # Open the image using PIL library
54
+ return pil_img # Return the converted PIL image
55
+
56
+ title = "BUlatnaya V1 Demo 🎨"
57
+ description = "This app uses Hugging Face AI model to generate an image based on the provided text prompt 🖼."
58
+
59
+ input_prompt = gr.Textbox(label="Enter Prompt 📝", placeholder="E.g. 'Astronaut riding a horse'")
60
+ output_generated_image = gr.Image(label="Generated Image")
61
+
62
+ iface = gr.Interface(
63
+ fn=generate_image_from_prompt,
64
+ inputs=input_prompt,
65
+ outputs=output_generated_image,
66
+ title=title,
67
+ description=description,
68
+ theme="soft"
69
+ )
70
+ iface.launch()