Update app.py
Browse files
app.py
CHANGED
|
@@ -5,12 +5,12 @@ from huggingface_hub import InferenceClient
|
|
| 5 |
from io import BytesIO
|
| 6 |
from PIL import Image
|
| 7 |
|
| 8 |
-
# Initialize Flask app
|
| 9 |
app = Flask(__name__)
|
| 10 |
CORS(app) # Enable CORS for all routes
|
| 11 |
|
| 12 |
-
# Initialize the InferenceClient with Hugging Face token
|
| 13 |
-
HF_TOKEN = os.environ.get("HF_TOKEN") #
|
| 14 |
client = InferenceClient(token=HF_TOKEN)
|
| 15 |
|
| 16 |
# Hardcoded negative prompt
|
|
@@ -21,48 +21,36 @@ blurry hands, disproportionate fingers"""
|
|
| 21 |
|
| 22 |
@app.route('/')
|
| 23 |
def home():
|
| 24 |
-
return "Welcome to the
|
| 25 |
|
| 26 |
-
#
|
| 27 |
-
def
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
# Send the image to Hugging Face for NSFW classification
|
| 35 |
-
result = client.image_classification(model="Falconsai/nsfw_image_detection", inputs=img_byte_arr.getvalue())
|
| 36 |
-
|
| 37 |
-
# Check if any prediction is NSFW with high confidence
|
| 38 |
-
for item in result:
|
| 39 |
-
if item['label'].lower() == 'nsfw' and item['score'] > 0.5:
|
| 40 |
-
return True
|
| 41 |
-
return False
|
| 42 |
-
except Exception as e:
|
| 43 |
-
print(f"NSFW detection error: {e}")
|
| 44 |
-
return False
|
| 45 |
|
| 46 |
-
# Function to generate an image
|
| 47 |
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):
|
| 48 |
try:
|
| 49 |
-
# Generate the image using Hugging Face's API
|
| 50 |
image = client.text_to_image(
|
| 51 |
-
prompt=prompt,
|
| 52 |
-
negative_prompt=
|
| 53 |
-
height=height,
|
| 54 |
-
width=width,
|
| 55 |
model=model,
|
| 56 |
-
num_inference_steps=num_inference_steps,
|
| 57 |
-
guidance_scale=guidance_scale,
|
| 58 |
-
seed=seed
|
| 59 |
)
|
| 60 |
-
return image
|
| 61 |
except Exception as e:
|
| 62 |
-
print(f"Error generating image: {e}")
|
| 63 |
return None
|
| 64 |
|
| 65 |
-
# Flask route for
|
| 66 |
@app.route('/generate_image', methods=['POST'])
|
| 67 |
def generate_api():
|
| 68 |
data = request.get_json()
|
|
@@ -70,48 +58,49 @@ def generate_api():
|
|
| 70 |
# Extract required fields from the request
|
| 71 |
prompt = data.get('prompt', '')
|
| 72 |
negative_prompt = data.get('negative_prompt', None)
|
| 73 |
-
height = data.get('height',
|
| 74 |
-
width = data.get('width',
|
| 75 |
-
num_inference_steps = data.get('num_inference_steps', 50)
|
| 76 |
-
guidance_scale = data.get('guidance_scale', 7.5)
|
| 77 |
-
model_name = data.get('model', 'stabilityai/stable-diffusion-2-1')
|
| 78 |
-
seed = data.get('seed', None)
|
| 79 |
|
| 80 |
if not prompt:
|
| 81 |
return jsonify({"error": "Prompt is required"}), 400
|
| 82 |
|
| 83 |
try:
|
| 84 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
image = generate_image(prompt, negative_prompt, height, width, model_name, num_inference_steps, guidance_scale, seed)
|
| 86 |
|
| 87 |
if image:
|
| 88 |
-
# Check for NSFW content
|
| 89 |
-
if is_nsfw_image(image):
|
| 90 |
-
return send_file(
|
| 91 |
-
"nsfw.jpg", # Path to your predefined NSFW placeholder image
|
| 92 |
-
mimetype='image/jpeg',
|
| 93 |
-
as_attachment=False,
|
| 94 |
-
download_name='nsfw.jpg'
|
| 95 |
-
)
|
| 96 |
-
|
| 97 |
# Save the image to a BytesIO object
|
| 98 |
img_byte_arr = BytesIO()
|
| 99 |
-
image.save(img_byte_arr, format='PNG')
|
| 100 |
-
img_byte_arr.seek(0)
|
| 101 |
|
| 102 |
-
# Send the generated image
|
| 103 |
return send_file(
|
| 104 |
-
img_byte_arr,
|
| 105 |
-
mimetype='image/png',
|
| 106 |
-
as_attachment=False,
|
| 107 |
-
download_name='generated_image.png'
|
| 108 |
)
|
| 109 |
else:
|
| 110 |
return jsonify({"error": "Failed to generate image"}), 500
|
| 111 |
except Exception as e:
|
| 112 |
-
print(f"Error in generate_api: {e}")
|
| 113 |
return jsonify({"error": str(e)}), 500
|
| 114 |
|
| 115 |
-
#
|
| 116 |
-
if __name__ ==
|
| 117 |
-
app.run(host='0.0.0.0', port=7860)
|
|
|
|
| 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 |
# Hardcoded negative prompt
|
|
|
|
| 21 |
|
| 22 |
@app.route('/')
|
| 23 |
def home():
|
| 24 |
+
return "Welcome to the Image Background Remover!"
|
| 25 |
|
| 26 |
+
# Simple content moderation function
|
| 27 |
+
def is_prompt_explicit(prompt):
|
| 28 |
+
explicit_keywords = ["sexual", "nudity", "erotic", "explicit", "porn", "pornographic", "xxx", "hentai", "fetish", "sex", "sensual", "nude", "strip", "stripping", "adult", "lewd", "provocative", "obscene", "vulgar", "intimacy", "intimate", "lust", "arouse", "seductive", "seduction", "kinky", "bdsm", "dominatrix", "bondage", "hardcore", "softcore", "topless", "bottomless", "threesome", "orgy", "incest", "taboo", "masturbation", "genital", "penis", "vagina", "breast", "boob", "nipple", "butt", "anal", "oral", "ejaculation", "climax", "moan", "foreplay", "intercourse", "naked", "exposed", "suicide", "self-harm", "overdose", "poison", "hang", "end life", "kill myself", "noose", "depression", "hopeless", "worthless", "die", "death", "harm myself"] # Add more keywords as needed
|
| 29 |
+
for keyword in explicit_keywords:
|
| 30 |
+
if keyword.lower() in prompt.lower():
|
| 31 |
+
return True
|
| 32 |
+
return False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
+
# Function to generate an image from a text prompt
|
| 35 |
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):
|
| 36 |
try:
|
| 37 |
+
# Generate the image using Hugging Face's inference API with additional parameters
|
| 38 |
image = client.text_to_image(
|
| 39 |
+
prompt=prompt,
|
| 40 |
+
negative_prompt=NEGATIVE_PROMPT_FINGERS,
|
| 41 |
+
height=height,
|
| 42 |
+
width=width,
|
| 43 |
model=model,
|
| 44 |
+
num_inference_steps=num_inference_steps, # Control the number of inference steps
|
| 45 |
+
guidance_scale=guidance_scale, # Control the guidance scale
|
| 46 |
+
seed=seed # Control the seed for reproducibility
|
| 47 |
)
|
| 48 |
+
return image # Return the generated image
|
| 49 |
except Exception as e:
|
| 50 |
+
print(f"Error generating image: {str(e)}")
|
| 51 |
return None
|
| 52 |
|
| 53 |
+
# Flask route for the API endpoint to generate an image
|
| 54 |
@app.route('/generate_image', methods=['POST'])
|
| 55 |
def generate_api():
|
| 56 |
data = request.get_json()
|
|
|
|
| 58 |
# Extract required fields from the request
|
| 59 |
prompt = data.get('prompt', '')
|
| 60 |
negative_prompt = data.get('negative_prompt', None)
|
| 61 |
+
height = data.get('height', 1024) # Default height
|
| 62 |
+
width = data.get('width', 720) # Default width
|
| 63 |
+
num_inference_steps = data.get('num_inference_steps', 50) # Default number of inference steps
|
| 64 |
+
guidance_scale = data.get('guidance_scale', 7.5) # Default guidance scale
|
| 65 |
+
model_name = data.get('model', 'stabilityai/stable-diffusion-2-1') # Default model
|
| 66 |
+
seed = data.get('seed', None) # Seed for reproducibility, default is None
|
| 67 |
|
| 68 |
if not prompt:
|
| 69 |
return jsonify({"error": "Prompt is required"}), 400
|
| 70 |
|
| 71 |
try:
|
| 72 |
+
# Check for explicit content
|
| 73 |
+
if is_prompt_explicit(prompt):
|
| 74 |
+
# Return the pre-defined "thinkgood.png" image
|
| 75 |
+
return send_file(
|
| 76 |
+
"nsfw.jpg",
|
| 77 |
+
mimetype='image/png',
|
| 78 |
+
as_attachment=False,
|
| 79 |
+
download_name='thinkgood.png'
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
# Call the generate_image function with the provided parameters
|
| 83 |
image = generate_image(prompt, negative_prompt, height, width, model_name, num_inference_steps, guidance_scale, seed)
|
| 84 |
|
| 85 |
if image:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
# Save the image to a BytesIO object
|
| 87 |
img_byte_arr = BytesIO()
|
| 88 |
+
image.save(img_byte_arr, format='PNG') # Convert the image to PNG
|
| 89 |
+
img_byte_arr.seek(0) # Move to the start of the byte stream
|
| 90 |
|
| 91 |
+
# Send the generated image as a response
|
| 92 |
return send_file(
|
| 93 |
+
img_byte_arr,
|
| 94 |
+
mimetype='image/png',
|
| 95 |
+
as_attachment=False, # Send the file as an attachment
|
| 96 |
+
download_name='generated_image.png' # The file name for download
|
| 97 |
)
|
| 98 |
else:
|
| 99 |
return jsonify({"error": "Failed to generate image"}), 500
|
| 100 |
except Exception as e:
|
| 101 |
+
print(f"Error in generate_api: {str(e)}") # Log the error
|
| 102 |
return jsonify({"error": str(e)}), 500
|
| 103 |
|
| 104 |
+
# Add this block to make sure your app runs when called
|
| 105 |
+
if __name__ == "__main__":
|
| 106 |
+
app.run(host='0.0.0.0', port=7860) # Run directly if needed for testing
|