Geek7 commited on
Commit
19db560
1 Parent(s): a9dbd06

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +81 -36
app.py CHANGED
@@ -1,38 +1,83 @@
1
- import gradio as gr
 
 
2
  from huggingface_hub import InferenceClient
 
3
  from PIL import Image
4
- import io
5
-
6
- # Initialize the Inference Client
7
- client = InferenceClient()
8
-
9
- # Function to handle the image generation
10
- def generate_image(image, prompt):
11
- # Open the uploaded image
12
- image = Image.open(image)
13
-
14
- # Generate image using the InferenceClient
15
- generated_image = client.image_to_image(image, prompt=prompt)
16
-
17
- # Save generated image to a BytesIO object
18
- img_byte_arr = io.BytesIO()
19
- generated_image.save(img_byte_arr, format='PNG')
20
- img_byte_arr.seek(0) # Move the cursor to the beginning
21
-
22
- # Return the generated image
23
- return generated_image
24
-
25
- # Create Gradio interface
26
- iface = gr.Interface(
27
- fn=generate_image,
28
- inputs=[
29
- gr.inputs.Image(type="file", label="Input Image"), # File input for uploaded image
30
- gr.inputs.Textbox(label="Prompt") # Textbox for the prompt
31
- ],
32
- outputs=gr.outputs.Image(type="pil", label="Generated Image"), # Output as PIL image
33
- title="Image Generation with Hugging Face",
34
- description="Upload an image and provide a prompt to generate a new image."
35
- )
36
-
37
- # Launch the Gradio interface
38
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, jsonify, send_file
2
+ from flask_cors import CORS
3
+ import os
4
  from huggingface_hub import InferenceClient
5
+ from io import BytesIO
6
  from PIL import Image
7
+
8
+ # Initialize the Flask app
9
+ app = Flask(__name__)
10
+ CORS(app) # Enable CORS for all routes
11
+
12
+ # Initialize the InferenceClient with your Hugging Face token
13
+ HF_TOKEN = os.environ.get("HF_TOKEN") # Ensure to set your Hugging Face token in the environment
14
+ client = InferenceClient(token=HF_TOKEN)
15
+
16
+ @app.route('/')
17
+ def home():
18
+ return "Welcome to the Image Background Remover!"
19
+
20
+
21
+ # Function to generate an image from a text prompt
22
+ def generate_image(prompt, negative_prompt=None, height=512, width=512, model="stabilityai/stable-diffusion-2-1", num_inference_steps=50, guidance_scale=7.5, seed=None):
23
+ try:
24
+ # Generate the image using Hugging Face's inference API with additional parameters
25
+ image = client.text_to_image(
26
+ prompt=prompt,
27
+ negative_prompt=negative_prompt,
28
+ height=height,
29
+ width=width,
30
+ model=model,
31
+ num_inference_steps=num_inference_steps, # Control the number of inference steps
32
+ guidance_scale=guidance_scale, # Control the guidance scale
33
+ seed=seed # Control the seed for reproducibility
34
+ )
35
+ return image # Return the generated image
36
+ except Exception as e:
37
+ print(f"Error generating image: {str(e)}")
38
+ return None
39
+
40
+ # Flask route for the API endpoint to generate an image
41
+ @app.route('/generate_image', methods=['POST'])
42
+ def generate_api():
43
+ data = request.get_json()
44
+
45
+ # Extract required fields from the request
46
+ prompt = data.get('prompt', '')
47
+ negative_prompt = data.get('negative_prompt', None)
48
+ height = data.get('height', 1024) # Default height
49
+ width = data.get('width', 720) # Default width
50
+ num_inference_steps = data.get('num_inference_steps', 50) # Default number of inference steps
51
+ guidance_scale = data.get('guidance_scale', 7.5) # Default guidance scale
52
+ model_name = data.get('model', 'stabilityai/stable-diffusion-2-1') # Default model
53
+ seed = data.get('seed', None) # Seed for reproducibility, default is None
54
+
55
+ if not prompt:
56
+ return jsonify({"error": "Prompt is required"}), 400
57
+
58
+ try:
59
+ # Call the generate_image function with the provided parameters
60
+ image = generate_image(prompt, negative_prompt, height, width, model_name, num_inference_steps, guidance_scale, seed)
61
+
62
+ if image:
63
+ # Save the image to a BytesIO object
64
+ img_byte_arr = BytesIO()
65
+ image.save(img_byte_arr, format='PNG') # Convert the image to PNG
66
+ img_byte_arr.seek(0) # Move to the start of the byte stream
67
+
68
+ # Send the generated image as a response
69
+ return send_file(
70
+ img_byte_arr,
71
+ mimetype='image/png',
72
+ as_attachment=False, # Send the file as an attachment
73
+ download_name='generated_image.png' # The file name for download
74
+ )
75
+ else:
76
+ return jsonify({"error": "Failed to generate image"}), 500
77
+ except Exception as e:
78
+ print(f"Error in generate_api: {str(e)}") # Log the error
79
+ return jsonify({"error": str(e)}), 500
80
+
81
+ # Add this block to make sure your app runs when called
82
+ if __name__ == "__main__":
83
+ app.run(host='0.0.0.0', port=7860) # Run directly if needed for testing