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
|
9 |
app = Flask(__name__)
|
10 |
CORS(app) # Enable CORS for all routes
|
11 |
|
12 |
-
# Initialize the InferenceClient with
|
13 |
-
HF_TOKEN = os.environ.get("HF_TOKEN") #
|
14 |
client = InferenceClient(token=HF_TOKEN)
|
15 |
|
16 |
# Hardcoded negative prompt
|
@@ -21,54 +21,48 @@ blurry hands, disproportionate fingers"""
|
|
21 |
|
22 |
@app.route('/')
|
23 |
def home():
|
24 |
-
return "Welcome to the Image
|
25 |
|
26 |
-
#
|
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 |
-
# NSFW detection function using InferenceClient
|
35 |
def is_nsfw_image(image):
|
36 |
-
# Convert the image to bytes
|
37 |
-
img_byte_arr = BytesIO()
|
38 |
-
image.save(img_byte_arr, format='PNG')
|
39 |
-
img_byte_arr.seek(0)
|
40 |
-
|
41 |
-
# Send the image to the Hugging Face NSFW model
|
42 |
try:
|
43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
44 |
for item in result:
|
45 |
-
if item['label'] == 'nsfw' and item['score'] > 0.5:
|
46 |
return True
|
47 |
return False
|
48 |
except Exception as e:
|
49 |
-
print(f"
|
50 |
return False
|
51 |
|
52 |
-
# Function to generate an image
|
53 |
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):
|
54 |
try:
|
55 |
-
# Generate the image using Hugging Face's
|
56 |
image = client.text_to_image(
|
57 |
-
prompt=prompt,
|
58 |
-
negative_prompt=NEGATIVE_PROMPT_FINGERS,
|
59 |
-
height=height,
|
60 |
-
width=width,
|
61 |
model=model,
|
62 |
-
num_inference_steps=num_inference_steps,
|
63 |
-
guidance_scale=guidance_scale,
|
64 |
-
seed=seed
|
65 |
)
|
66 |
-
return image
|
67 |
except Exception as e:
|
68 |
-
print(f"Error generating image: {
|
69 |
return None
|
70 |
|
71 |
-
# Flask route for
|
72 |
@app.route('/generate_image', methods=['POST'])
|
73 |
def generate_api():
|
74 |
data = request.get_json()
|
@@ -76,26 +70,17 @@ def generate_api():
|
|
76 |
# Extract required fields from the request
|
77 |
prompt = data.get('prompt', '')
|
78 |
negative_prompt = data.get('negative_prompt', None)
|
79 |
-
height = data.get('height',
|
80 |
-
width = data.get('width',
|
81 |
-
num_inference_steps = data.get('num_inference_steps', 50)
|
82 |
-
guidance_scale = data.get('guidance_scale', 7.5)
|
83 |
-
model_name = data.get('model', 'stabilityai/stable-diffusion-2-1')
|
84 |
-
seed = data.get('seed', None)
|
85 |
|
86 |
if not prompt:
|
87 |
return jsonify({"error": "Prompt is required"}), 400
|
88 |
|
89 |
try:
|
90 |
-
# Check for explicit content
|
91 |
-
if is_prompt_explicit(prompt):
|
92 |
-
return send_file(
|
93 |
-
"thinkgood.jpeg",
|
94 |
-
mimetype='image/png',
|
95 |
-
as_attachment=False,
|
96 |
-
download_name='thinkgood.png'
|
97 |
-
)
|
98 |
-
|
99 |
# Generate the image
|
100 |
image = generate_image(prompt, negative_prompt, height, width, model_name, num_inference_steps, guidance_scale, seed)
|
101 |
|
@@ -103,30 +88,30 @@ def generate_api():
|
|
103 |
# Check for NSFW content
|
104 |
if is_nsfw_image(image):
|
105 |
return send_file(
|
106 |
-
"nsfw.jpg",
|
107 |
-
mimetype='image/jpeg',
|
108 |
-
as_attachment=False,
|
109 |
download_name='nsfw.jpg'
|
110 |
)
|
111 |
|
112 |
# Save the image to a BytesIO object
|
113 |
img_byte_arr = BytesIO()
|
114 |
-
image.save(img_byte_arr, format='PNG')
|
115 |
-
img_byte_arr.seek(0)
|
116 |
|
117 |
-
# Send the generated image
|
118 |
return send_file(
|
119 |
-
img_byte_arr,
|
120 |
-
mimetype='image/png',
|
121 |
-
as_attachment=False,
|
122 |
-
download_name='generated_image.png'
|
123 |
)
|
124 |
else:
|
125 |
return jsonify({"error": "Failed to generate image"}), 500
|
126 |
except Exception as e:
|
127 |
-
print(f"Error in generate_api: {
|
128 |
return jsonify({"error": str(e)}), 500
|
129 |
|
130 |
-
#
|
131 |
-
if __name__ ==
|
132 |
-
app.run(host='0.0.0.0', port=7860)
|
|
|
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") # Set your Hugging Face token in environment variables
|
14 |
client = InferenceClient(token=HF_TOKEN)
|
15 |
|
16 |
# Hardcoded negative prompt
|
|
|
21 |
|
22 |
@app.route('/')
|
23 |
def home():
|
24 |
+
return "Welcome to the AI Image Generator with NSFW Detection!"
|
25 |
|
26 |
+
# Function for NSFW detection
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
def is_nsfw_image(image):
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
try:
|
29 |
+
# Convert the image to bytes
|
30 |
+
img_byte_arr = BytesIO()
|
31 |
+
image.save(img_byte_arr, format='PNG')
|
32 |
+
img_byte_arr.seek(0)
|
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=negative_prompt or NEGATIVE_PROMPT_FINGERS,
|
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 image generation API
|
66 |
@app.route('/generate_image', methods=['POST'])
|
67 |
def generate_api():
|
68 |
data = request.get_json()
|
|
|
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', 512)
|
74 |
+
width = data.get('width', 512)
|
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 |
# Generate the image
|
85 |
image = generate_image(prompt, negative_prompt, height, width, model_name, num_inference_steps, guidance_scale, seed)
|
86 |
|
|
|
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 |
+
# Run the Flask app
|
116 |
+
if __name__ == '__main__':
|
117 |
+
app.run(host='0.0.0.0', port=7860)
|