File size: 7,488 Bytes
3ebc13c
 
 
 
 
 
 
 
 
 
 
 
cd03e33
3ebc13c
 
 
 
 
 
 
 
 
 
 
 
9d517d5
3ebc13c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36a2325
3ebc13c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dea28b2
8959c8c
406b0be
8959c8c
 
 
2a5fb89
8959c8c
3ebc13c
 
 
cd03e33
3ebc13c
 
 
8959c8c
 
 
3ebc13c
 
 
 
 
8959c8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6785c69
3ebc13c
 
 
 
526124b
81244e1
6188830
81244e1
3ebc13c
36a2325
909987e
81244e1
8959c8c
3ebc13c
d6e1aa5
3ebc13c
 
 
 
8959c8c
3ebc13c
 
4921ea7
3ebc13c
 
 
 
 
 
0ab732a
 
2c56a67
3ebc13c
 
9d517d5
3ebc13c
 
 
 
 
6188830
9d517d5
20b640e
3ebc13c
 
4921ea7
3ebc13c
 
0ab732a
b0e48f4
 
909987e
b0e48f4
9d517d5
d947f14
 
b0e48f4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
# import gradio as gr
# import requests
# import base64
# from PIL import Image
# import io

# gr.set_page_config(page_title="AI Image Detector", page_icon="🔍")

# gr.title("AI Image Detector")
# gr.write("Upload an image to check if it's AI-generated")


# api_key = NVIDIA_API_KEY
# gr.session_state.api_key = api_key

# def process_image(image_bytes, api_key):
#     header_auth = f"Bearer {api_key}"
#     invoke_url = "https://ai.api.nvidia.com/v1/cv/hive/ai-generated-image-detection"
    
#     # Convert image bytes to base64
#     image_b64 = base64.b64encode(image_bytes).decode()
    
#     payload = {
#         "input": [f"data:image/png;base64,{image_b64}"]
#     }

#     headers = {
#         "Content-Type": "application/json",
#         "Authorization": header_auth,
#         "Accept": "application/json",
#     }
    
#     try:
#         response = requests.post(invoke_url, headers=headers, json=payload)
#         response.raise_for_status()
#         result = response.json()
        
#         # Check if response contains the expected structure
#         if 'data' in result and len(result['data']) > 0:
#             first_result = result['data'][0]
#             if 'is_ai_generated' in first_result:
#                 return {
#                     'confidence': first_result['is_ai_generated'],
#                     'sources': first_result.get('possible_sources', {}),
#                     'status': first_result.get('status', 'UNKNOWN')
#                 }
        
#         gr.error("Unexpected response format from API")
#         return None
            
#     except requests.exceptions.RequestException as e:
#         gr.error(f"Error processing image: {str(e)}")
#         return None

# # File uploader
# uploaded_file = gr.file_uploader("Choose an image...", type=['png', 'jpg', 'jpeg'])

# if uploaded_file is not None and api_key:
#     # Display the uploaded image
#     image = Image.open(uploaded_file)
#     gr.image(image, caption="Uploaded Image", use_container_width=True)
    
#     # Convert image to bytes
#     img_byte_arr = io.BytesIO()
#     image.save(img_byte_arr, format=image.format)
#     img_byte_arr = img_byte_arr.getvalue()
    
#     # Process the image
#     with gr.spinner("Analyzing image..."):

#         result = process_image(img_byte_arr, api_key)
        
#         if result and result['status'] == 'SUCCESS':
#             confidence = result['confidence']
#             sources = result['sources']
            
#             gr.write("---")
#             gr.write("### Result")
            
#             # Determine if image is AI-generated (using 50% threshold)
#             is_ai_generated = "Yes" if confidence >= 0.5 else "No"
            
#             # Display result with appropriate styling
#             if is_ai_generated == "Yes":
#                 gr.error(f"Is this image AI-generated? **{is_ai_generated}**")
                
#                 # Show top 3 possible sources if AI-generated
#                 if sources:
#                     gr.write("Top possible AI models used:")
#                     sorted_sources = sorted(sources.items(), key=lambda x: x[1], reverse=True)[:3]
#                     for source, prob in sorted_sources:
#                         if prob > 0.01:  # Only show sources with >1% probability
#                             gr.write(f"- {source}: {prob:.1%}")
#             else:
#                 gr.success(f"Is this image AI-generated? **{is_ai_generated}**")
            
#             # Show confidence score in smaller text
#             gr.caption(f"Confidence score: {confidence:.2%}")

# elif not api_key and uploaded_file is not None:
#     gr.warning("Please enter your NVIDIA API key first")

# # Add footer with instructions
# gr.markdown("---")
# gr.markdown("""
# ---
# ### How to use:

# 1. Upload an image (PNG, JPG, or JPEG)
# 2. Wait for the analysis result
# 3. Get a ** Yes/No ** answer based on whether the image is AI-generated

# """)

import gradio as gr
import requests

import base64
from PIL import Image
import io
import os

def process_image(image):
    """Process the uploaded image using NVIDIA's AI detection API"""
    # Get API key from environment variable for security
    api_key = os.getenv('NVIDIA_API_KEY')
    if not api_key:
        raise ValueError("NVIDIA API key not found in environment variables")
    
    header_auth = f"Bearer {api_key}"
    invoke_url = "https://ai.api.nvidia.com/v1/cv/hive/ai-generated-image-detection"
    
    # Convert PIL Image to bytes
    img_byte_arr = io.BytesIO()
    image.save(img_byte_arr, format='PNG')
    image_bytes = img_byte_arr.getvalue()
    
    # Convert image bytes to base64
    image_b64 = base64.b64encode(image_bytes).decode()
    
    payload = {
        "input": [f"data:image/png;base64,{image_b64}"]
    }
    headers = {
        "Content-Type": "application/json",
        "Authorization": header_auth,
        "Accept": "application/json",
    }
    
    try:
        response = requests.post(invoke_url, headers=headers, json=payload)
        response.raise_for_status()
        result = response.json()
        
        if 'data' in result and len(result['data']) > 0:
            first_result = result['data'][0]
            if 'is_ai_generated' in first_result:
                confidence = first_result['is_ai_generated']
                sources = first_result.get('possible_sources', {})
                
                # Format the result message
                is_ai_generated = "<span style='color:red'>### Yes</span>" if confidence >= 0.5 else "<span style='color:green'>### No</span>"
                result_message = f"\n ### Is this image AI-generated? {is_ai_generated}\n"
                result_message += f"\n Confidence score: {confidence:.2%}\n\n"

                if is_ai_generated == "Yes" and sources:
                    result_message += "\n **Top possible AI models used** :\n"
                    sorted_sources = sorted(sources
                    .items(), key=lambda x: x[1], reverse=True)[:3]
                    for source, prob in sorted_sources:
                        if prob > 0.01:
                            result_message += f"- {source}: {prob:.1%}\n"
                
                return image, result_message
                
        return image, "Error: Unable to process image analysis results"
            
    except requests.exceptions.RequestException as e:
        return image, f"Error processing image: {str(e)}"

def create_demo():
    """Create and return the Gradio interface"""
    demo = gr.Interface(
        fn=process_image,
        inputs=gr.Image(type="pil", label="Upload Image"),
        outputs=[
            gr.Image(type="pil", label="Analyzed Image"
),
            gr.Markdown(label=" ## Analysis Results")
        ],
        title="AI Image Detector",
        
        description="Upload an image to check if it's AI-generated",
        article="""
        ### How to use:
        1. Upload an image (PNG, JPG, or JPEG)
        2. Click the 'Submit' button
        3. Get a detailed analysis of whether the image is AI-generated alongside the Model that might be used in generation.
        """,
        css=".footer {display: none;}"
    )
    return demo

# Create and launch the application
if __name__ == "__main__":
    demo= create_demo()
    demo.launch(
        show_api=False,
        show_error=False,
        share=False,
        quiet=True
        
        
    )