aiart-proxy1 / app.py
lucky0146's picture
Upload 3 files
9c51c49 verified
from flask import Flask, request, jsonify, Response
import requests
import os
app = Flask(__name__)
@app.route('/', methods=['GET'])
def home():
return "Proxy API is running! Use /api/generate endpoint for image generation."
@app.route('/api/generate', methods=['POST'])
def proxy_generate():
try:
# Get the data from the request
data = request.json
# Forward the request to the actual API
response = requests.post(
"https://aiart-zroo.onrender.com/api/generate",
headers={"Content-Type": "application/json"},
json=data,
timeout=60 # Set a reasonable timeout
)
# If successful, modify the response to use our proxy for the image
if response.status_code == 200:
try:
result = response.json()
if 'image_url' in result:
# Get the original image filename
original_url = result['image_url']
filename = original_url.split('/')[-1]
# Replace the image URL with our proxy URL
proxy_url = f"/proxy-image/{filename}"
result['original_image_url'] = original_url
result['image_url'] = proxy_url
return jsonify(result)
except:
pass
# Return the response from the API
return response.content, response.status_code, {'Content-Type': response.headers.get('Content-Type', 'application/json')}
except Exception as e:
return jsonify({"error": str(e)}), 500
# Add an image proxy endpoint
@app.route('/proxy-image/<filename>', methods=['GET'])
def proxy_image(filename):
try:
# Construct the original URL
original_url = f"https://aiart-zroo.onrender.com/images/{filename}"
# Get the image with stream=True to handle binary data properly
response = requests.get(original_url, stream=True)
# Return the image data with explicit content type
return Response(
response.raw.read(), # Use raw.read() for binary data
status=response.status_code,
content_type='image/png', # Force content type to image/png
headers={
'Cache-Control': 'no-cache',
'Content-Disposition': f'inline; filename={filename}'
}
)
except Exception as e:
return jsonify({"error": str(e)}), 500
#new
if __name__ == '__main__':
# Get port from environment variable or use 7860 as default
port = int(os.environ.get('PORT', 7860))
app.run(host='0.0.0.0', port=port)