akhaliq HF Staff commited on
Commit
0cea930
·
verified ·
1 Parent(s): c847b55

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +98 -39
app.py CHANGED
@@ -4,6 +4,7 @@ import random
4
  import os
5
  import base64
6
  import requests
 
7
  import io
8
  from PIL import Image, ImageOps
9
  import pillow_heif # For HEIF/AVIF support
@@ -23,57 +24,115 @@ def get_headers():
23
  "X-HF-Bill-To": "huggingface"
24
  }
25
 
26
- def query_api(payload):
27
  """Send request to the API and return response"""
28
  headers = get_headers()
 
 
29
  response = requests.post(API_URL, headers=headers, json=payload)
30
 
31
  if response.status_code != 200:
32
  raise gr.Error(f"API request failed with status {response.status_code}: {response.text}")
33
 
34
- # Debug: Check response content type and first few bytes
35
- print(f"Response status: {response.status_code}")
36
- print(f"Response headers: {dict(response.headers)}")
37
- print(f"Response content type: {response.headers.get('content-type', 'unknown')}")
38
- print(f"Response content length: {len(response.content)}")
39
- print(f"First 200 chars of response: {response.content[:200]}")
40
-
41
- # Check if response is JSON (error case) or binary (image case)
42
- content_type = response.headers.get('content-type', '').lower()
43
 
44
- if 'application/json' in content_type:
45
- # Response is JSON, might contain base64 image or error
46
- try:
47
- json_response = response.json()
48
- print(f"JSON response: {json_response}")
 
 
 
 
 
 
 
 
49
 
50
- # Check if there's a base64 image in the response
51
- if 'image' in json_response:
52
- # Decode base64 image
53
- image_data = base64.b64decode(json_response['image'])
54
- return image_data
55
- elif 'images' in json_response and len(json_response['images']) > 0:
56
- # Multiple images, take the first one
57
- image_data = base64.b64decode(json_response['images'][0])
58
- return image_data
59
- else:
60
- raise gr.Error(f"Unexpected JSON response format: {json_response}")
61
- except Exception as e:
62
- raise gr.Error(f"Failed to parse JSON response: {str(e)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
 
64
- elif 'image/' in content_type:
65
- # Response is direct image bytes
66
- return response.content
 
 
 
 
 
 
 
67
 
68
  else:
69
- # Try to decode as base64 first, then as direct bytes
70
- try:
71
- # Maybe the entire response is base64 encoded
72
- image_data = base64.b64decode(response.content)
73
- return image_data
74
- except:
75
- # Return as-is and let PIL try to handle it
76
- return response.content
77
 
78
  # --- Core Inference Function for ChatInterface ---
79
  def chat_fn(message, chat_history, seed, randomize_seed, guidance_scale, steps, progress=gr.Progress()):
 
4
  import os
5
  import base64
6
  import requests
7
+ import time
8
  import io
9
  from PIL import Image, ImageOps
10
  import pillow_heif # For HEIF/AVIF support
 
24
  "X-HF-Bill-To": "huggingface"
25
  }
26
 
27
+ def query_api(payload, progress_callback=None):
28
  """Send request to the API and return response"""
29
  headers = get_headers()
30
+
31
+ # Submit the job
32
  response = requests.post(API_URL, headers=headers, json=payload)
33
 
34
  if response.status_code != 200:
35
  raise gr.Error(f"API request failed with status {response.status_code}: {response.text}")
36
 
37
+ # Parse the initial response
38
+ try:
39
+ json_response = response.json()
40
+ print(f"Initial response: {json_response}")
41
+ except:
42
+ raise gr.Error("Failed to parse initial API response as JSON")
 
 
 
43
 
44
+ # Check if job was queued
45
+ if json_response.get("status") == "IN_QUEUE":
46
+ status_url = json_response.get("status_url")
47
+ if not status_url:
48
+ raise gr.Error("No status URL provided in queue response")
49
+
50
+ # Poll for completion
51
+ max_attempts = 60 # Wait up to 5 minutes (60 * 5 seconds)
52
+ attempt = 0
53
+
54
+ while attempt < max_attempts:
55
+ if progress_callback:
56
+ progress_callback(0.1 + (attempt / max_attempts) * 0.8, f"Processing... (attempt {attempt + 1}/60)")
57
 
58
+ time.sleep(5) # Wait 5 seconds between polls
59
+
60
+ # Check status
61
+ status_response = requests.get(status_url, headers=headers)
62
+
63
+ if status_response.status_code != 200:
64
+ raise gr.Error(f"Status check failed: {status_response.status_code}")
65
+
66
+ try:
67
+ status_data = status_response.json()
68
+ print(f"Status check {attempt + 1}: {status_data}")
69
+
70
+ if status_data.get("status") == "COMPLETED":
71
+ # Job completed, get the result
72
+ response_url = json_response.get("response_url")
73
+ if not response_url:
74
+ raise gr.Error("No response URL provided")
75
+
76
+ result_response = requests.get(response_url, headers=headers)
77
+ if result_response.status_code != 200:
78
+ raise gr.Error(f"Failed to get result: {result_response.status_code}")
79
+
80
+ # Check if result is JSON with image data
81
+ try:
82
+ result_data = result_response.json()
83
+ print(f"Result data: {result_data}")
84
+
85
+ # Look for image in various possible fields
86
+ if 'images' in result_data and len(result_data['images']) > 0:
87
+ # Images array with URLs or base64
88
+ image_data = result_data['images'][0]
89
+ if isinstance(image_data, dict) and 'url' in image_data:
90
+ # Image URL - fetch it
91
+ img_response = requests.get(image_data['url'])
92
+ return img_response.content
93
+ elif isinstance(image_data, str):
94
+ # Assume base64
95
+ return base64.b64decode(image_data)
96
+ elif 'image' in result_data:
97
+ # Single image field
98
+ if isinstance(result_data['image'], str):
99
+ return base64.b64decode(result_data['image'])
100
+ elif 'url' in result_data:
101
+ # Direct URL
102
+ img_response = requests.get(result_data['url'])
103
+ return img_response.content
104
+ else:
105
+ raise gr.Error(f"No image found in result: {result_data}")
106
+
107
+ except requests.exceptions.JSONDecodeError:
108
+ # Result might be direct image bytes
109
+ return result_response.content
110
+
111
+ elif status_data.get("status") == "FAILED":
112
+ error_msg = status_data.get("error", "Unknown error")
113
+ raise gr.Error(f"Job failed: {error_msg}")
114
+
115
+ # Still processing, continue polling
116
+ attempt += 1
117
+
118
+ except requests.exceptions.JSONDecodeError:
119
+ raise gr.Error("Failed to parse status response")
120
+
121
+ raise gr.Error("Job timed out after 5 minutes")
122
 
123
+ elif json_response.get("status") == "COMPLETED":
124
+ # Job completed immediately
125
+ if 'images' in json_response and len(json_response['images']) > 0:
126
+ image_data = json_response['images'][0]
127
+ if isinstance(image_data, str):
128
+ return base64.b64decode(image_data)
129
+ elif 'image' in json_response:
130
+ return base64.b64decode(json_response['image'])
131
+ else:
132
+ raise gr.Error(f"No image found in immediate response: {json_response}")
133
 
134
  else:
135
+ raise gr.Error(f"Unexpected response status: {json_response.get('status', 'unknown')}")
 
 
 
 
 
 
 
136
 
137
  # --- Core Inference Function for ChatInterface ---
138
  def chat_fn(message, chat_history, seed, randomize_seed, guidance_scale, steps, progress=gr.Progress()):