5m4ck3r commited on
Commit
bb18612
·
verified ·
1 Parent(s): 0841eca

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -4
app.py CHANGED
@@ -1,6 +1,4 @@
1
  import os
2
- os.system("pip install git+https://github.com/huggingface/huggingface_hub")
3
- from huggingface_hub.inference_api import InferenceClient
4
  import gradio as gr
5
  import numpy as np
6
  import random
@@ -8,20 +6,80 @@ import spaces
8
  import torch
9
  import tempfile
10
  import os
 
 
 
 
11
  from PIL import Image
12
 
13
  token = os.environ["API_TOKEN"]
14
- model = InferenceClient("black-forest-labs/FLUX.1-schnell", token=token)
15
  dtype = torch.bfloat16
16
  device = "cuda" if torch.cuda.is_available() else "cpu"
17
 
18
  MAX_SEED = np.iinfo(np.int32).max
19
  MAX_IMAGE_SIZE = 2048
20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  def infer(prompt, seed=42, randomize_seed=False, width=1024, height=1024, num_inference_steps=4, progress=gr.Progress(track_tqdm=True)):
22
  if randomize_seed:
23
  seed = random.randint(0, MAX_SEED)
24
- image = client.text_to_image(
25
  "A girl and a boy dancing in the forest",
26
  height=height,
27
  width=width,
 
1
  import os
 
 
2
  import gradio as gr
3
  import numpy as np
4
  import random
 
6
  import torch
7
  import tempfile
8
  import os
9
+ import requests
10
+ import time
11
+ from io import BytesIO
12
+
13
  from PIL import Image
14
 
15
  token = os.environ["API_TOKEN"]
16
+ model = "black-forest-labs/FLUX.1-schnell"
17
  dtype = torch.bfloat16
18
  device = "cuda" if torch.cuda.is_available() else "cpu"
19
 
20
  MAX_SEED = np.iinfo(np.int32).max
21
  MAX_IMAGE_SIZE = 2048
22
 
23
+ def text_to_image(prompt, height, width, seed, num_inference_steps,
24
+ model=model,
25
+ token=token):
26
+ """
27
+ Generate an image from a text prompt using the Hugging Face Inference API.
28
+ Returns a PIL Image (JPEG) if successful, otherwise returns None after retrying.
29
+
30
+ Parameters:
31
+ prompt (str): The text prompt describing the image.
32
+ height (int): Height of the generated image.
33
+ width (int): Width of the generated image.
34
+ seed (int): Random seed for generation reproducibility.
35
+ num_inference_steps (int): Number of inference steps.
36
+ model (str): Hugging Face model identifier.
37
+ token (str): Hugging Face API token.
38
+
39
+ Returns:
40
+ PIL.Image.Image or None: The generated image as a PIL Image object or None on failure.
41
+ """
42
+ api_url = f"https://api-inference.huggingface.co/models/{model}"
43
+ headers = {
44
+ "Authorization": f"Bearer {token}"
45
+ }
46
+ payload = {
47
+ "inputs": prompt,
48
+ "parameters": {
49
+ "height": height,
50
+ "width": width,
51
+ "seed": seed,
52
+ "num_inference_steps": num_inference_steps
53
+ }
54
+ }
55
+ for attempt in range(1, 4):
56
+ response = requests.post(api_url, headers=headers, json=payload)
57
+ if response.status_code == 200:
58
+ try:
59
+ image = Image.open(BytesIO(response.content))
60
+ if image.format != 'JPEG':
61
+ with BytesIO() as output:
62
+ image.convert("RGB").save(output, format="JPEG")
63
+ output.seek(0)
64
+ image = Image.open(output)
65
+ return image
66
+ except Exception as e:
67
+ print(f"Error processing the image data: {e}")
68
+ else:
69
+ print(f"Attempt {attempt}: Request failed with status code {response.status_code}")
70
+
71
+ if attempt == 1:
72
+ print("Waiting for 3 seconds before retrying...")
73
+ time.sleep(3)
74
+ elif attempt == 2:
75
+ print("Waiting for 5 seconds before retrying...")
76
+ time.sleep(5)
77
+ return None
78
+
79
  def infer(prompt, seed=42, randomize_seed=False, width=1024, height=1024, num_inference_steps=4, progress=gr.Progress(track_tqdm=True)):
80
  if randomize_seed:
81
  seed = random.randint(0, MAX_SEED)
82
+ image = text_to_image(
83
  "A girl and a boy dancing in the forest",
84
  height=height,
85
  width=width,