openfree commited on
Commit
047bc32
Β·
verified Β·
1 Parent(s): f457b8d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -28
app.py CHANGED
@@ -5,6 +5,8 @@ from PIL import Image
5
  import requests
6
  from io import BytesIO
7
  import time
 
 
8
 
9
  # Set up Replicate API key from environment variable
10
  os.environ['REPLICATE_API_TOKEN'] = os.getenv('REPLICATE_API_TOKEN')
@@ -21,44 +23,85 @@ def process_images(prompt, image1, image2=None):
21
  return None, "⚠️ Please set REPLICATE_API_TOKEN environment variable"
22
 
23
  try:
24
- # Prepare input images list
 
 
 
25
  image_inputs = []
26
 
27
- # Convert PIL images to temporary files or use file paths
28
- # Note: In production, you'd upload these to a cloud service
29
- # For this example, we'll assume the images are accessible via URLs
30
- # You may need to upload them to a service like Cloudinary or S3 first
 
 
 
 
31
 
32
- # This is a placeholder - in real implementation, you'd need to:
33
- # 1. Save images temporarily
34
- # 2. Upload to a cloud service
35
- # 3. Get the URLs
 
 
 
 
36
 
37
  status_message = "🎨 Processing your images..."
38
 
39
- # Prepare input for Replicate
40
- input_data = {
41
- "prompt": prompt,
42
- "image_input": image_inputs # This should contain actual URLs
43
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
- # Run the model
46
- output = replicate.run(
47
- "google/nano-banana", # Replace with actual model
48
- input=input_data
49
- )
50
 
51
- # Get the output URL
52
- if hasattr(output, 'url'):
 
 
 
 
 
 
53
  output_url = output.url()
54
- else:
55
- output_url = str(output)
 
 
 
 
 
 
 
56
 
57
  # Download and return the generated image
58
  response = requests.get(output_url)
59
- img = Image.open(BytesIO(response.content))
60
-
61
- return img, "βœ… Image generated successfully!"
 
 
62
 
63
  except Exception as e:
64
  return None, f"❌ Error: {str(e)}"
@@ -201,10 +244,16 @@ with gr.Blocks(css=css, theme=gr.themes.Soft()) as demo:
201
  pip install gradio replicate pillow requests
202
  ```
203
 
204
- 3. **Note:** For production use, you'll need to:
 
 
 
 
 
 
205
  - Implement proper image upload to cloud storage (S3, Cloudinary, etc.)
206
- - Replace the model name with the actual Replicate model you want to use
207
  - Add proper error handling and rate limiting
 
208
 
209
  ### πŸ”’ Security:
210
  - API keys are managed through environment variables
 
5
  import requests
6
  from io import BytesIO
7
  import time
8
+ import tempfile
9
+ import base64
10
 
11
  # Set up Replicate API key from environment variable
12
  os.environ['REPLICATE_API_TOKEN'] = os.getenv('REPLICATE_API_TOKEN')
 
23
  return None, "⚠️ Please set REPLICATE_API_TOKEN environment variable"
24
 
25
  try:
26
+ import tempfile
27
+ import base64
28
+
29
+ # Save images temporarily and create data URIs
30
  image_inputs = []
31
 
32
+ # Process first image
33
+ with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as tmp1:
34
+ image1.save(tmp1.name)
35
+ with open(tmp1.name, 'rb') as f:
36
+ img_data = base64.b64encode(f.read()).decode()
37
+ # For some models, you might need data URI format
38
+ image_inputs.append(f"data:image/png;base64,{img_data}")
39
+ os.unlink(tmp1.name) # Clean up temp file
40
 
41
+ # Process second image if provided
42
+ if image2:
43
+ with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as tmp2:
44
+ image2.save(tmp2.name)
45
+ with open(tmp2.name, 'rb') as f:
46
+ img_data = base64.b64encode(f.read()).decode()
47
+ image_inputs.append(f"data:image/png;base64,{img_data}")
48
+ os.unlink(tmp2.name)
49
 
50
  status_message = "🎨 Processing your images..."
51
 
52
+ # Example using a real Replicate model (stable-diffusion)
53
+ # You should replace this with your actual model
54
+ try:
55
+ # For image-to-image models, use something like:
56
+ output = replicate.run(
57
+ "stability-ai/stable-diffusion:db21e45d3f7023abc2a46ee38a23973f6dce16bb082a930b0c49861f96d1e5bf",
58
+ input={
59
+ "prompt": prompt,
60
+ "image": image_inputs[0] if image_inputs else None,
61
+ "num_outputs": 1,
62
+ "guidance_scale": 7.5,
63
+ "num_inference_steps": 50
64
+ }
65
+ )
66
+ except:
67
+ # Fallback to a simpler text-to-image if image input fails
68
+ output = replicate.run(
69
+ "stability-ai/stable-diffusion:db21e45d3f7023abc2a46ee38a23973f6dce16bb082a930b0c49861f96d1e5bf",
70
+ input={
71
+ "prompt": prompt,
72
+ "num_outputs": 1
73
+ }
74
+ )
75
 
76
+ # Handle different output formats
77
+ output_url = None
 
 
 
78
 
79
+ if isinstance(output, list) and len(output) > 0:
80
+ # If output is a list, take the first item
81
+ output_url = output[0]
82
+ elif isinstance(output, str):
83
+ # If output is already a string URL
84
+ output_url = output
85
+ elif hasattr(output, 'url'):
86
+ # If output has a url method
87
  output_url = output.url()
88
+ elif hasattr(output, '__iter__'):
89
+ # If output is iterable, try to get first item
90
+ try:
91
+ output_url = next(iter(output))
92
+ except:
93
+ pass
94
+
95
+ if not output_url:
96
+ return None, "❌ Error: No image content found in response"
97
 
98
  # Download and return the generated image
99
  response = requests.get(output_url)
100
+ if response.status_code == 200:
101
+ img = Image.open(BytesIO(response.content))
102
+ return img, "βœ… Image generated successfully!"
103
+ else:
104
+ return None, f"❌ Error: Failed to download image (Status: {response.status_code})"
105
 
106
  except Exception as e:
107
  return None, f"❌ Error: {str(e)}"
 
244
  pip install gradio replicate pillow requests
245
  ```
246
 
247
+ 3. **Available Models to Try:**
248
+ - `stability-ai/stable-diffusion` - Text to image generation
249
+ - `jagilley/controlnet-canny` - Image style transfer with edge detection
250
+ - `rossjillian/controlnet` - Image controlled generation
251
+ - Replace the model in the code with your preferred model
252
+
253
+ 4. **Note:** For production use, you'll need to:
254
  - Implement proper image upload to cloud storage (S3, Cloudinary, etc.)
 
255
  - Add proper error handling and rate limiting
256
+ - Check the specific input format required by your chosen model
257
 
258
  ### πŸ”’ Security:
259
  - API keys are managed through environment variables