Kyan14 commited on
Commit
2afae35
·
1 Parent(s): abd7ad6

Added timeout request from api call to prevent infinite looping

Browse files
Files changed (1) hide show
  1. app.py +9 -8
app.py CHANGED
@@ -47,13 +47,12 @@ def is_black_image(image: Image.Image) -> bool:
47
  img_array = np.array(image)
48
  return np.all(img_array == 0)
49
 
50
- def generate_art(mood, max_retries=10):
51
- # Implement art generation logic using the Stable Diffusion API
52
  prompt = f"{mood} generative art with vibrant colors and intricate patterns ({str(np.random.randint(1, 10000))})"
53
 
54
  headers = {
55
  "Authorization": f"Bearer {STABLE_DIFFUSION_API_KEY}",
56
- "Accept": "image/jpeg", # Set the Accept header to receive an image directly
57
  }
58
 
59
  json_data = {
@@ -62,7 +61,12 @@ def generate_art(mood, max_retries=10):
62
 
63
  retries = 0
64
  while retries < max_retries:
65
- response = requests.post('https://api-inference.huggingface.co/models/runwayml/stable-diffusion-v1-5', headers=headers, json=json_data)
 
 
 
 
 
66
 
67
  if response.status_code == 503:
68
  print("Model is loading, waiting for 30 seconds before retrying...")
@@ -76,8 +80,7 @@ def generate_art(mood, max_retries=10):
76
  return None
77
 
78
  image = Image.open(BytesIO(response.content))
79
-
80
- # Check if the image is black
81
  if not is_black_image(image):
82
  break
83
 
@@ -88,8 +91,6 @@ def generate_art(mood, max_retries=10):
88
 
89
  return image
90
 
91
-
92
-
93
  def mood_art_generator(image):
94
  mood = get_mood_from_image(image)
95
  print("Mood:", mood)
 
47
  img_array = np.array(image)
48
  return np.all(img_array == 0)
49
 
50
+ def generate_art(mood, max_retries=3, request_timeout=30):
 
51
  prompt = f"{mood} generative art with vibrant colors and intricate patterns ({str(np.random.randint(1, 10000))})"
52
 
53
  headers = {
54
  "Authorization": f"Bearer {STABLE_DIFFUSION_API_KEY}",
55
+ "Accept": "image/jpeg",
56
  }
57
 
58
  json_data = {
 
61
 
62
  retries = 0
63
  while retries < max_retries:
64
+ try:
65
+ response = requests.post('https://api-inference.huggingface.co/models/runwayml/stable-diffusion-v1-5', headers=headers, json=json_data, timeout=request_timeout)
66
+ except requests.exceptions.Timeout:
67
+ print(f"Request timed out after {request_timeout} seconds. Retrying...")
68
+ retries += 1
69
+ continue
70
 
71
  if response.status_code == 503:
72
  print("Model is loading, waiting for 30 seconds before retrying...")
 
80
  return None
81
 
82
  image = Image.open(BytesIO(response.content))
83
+
 
84
  if not is_black_image(image):
85
  break
86
 
 
91
 
92
  return image
93
 
 
 
94
  def mood_art_generator(image):
95
  mood = get_mood_from_image(image)
96
  print("Mood:", mood)