Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,22 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
import requests
|
3 |
import base64
|
4 |
from PIL import Image
|
5 |
import io
|
6 |
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
gr.session_state.api_key = api_key
|
15 |
-
|
16 |
-
def process_image(image_bytes, api_key):
|
17 |
header_auth = f"Bearer {api_key}"
|
18 |
invoke_url = "https://ai.api.nvidia.com/v1/cv/hive/ai-generated-image-detection"
|
19 |
|
|
|
|
|
|
|
|
|
|
|
20 |
# Convert image bytes to base64
|
21 |
image_b64 = base64.b64encode(image_bytes).decode()
|
22 |
|
@@ -34,78 +148,54 @@ def process_image(image_bytes, api_key):
|
|
34 |
response.raise_for_status()
|
35 |
result = response.json()
|
36 |
|
37 |
-
# Check if response contains the expected structure
|
38 |
if 'data' in result and len(result['data']) > 0:
|
39 |
first_result = result['data'][0]
|
40 |
if 'is_ai_generated' in first_result:
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
return None
|
49 |
-
|
50 |
-
except requests.exceptions.RequestException as e:
|
51 |
-
gr.error(f"Error processing image: {str(e)}")
|
52 |
-
return None
|
53 |
-
|
54 |
-
# File uploader
|
55 |
-
uploaded_file = gr.file_uploader("Choose an image...", type=['png', 'jpg', 'jpeg'])
|
56 |
-
|
57 |
-
if uploaded_file is not None and api_key:
|
58 |
-
# Display the uploaded image
|
59 |
-
image = Image.open(uploaded_file)
|
60 |
-
gr.image(image, caption="Uploaded Image", use_container_width=True)
|
61 |
-
|
62 |
-
# Convert image to bytes
|
63 |
-
img_byte_arr = io.BytesIO()
|
64 |
-
image.save(img_byte_arr, format=image.format)
|
65 |
-
img_byte_arr = img_byte_arr.getvalue()
|
66 |
-
|
67 |
-
# Process the image
|
68 |
-
with gr.spinner("Analyzing image..."):
|
69 |
-
result = process_image(img_byte_arr, api_key)
|
70 |
-
|
71 |
-
if result and result['status'] == 'SUCCESS':
|
72 |
-
confidence = result['confidence']
|
73 |
-
sources = result['sources']
|
74 |
-
|
75 |
-
gr.write("---")
|
76 |
-
gr.write("### Result")
|
77 |
-
|
78 |
-
# Determine if image is AI-generated (using 50% threshold)
|
79 |
-
is_ai_generated = "Yes" if confidence >= 0.5 else "No"
|
80 |
-
|
81 |
-
# Display result with appropriate styling
|
82 |
-
if is_ai_generated == "Yes":
|
83 |
-
gr.error(f"Is this image AI-generated? **{is_ai_generated}**")
|
84 |
|
85 |
-
|
86 |
-
|
87 |
-
gr.write("Top possible AI models used:")
|
88 |
sorted_sources = sorted(sources.items(), key=lambda x: x[1], reverse=True)[:3]
|
89 |
for source, prob in sorted_sources:
|
90 |
-
if prob > 0.01:
|
91 |
-
|
92 |
-
|
93 |
-
|
|
|
|
|
94 |
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
elif not api_key and uploaded_file is not None:
|
99 |
-
gr.warning("Please enter your NVIDIA API key first")
|
100 |
-
|
101 |
-
# Add footer with instructions
|
102 |
-
gr.markdown("---")
|
103 |
-
gr.markdown("""
|
104 |
-
---
|
105 |
-
### How to use:
|
106 |
|
107 |
-
|
108 |
-
|
109 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
110 |
|
111 |
-
|
|
|
|
|
|
|
|
1 |
+
# import gradio as gr
|
2 |
+
# import requests
|
3 |
+
# import base64
|
4 |
+
# from PIL import Image
|
5 |
+
# import io
|
6 |
+
|
7 |
+
# gr.set_page_config(page_title="AI Image Detector", page_icon="🔍")
|
8 |
+
|
9 |
+
# gr.title("AI Image Detector")
|
10 |
+
# gr.write("Upload an image to check if it's AI-generated")
|
11 |
+
|
12 |
+
|
13 |
+
# api_key = "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"
|
14 |
+
# gr.session_state.api_key = api_key
|
15 |
+
|
16 |
+
# def process_image(image_bytes, api_key):
|
17 |
+
# header_auth = f"Bearer {api_key}"
|
18 |
+
# invoke_url = "https://ai.api.nvidia.com/v1/cv/hive/ai-generated-image-detection"
|
19 |
+
|
20 |
+
# # Convert image bytes to base64
|
21 |
+
# image_b64 = base64.b64encode(image_bytes).decode()
|
22 |
+
|
23 |
+
# payload = {
|
24 |
+
# "input": [f"data:image/png;base64,{image_b64}"]
|
25 |
+
# }
|
26 |
+
# headers = {
|
27 |
+
# "Content-Type": "application/json",
|
28 |
+
# "Authorization": header_auth,
|
29 |
+
# "Accept": "application/json",
|
30 |
+
# }
|
31 |
+
|
32 |
+
# try:
|
33 |
+
# response = requests.post(invoke_url, headers=headers, json=payload)
|
34 |
+
# response.raise_for_status()
|
35 |
+
# result = response.json()
|
36 |
+
|
37 |
+
# # Check if response contains the expected structure
|
38 |
+
# if 'data' in result and len(result['data']) > 0:
|
39 |
+
# first_result = result['data'][0]
|
40 |
+
# if 'is_ai_generated' in first_result:
|
41 |
+
# return {
|
42 |
+
# 'confidence': first_result['is_ai_generated'],
|
43 |
+
# 'sources': first_result.get('possible_sources', {}),
|
44 |
+
# 'status': first_result.get('status', 'UNKNOWN')
|
45 |
+
# }
|
46 |
+
|
47 |
+
# gr.error("Unexpected response format from API")
|
48 |
+
# return None
|
49 |
+
|
50 |
+
# except requests.exceptions.RequestException as e:
|
51 |
+
# gr.error(f"Error processing image: {str(e)}")
|
52 |
+
# return None
|
53 |
+
|
54 |
+
# # File uploader
|
55 |
+
# uploaded_file = gr.file_uploader("Choose an image...", type=['png', 'jpg', 'jpeg'])
|
56 |
+
|
57 |
+
# if uploaded_file is not None and api_key:
|
58 |
+
# # Display the uploaded image
|
59 |
+
# image = Image.open(uploaded_file)
|
60 |
+
# gr.image(image, caption="Uploaded Image", use_container_width=True)
|
61 |
+
|
62 |
+
# # Convert image to bytes
|
63 |
+
# img_byte_arr = io.BytesIO()
|
64 |
+
# image.save(img_byte_arr, format=image.format)
|
65 |
+
# img_byte_arr = img_byte_arr.getvalue()
|
66 |
+
|
67 |
+
# # Process the image
|
68 |
+
# with gr.spinner("Analyzing image..."):
|
69 |
+
# result = process_image(img_byte_arr, api_key)
|
70 |
+
|
71 |
+
# if result and result['status'] == 'SUCCESS':
|
72 |
+
# confidence = result['confidence']
|
73 |
+
# sources = result['sources']
|
74 |
+
|
75 |
+
# gr.write("---")
|
76 |
+
# gr.write("### Result")
|
77 |
+
|
78 |
+
# # Determine if image is AI-generated (using 50% threshold)
|
79 |
+
# is_ai_generated = "Yes" if confidence >= 0.5 else "No"
|
80 |
+
|
81 |
+
# # Display result with appropriate styling
|
82 |
+
# if is_ai_generated == "Yes":
|
83 |
+
# gr.error(f"Is this image AI-generated? **{is_ai_generated}**")
|
84 |
+
|
85 |
+
# # Show top 3 possible sources if AI-generated
|
86 |
+
# if sources:
|
87 |
+
# gr.write("Top possible AI models used:")
|
88 |
+
# sorted_sources = sorted(sources.items(), key=lambda x: x[1], reverse=True)[:3]
|
89 |
+
# for source, prob in sorted_sources:
|
90 |
+
# if prob > 0.01: # Only show sources with >1% probability
|
91 |
+
# gr.write(f"- {source}: {prob:.1%}")
|
92 |
+
# else:
|
93 |
+
# gr.success(f"Is this image AI-generated? **{is_ai_generated}**")
|
94 |
+
|
95 |
+
# # Show confidence score in smaller text
|
96 |
+
# gr.caption(f"Confidence score: {confidence:.2%}")
|
97 |
+
|
98 |
+
# elif not api_key and uploaded_file is not None:
|
99 |
+
# gr.warning("Please enter your NVIDIA API key first")
|
100 |
+
|
101 |
+
# # Add footer with instructions
|
102 |
+
# gr.markdown("---")
|
103 |
+
# gr.markdown("""
|
104 |
+
# ---
|
105 |
+
# ### How to use:
|
106 |
+
|
107 |
+
# 1. Upload an image (PNG, JPG, or JPEG)
|
108 |
+
# 2. Wait for the analysis result
|
109 |
+
# 3. Get a ** Yes/No ** answer based on whether the image is AI-generated
|
110 |
+
|
111 |
+
# """)
|
112 |
+
|
113 |
import gradio as gr
|
114 |
import requests
|
115 |
import base64
|
116 |
from PIL import Image
|
117 |
import io
|
118 |
|
119 |
+
def process_image(image):
|
120 |
+
"""Process the uploaded image using NVIDIA's AI detection API"""
|
121 |
+
# Get API key from environment variable for security
|
122 |
+
api_key = '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'
|
123 |
+
if not api_key:
|
124 |
+
raise ValueError("NVIDIA API key not found in environment variables")
|
125 |
+
|
|
|
|
|
|
|
126 |
header_auth = f"Bearer {api_key}"
|
127 |
invoke_url = "https://ai.api.nvidia.com/v1/cv/hive/ai-generated-image-detection"
|
128 |
|
129 |
+
# Convert PIL Image to bytes
|
130 |
+
img_byte_arr = io.BytesIO()
|
131 |
+
image.save(img_byte_arr, format='PNG')
|
132 |
+
image_bytes = img_byte_arr.getvalue()
|
133 |
+
|
134 |
# Convert image bytes to base64
|
135 |
image_b64 = base64.b64encode(image_bytes).decode()
|
136 |
|
|
|
148 |
response.raise_for_status()
|
149 |
result = response.json()
|
150 |
|
|
|
151 |
if 'data' in result and len(result['data']) > 0:
|
152 |
first_result = result['data'][0]
|
153 |
if 'is_ai_generated' in first_result:
|
154 |
+
confidence = first_result['is_ai_generated']
|
155 |
+
sources = first_result.get('possible_sources', {})
|
156 |
+
|
157 |
+
# Format the result message
|
158 |
+
is_ai_generated = "Yes" if confidence >= 0.5 else "No"
|
159 |
+
result_message = f"Is this image AI-generated? {is_ai_generated}\n"
|
160 |
+
result_message += f"Confidence score: {confidence:.2%}\n\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
161 |
|
162 |
+
if is_ai_generated == "Yes" and sources:
|
163 |
+
result_message += "Top possible AI models used:\n"
|
|
|
164 |
sorted_sources = sorted(sources.items(), key=lambda x: x[1], reverse=True)[:3]
|
165 |
for source, prob in sorted_sources:
|
166 |
+
if prob > 0.01:
|
167 |
+
result_message += f"- {source}: {prob:.1%}\n"
|
168 |
+
|
169 |
+
return image, result_message
|
170 |
+
|
171 |
+
return image, "Error: Unable to process image analysis results"
|
172 |
|
173 |
+
except requests.exceptions.RequestException as e:
|
174 |
+
return image, f"Error processing image: {str(e)}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
175 |
|
176 |
+
def create_demo():
|
177 |
+
"""Create and return the Gradio interface"""
|
178 |
+
demo = gr.Interface(
|
179 |
+
fn=process_image,
|
180 |
+
inputs=gr.Image(type="pil", label="Upload Image"),
|
181 |
+
outputs=[
|
182 |
+
gr.Image(type="pil", label="Analyzed Image"),
|
183 |
+
gr.Textbox(label="Analysis Results", lines=10)
|
184 |
+
],
|
185 |
+
title="AI Image Detector",
|
186 |
+
description="Upload an image to check if it's AI-generated",
|
187 |
+
article="""
|
188 |
+
### How to use:
|
189 |
+
1. Upload an image (PNG, JPG, or JPEG)
|
190 |
+
2. Click the 'Submit' button
|
191 |
+
3. Get a detailed analysis of whether the image is AI-generated
|
192 |
+
|
193 |
+
Note: This application requires a valid NVIDIA API key set in environment variables.
|
194 |
+
"""
|
195 |
+
)
|
196 |
+
return demo
|
197 |
|
198 |
+
# Create and launch the application
|
199 |
+
if __name__ == "__main__":
|
200 |
+
demo = create_demo()
|
201 |
+
demo.launch()
|