|
from flask import Flask, request, jsonify, send_file |
|
from flask_cors import CORS |
|
import os |
|
from huggingface_hub import InferenceClient |
|
from io import BytesIO |
|
from PIL import Image |
|
|
|
|
|
myapp = Flask(__name__) |
|
CORS(myapp) |
|
|
|
|
|
HF_TOKEN = os.environ.get("HF_TOKEN") |
|
client = InferenceClient(token=HF_TOKEN) |
|
|
|
@myapp.route('/') |
|
def home(): |
|
return "Welcome to the Image Background Remover!" |
|
|
|
|
|
def generate_image(prompt, seed=1, model="prompthero/openjourney-v4"): |
|
try: |
|
|
|
result_image = client.text_to_image(prompt=prompt, seed=seed, model=model) |
|
return result_image |
|
except Exception as e: |
|
print(f"Error generating image: {str(e)}") |
|
return None |
|
|
|
|
|
@myapp.route('/generate_image', methods=['POST']) |
|
def generate_api(): |
|
data = request.get_json() |
|
|
|
|
|
prompt = data.get('prompt', '') |
|
seed = data.get('seed', 1) |
|
model_name = data.get('model', 'prompthero/openjourney-v4') |
|
|
|
if not prompt: |
|
return jsonify({"error": "Prompt is required"}), 400 |
|
|
|
try: |
|
|
|
image = generate_image(prompt, seed, model_name) |
|
|
|
if image: |
|
|
|
image_bytes = BytesIO() |
|
image.save(image_bytes, format='PNG') |
|
image_bytes.seek(0) |
|
|
|
|
|
return send_file(image_bytes, mimetype='image/png', as_attachment=True, download_name='generated_image.png') |
|
else: |
|
return jsonify({"error": "Failed to generate image"}), 500 |
|
except Exception as e: |
|
print(f"Error in generate_api: {str(e)}") |
|
return jsonify({"error": str(e)}), 500 |
|
|
|
|
|
if __name__ == "__main__": |
|
myapp.run(host='0.0.0.0', port=7860) |