aiqtech commited on
Commit
9612414
·
verified ·
1 Parent(s): 2e3e7c3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -38
app.py CHANGED
@@ -29,8 +29,61 @@ def verify_login_status(token: Optional[gr.OAuthToken]) -> bool:
29
  print(f"Could not verify user's login status: {e}")
30
  return False
31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  def image_to_data_uri(image_path: str) -> str:
33
- """Convert local image file to data URI format."""
34
  with open(image_path, "rb") as img_file:
35
  img_data = img_file.read()
36
  img_base64 = base64.b64encode(img_data).decode('utf-8')
@@ -53,11 +106,18 @@ def run_single_image_logic(prompt: str, image_path: Optional[str] = None, progre
53
  "prompt": prompt
54
  }
55
 
56
- # If there's an input image, convert it to data URI
57
  if image_path:
58
- # Convert local image to data URI format
59
- data_uri = image_to_data_uri(image_path)
60
- input_data["image_input"] = [data_uri]
 
 
 
 
 
 
 
61
 
62
  progress(0.5, desc="✨ Generating...")
63
 
@@ -71,43 +131,17 @@ def run_single_image_logic(prompt: str, image_path: Optional[str] = None, progre
71
 
72
  # Handle the output - output is already a URL string or FileObject
73
  if output:
74
- # Check if output has a url attribute (FileObject)
75
- if hasattr(output, 'url'):
76
- # If url is a method, call it; if it's a property, just access it
77
- image_url = output.url() if callable(output.url) else output.url
78
- # If output is already a string URL
79
- elif isinstance(output, str):
80
- image_url = output
81
- # If output is a list of URLs
82
- elif isinstance(output, list) and len(output) > 0:
83
- # Check first item in list
84
- first_item = output[0]
85
- if hasattr(first_item, 'url'):
86
- image_url = first_item.url() if callable(first_item.url) else first_item.url
87
- else:
88
- image_url = first_item
89
- else:
90
- raise ValueError(f"Unexpected output format from Replicate: {type(output)}")
91
-
92
- # Download the image from URL
93
- response = requests.get(image_url)
94
- response.raise_for_status()
95
-
96
- # Save to temporary file
97
- img = Image.open(BytesIO(response.content))
98
- with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as tmpfile:
99
- img.save(tmpfile.name)
100
- progress(1.0, desc="✅ Complete!")
101
- return tmpfile.name
102
  else:
103
  raise ValueError("No output received from Replicate API")
104
 
105
  except Exception as e:
106
  print(f"Error details: {e}")
107
  print(f"Error type: {type(e)}")
108
- print(f"Output value: {output if 'output' in locals() else 'Not set'}")
109
- print(f"Output type: {type(output) if 'output' in locals() else 'Not set'}")
110
- raise gr.Error(f"Image generation failed: {e}")
 
111
 
112
  def run_multi_image_logic(prompt: str, images: List[str], progress=gr.Progress()) -> str:
113
  """
@@ -563,5 +597,4 @@ with gr.Blocks(theme=gr.themes.Soft(), css=css) as demo:
563
 
564
  if __name__ == "__main__":
565
  demo.queue(max_size=None, default_concurrency_limit=None)
566
- demo.launch()
567
-
 
29
  print(f"Could not verify user's login status: {e}")
30
  return False
31
 
32
+ def upload_image_to_hosting(image_path: str) -> str:
33
+ """
34
+ Upload image to hosting service and return URL.
35
+ Using multiple fallback methods for reliability.
36
+ """
37
+ # Open the image
38
+ img = Image.open(image_path)
39
+
40
+ # Method 1: Try imgbb.com (most reliable)
41
+ try:
42
+ buffered = BytesIO()
43
+ img.save(buffered, format="PNG")
44
+ buffered.seek(0)
45
+ img_base64 = base64.b64encode(buffered.getvalue()).decode()
46
+
47
+ response = requests.post(
48
+ "https://api.imgbb.com/1/upload",
49
+ data={
50
+ 'key': '6d207e02198a847aa98d0a2a901485a5', # Free API key
51
+ 'image': img_base64,
52
+ }
53
+ )
54
+
55
+ if response.status_code == 200:
56
+ data = response.json()
57
+ if data.get('success'):
58
+ return data['data']['url']
59
+ except Exception as e:
60
+ print(f"imgbb upload failed: {e}")
61
+
62
+ # Method 2: Try 0x0.st (simple and reliable)
63
+ try:
64
+ buffered = BytesIO()
65
+ img.save(buffered, format="PNG")
66
+ buffered.seek(0)
67
+
68
+ files = {'file': ('image.png', buffered, 'image/png')}
69
+ response = requests.post("https://0x0.st", files=files)
70
+
71
+ if response.status_code == 200:
72
+ url = response.text.strip()
73
+ if url.startswith('http'):
74
+ return url
75
+ except Exception as e:
76
+ print(f"0x0.st upload failed: {e}")
77
+
78
+ # Method 3: Fallback to data URI (last resort)
79
+ buffered = BytesIO()
80
+ img.save(buffered, format="PNG")
81
+ buffered.seek(0)
82
+ img_base64 = base64.b64encode(buffered.getvalue()).decode()
83
+ return f"data:image/png;base64,{img_base64}"
84
+
85
  def image_to_data_uri(image_path: str) -> str:
86
+ """Convert local image file to data URI format (kept for backwards compatibility)."""
87
  with open(image_path, "rb") as img_file:
88
  img_data = img_file.read()
89
  img_base64 = base64.b64encode(img_data).decode('utf-8')
 
106
  "prompt": prompt
107
  }
108
 
109
+ # If there's an input image, upload it to get a proper URL
110
  if image_path:
111
+ progress(0.3, desc="📤 Uploading image...")
112
+ # Upload to hosting service for proper URL
113
+ image_url = upload_image_to_hosting(image_path)
114
+
115
+ if image_url.startswith('http'):
116
+ print(f"Image uploaded successfully: {image_url[:50]}...")
117
+ else:
118
+ print("Using data URI fallback")
119
+
120
+ input_data["image_input"] = [image_url]
121
 
122
  progress(0.5, desc="✨ Generating...")
123
 
 
131
 
132
  # Handle the output - output is already a URL string or FileObject
133
  if output:
134
+ return process_output(output, progress)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  else:
136
  raise ValueError("No output received from Replicate API")
137
 
138
  except Exception as e:
139
  print(f"Error details: {e}")
140
  print(f"Error type: {type(e)}")
141
+ if 'output' in locals():
142
+ print(f"Output value: {output}")
143
+ print(f"Output type: {type(output)}")
144
+ raise gr.Error(f"Image generation failed: {str(e)[:200]}")
145
 
146
  def run_multi_image_logic(prompt: str, images: List[str], progress=gr.Progress()) -> str:
147
  """
 
597
 
598
  if __name__ == "__main__":
599
  demo.queue(max_size=None, default_concurrency_limit=None)
600
+ demo.launch()