Andercar commited on
Commit
f3944ef
·
verified ·
1 Parent(s): 24b3942

Upload 3 files

Browse files
Files changed (3) hide show
  1. Dockerfile +14 -0
  2. main.py +110 -0
  3. requirements.txt +5 -0
Dockerfile ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.9
2
+
3
+ WORKDIR /code
4
+
5
+ COPY ./requirements.txt /code/requirements.txt
6
+
7
+ RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
8
+
9
+ COPY . /code
10
+
11
+ # Create a directory for uploads if it doesn't exist
12
+ RUN mkdir -p /code/uploads && chmod 777 /code/uploads
13
+
14
+ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
main.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, UploadFile, File, HTTPException
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+ from PIL import Image, ImageChops, ImageEnhance
4
+ import io
5
+ import numpy as np
6
+
7
+ app = FastAPI()
8
+
9
+ # Allow CORS for frontend
10
+ app.add_middleware(
11
+ CORSMiddleware,
12
+ allow_origins=["*"], # In production, specify the frontend domain
13
+ allow_credentials=True,
14
+ allow_methods=["*"],
15
+ allow_headers=["*"],
16
+ )
17
+
18
+ def analyze_image_heuristics(image: Image.Image) -> float:
19
+ """
20
+ Enhanced heuristic analysis for AI detection.
21
+ Combines:
22
+ 1. Metadata Analysis (EXIF, Software tags)
23
+ 2. Error Level Analysis (ELA)
24
+ 3. Frequency Analysis (FFT)
25
+ """
26
+ score = 0.0
27
+
28
+ # --- 1. Metadata Check ---
29
+ exif_data = image.getexif()
30
+ if not exif_data:
31
+ score += 0.3 # Suspicious: No EXIF
32
+ else:
33
+ # Check for common AI generation software tags
34
+ # 305 is the tag for 'Software'
35
+ software = exif_data.get(305, "").lower()
36
+ ai_signatures = ['stable diffusion', 'midjourney', 'dall-e', 'comfyui']
37
+ if any(sig in software for sig in ai_signatures):
38
+ return 1.0 # Definitely AI
39
+
40
+ # --- 2. Error Level Analysis (ELA) ---
41
+ try:
42
+ if image.mode != 'RGB':
43
+ image = image.convert('RGB')
44
+
45
+ buffer = io.BytesIO()
46
+ image.save(buffer, 'JPEG', quality=90)
47
+ buffer.seek(0)
48
+ resaved = Image.open(buffer)
49
+
50
+ ela_image = ImageChops.difference(image, resaved)
51
+ extrema = ela_image.getextrema()
52
+ max_diff = max([ex[1] for ex in extrema])
53
+
54
+ # AI images often have very smooth noise profiles
55
+ if max_diff < 15:
56
+ score += 0.2
57
+
58
+ except Exception as e:
59
+ print(f"ELA Error: {e}")
60
+
61
+ # --- 3. Frequency Analysis (FFT) ---
62
+ # AI images often lack high-frequency details compared to real photos
63
+ try:
64
+ img_gray = image.convert('L')
65
+ f = np.fft.fft2(img_gray)
66
+ fshift = np.fft.fftshift(f)
67
+ magnitude_spectrum = 20 * np.log(np.abs(fshift) + 1)
68
+
69
+ # Calculate mean magnitude at high frequencies
70
+ rows, cols = img_gray.size
71
+ crow, ccol = rows//2 , cols//2
72
+ # Mask center (low frequencies)
73
+ mask_size = 30
74
+ magnitude_spectrum[crow-mask_size:crow+mask_size, ccol-mask_size:ccol+mask_size] = 0
75
+
76
+ high_freq_mean = np.mean(magnitude_spectrum)
77
+
78
+ # Heuristic threshold: Real photos usually have more high-freq noise
79
+ if high_freq_mean < 100:
80
+ score += 0.3
81
+
82
+ except Exception as e:
83
+ print(f"FFT Error: {e}")
84
+
85
+ return min(score, 0.99)
86
+
87
+ @app.post("/analyze")
88
+ async def analyze_media(file: UploadFile = File(...)):
89
+ try:
90
+ contents = await file.read()
91
+ image = Image.open(io.BytesIO(contents))
92
+
93
+ # Perform analysis
94
+ ai_probability = analyze_image_heuristics(image)
95
+
96
+ # Threshold
97
+ is_ai = ai_probability > 0.5
98
+
99
+ return {
100
+ "filename": file.filename,
101
+ "is_ai": is_ai,
102
+ "confidence": round(ai_probability * 100, 2),
103
+ "message": "AI Generated" if is_ai else "Real / Human Created"
104
+ }
105
+ except Exception as e:
106
+ raise HTTPException(status_code=500, detail=str(e))
107
+
108
+ @app.get("/")
109
+ def read_root():
110
+ return {"status": "Server is running"}
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ fastapi
2
+ uvicorn
3
+ python-multipart
4
+ pillow
5
+ numpy