File size: 7,271 Bytes
3ebc13c
 
 
 
 
 
 
 
 
 
 
 
cd03e33
3ebc13c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dea28b2
8959c8c
 
 
 
 
3ebc13c
 
 
cd03e33
3ebc13c
 
 
8959c8c
 
 
3ebc13c
 
 
 
 
8959c8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ebc13c
 
 
 
 
 
 
8959c8c
3ebc13c
 
8959c8c
 
3ebc13c
 
 
 
 
 
8959c8c
3ebc13c
 
4921ea7
3ebc13c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4921ea7
3ebc13c
 
 
 
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
# 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

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 = "Yes" if confidence >= 0.5 else "No"
                result_message = f"Is this image AI-generated? {is_ai_generated}\n"
                result_message += f"Confidence score: {confidence:.2%}\n\n"
                
                if is_ai_generated == "Yes" and sources:
                    result_message += "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.Textbox(label="Analysis Results", lines=10)
        ],
        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
        
        Note: This application requires a valid NVIDIA API key set in environment variables.
        """
    )
    return demo

# Create and launch the application
if __name__ == "__main__":
    demo = create_demo()
    demo.launch()