renesistech/AIdetection
0
1import streamlit as st2import requests3import base644from PIL import Image5import io6 7st.set_page_config(page_title="AI Image Detector", page_icon="๐")8 9st.title("AI Image Detector")10st.write("Upload an image to check if it's AI-generated")11 12 13api_key = "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"14st.session_state.api_key = api_key15 16def 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 base6421 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 structure38 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 st.error("Unexpected response format from API")48 return None49 50 except requests.exceptions.RequestException as e:51 st.error(f"Error processing image: {str(e)}")52 return None53 54# File uploader55uploaded_file = st.file_uploader("Choose an image...", type=['png', 'jpg', 'jpeg'])56 57if uploaded_file is not None and api_key:58 # Display the uploaded image59 image = Image.open(uploaded_file)60 st.image(image, caption="Uploaded Image", use_container_width=True)61 62 # Convert image to bytes63 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 image68 with st.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 st.write("---")76 st.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 styling82 if is_ai_generated == "Yes":83 st.error(f"Is this image AI-generated? **{is_ai_generated}**")84 85 # Show top 3 possible sources if AI-generated86 if sources:87 st.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% probability91 st.write(f"- {source}: {prob:.1%}")92 else:93 st.success(f"Is this image AI-generated? **{is_ai_generated}**")94 95 # Show confidence score in smaller text96 st.caption(f"Confidence score: {confidence:.2%}")97 98elif not api_key and uploaded_file is not None:99 st.warning("Please enter your NVIDIA API key first")100 101# Add footer with instructions102st.markdown("---")103st.markdown("""104---105### How to use:106 1071. Upload an image (PNG, JPG, or JPEG)1082. Wait for the analysis result1093. Get a ** Yes/No ** answer based on whether the image is AI-generated110 111""")