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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import torch
|
| 3 |
+
import math
|
| 4 |
+
import gradio as gr
|
| 5 |
+
from PIL import Image
|
| 6 |
+
from transformers import (
|
| 7 |
+
GPT2LMHeadModel, GPT2Tokenizer,
|
| 8 |
+
AutoTokenizer, AutoModelForSequenceClassification,
|
| 9 |
+
AutoImageProcessor, AutoModelForImageClassification,
|
| 10 |
+
logging
|
| 11 |
+
)
|
| 12 |
+
from openai import OpenAI
|
| 13 |
+
from groq import Groq
|
| 14 |
+
import cv2
|
| 15 |
+
import numpy as np
|
| 16 |
+
import torch.nn as nn
|
| 17 |
+
import librosa
|
| 18 |
+
|
| 19 |
+
logging.set_verbosity_error()
|
| 20 |
+
|
| 21 |
+
# -----------------------------
|
| 22 |
+
# API Keys (set via Space secrets)
|
| 23 |
+
# -----------------------------
|
| 24 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 25 |
+
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
|
| 26 |
+
client = Groq(api_key=GROQ_API_KEY)
|
| 27 |
+
|
| 28 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 29 |
+
|
| 30 |
+
# -----------------------------
|
| 31 |
+
# TEXT DETECTION
|
| 32 |
+
# -----------------------------
|
| 33 |
+
def run_hf_detector(text, model_id="roberta-base-openai-detector"):
|
| 34 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id, token=HF_TOKEN)
|
| 35 |
+
model = AutoModelForSequenceClassification.from_pretrained(model_id, token=HF_TOKEN).to(device)
|
| 36 |
+
inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=512).to(device)
|
| 37 |
+
with torch.no_grad():
|
| 38 |
+
outputs = model(**inputs)
|
| 39 |
+
probs = torch.nn.functional.softmax(outputs.logits, dim=-1).cpu().numpy()[0]
|
| 40 |
+
human_score, ai_score = float(probs[0]), float(probs[1])
|
| 41 |
+
label = "AI-generated" if ai_score > human_score else "Human-generated"
|
| 42 |
+
return {"ai_score": ai_score, "human_score": human_score, "hf_label": label}
|
| 43 |
+
|
| 44 |
+
def calculate_perplexity(text):
|
| 45 |
+
model = GPT2LMHeadModel.from_pretrained("gpt2").to(device)
|
| 46 |
+
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
|
| 47 |
+
encodings = tokenizer(text, return_tensors="pt").to(device)
|
| 48 |
+
max_length = model.config.n_positions
|
| 49 |
+
if encodings.input_ids.size(1) > max_length:
|
| 50 |
+
encodings.input_ids = encodings.input_ids[:, :max_length]
|
| 51 |
+
encodings.attention_mask = encodings.attention_mask[:, :max_length]
|
| 52 |
+
with torch.no_grad():
|
| 53 |
+
outputs = model(**encodings, labels=encodings.input_ids)
|
| 54 |
+
loss = outputs.loss
|
| 55 |
+
perplexity = math.exp(loss.item())
|
| 56 |
+
label = "AI-generated" if perplexity < 60 else "Human-generated"
|
| 57 |
+
return {"perplexity": perplexity, "perplexity_label": label}
|
| 58 |
+
|
| 59 |
+
def generate_text_explanation(text, ai_score, human_score):
|
| 60 |
+
decision = "AI-generated" if ai_score > human_score else "Human-generated"
|
| 61 |
+
prompt = f"""
|
| 62 |
+
You are an AI text analysis expert. Explain concisely why this text was classified as '{decision}'.
|
| 63 |
+
Text: "{text}"
|
| 64 |
+
Explanation:"""
|
| 65 |
+
response = client.chat.completions.create(
|
| 66 |
+
model="gemma2-9b-it",
|
| 67 |
+
messages=[{"role":"user","content":prompt}],
|
| 68 |
+
max_tokens=150,
|
| 69 |
+
temperature=0.7
|
| 70 |
+
)
|
| 71 |
+
return response.choices[0].message.content.strip()
|
| 72 |
+
|
| 73 |
+
def analyze_text(text):
|
| 74 |
+
try:
|
| 75 |
+
hf_out = run_hf_detector(text)
|
| 76 |
+
hf_out["ai_score"] = float(hf_out["ai_score"])
|
| 77 |
+
hf_out["human_score"] = float(hf_out["human_score"])
|
| 78 |
+
diff = abs(hf_out["ai_score"] - hf_out["human_score"])
|
| 79 |
+
confidence = "High" if diff>0.8 else "Medium" if diff>=0.3 else "Low"
|
| 80 |
+
perp_out = calculate_perplexity(text)
|
| 81 |
+
explanation = generate_text_explanation(text, hf_out["ai_score"], hf_out["human_score"])
|
| 82 |
+
return {"ai_score": hf_out["ai_score"], "confidence": confidence, "explanation": explanation}
|
| 83 |
+
except:
|
| 84 |
+
return {"ai_score":0.0,"confidence":"Low","explanation":"Error analyzing text."}
|
| 85 |
+
|
| 86 |
+
# -----------------------------
|
| 87 |
+
# IMAGE DETECTION
|
| 88 |
+
# -----------------------------
|
| 89 |
+
image_model_name = "Ateeqq/ai-vs-human-image-detector"
|
| 90 |
+
image_processor = AutoImageProcessor.from_pretrained(image_model_name)
|
| 91 |
+
image_model = AutoModelForImageClassification.from_pretrained(image_model_name)
|
| 92 |
+
image_model.eval()
|
| 93 |
+
|
| 94 |
+
def generate_image_explanation(ai_probability,human_probability,confidence):
|
| 95 |
+
prompt = f"""
|
| 96 |
+
You are an AI image analysis expert.
|
| 97 |
+
AI: {ai_probability:.4f}, Human: {human_probability:.4f}, Confidence: {confidence}
|
| 98 |
+
Explain in 1-2 sentences why it was classified as {'AI-generated' if ai_probability>human_probability else 'Human-generated'}.
|
| 99 |
+
"""
|
| 100 |
+
response = client.chat.completions.create(
|
| 101 |
+
model="llama-3.3-70b-versatile",
|
| 102 |
+
messages=[{"role":"user","content":prompt}],
|
| 103 |
+
temperature=0.6
|
| 104 |
+
)
|
| 105 |
+
return response.choices[0].message.content.strip()
|
| 106 |
+
|
| 107 |
+
def analyze_image(image):
|
| 108 |
+
image = image.convert("RGB")
|
| 109 |
+
inputs = image_processor(images=image, return_tensors="pt")
|
| 110 |
+
with torch.no_grad():
|
| 111 |
+
logits = image_model(**inputs).logits
|
| 112 |
+
probabilities = torch.nn.functional.softmax(logits/6.0, dim=-1)[0]
|
| 113 |
+
ai_prob, human_prob = probabilities[0].item(), probabilities[1].item()
|
| 114 |
+
diff = abs(ai_prob-human_prob)
|
| 115 |
+
confidence = "High" if diff>=0.7 else "Medium" if diff>=0.3 else "Low"
|
| 116 |
+
explanation = generate_image_explanation(ai_prob, human_prob, confidence)
|
| 117 |
+
return {"ai_probability": ai_prob, "confidence": confidence, "explanation": explanation}
|
| 118 |
+
|
| 119 |
+
# -----------------------------
|
| 120 |
+
# VIDEO DETECTION
|
| 121 |
+
# -----------------------------
|
| 122 |
+
def extract_frames(video_path, frame_rate=1):
|
| 123 |
+
cap = cv2.VideoCapture(video_path)
|
| 124 |
+
fps = cap.get(cv2.CAP_PROP_FPS)
|
| 125 |
+
interval = int(fps*frame_rate)
|
| 126 |
+
frames,count = [],0
|
| 127 |
+
while cap.isOpened():
|
| 128 |
+
ret,frame = cap.read()
|
| 129 |
+
if not ret: break
|
| 130 |
+
if count%interval==0: frames.append(Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)))
|
| 131 |
+
count+=1
|
| 132 |
+
cap.release()
|
| 133 |
+
return frames
|
| 134 |
+
|
| 135 |
+
def analyze_video(video_path):
|
| 136 |
+
frames = extract_frames(video_path, frame_rate=1)
|
| 137 |
+
if not frames: return {"error":"No frames extracted."}
|
| 138 |
+
ai_probs,human_probs = [],[]
|
| 139 |
+
for img in frames:
|
| 140 |
+
inputs = image_processor(images=img, return_tensors="pt")
|
| 141 |
+
with torch.no_grad(): logits = image_model(**inputs).logits
|
| 142 |
+
probs = torch.nn.functional.softmax(logits, dim=-1)[0]
|
| 143 |
+
ai_probs.append(probs[0].item())
|
| 144 |
+
human_probs.append(probs[1].item())
|
| 145 |
+
avg_ai,avg_human = float(np.mean(ai_probs)), float(np.mean(human_probs))
|
| 146 |
+
diff = abs(avg_ai-avg_human)
|
| 147 |
+
confidence = "High" if diff>=0.7 else "Medium" if diff>=0.3 else "Low"
|
| 148 |
+
prompt = f"Video processed {len(frames)} frames. AI: {avg_ai:.4f}, Human: {avg_human:.4f}. Confidence: {confidence}. Explain why it was {'AI-generated' if avg_ai>avg_human else 'Human-generated'}."
|
| 149 |
+
response = client.chat.completions.create(model="llama-3.3-70b-versatile", messages=[{"role":"user","content":prompt}], temperature=0.6)
|
| 150 |
+
explanation = response.choices[0].message.content.strip()
|
| 151 |
+
return {"ai_probability":avg_ai,"confidence":confidence,"explanation":explanation}
|
| 152 |
+
|
| 153 |
+
# -----------------------------
|
| 154 |
+
# AUDIO DETECTION
|
| 155 |
+
# -----------------------------
|
| 156 |
+
class AudioCNNRNN(nn.Module):
|
| 157 |
+
def __init__(self,lstm_hidden_size=128,num_classes=2):
|
| 158 |
+
super().__init__()
|
| 159 |
+
self.cnn = nn.Sequential(
|
| 160 |
+
nn.Conv2d(1,32,3,1,1), nn.ReLU(), nn.MaxPool2d(2),
|
| 161 |
+
nn.Conv2d(32,64,3,1,1), nn.ReLU(), nn.MaxPool2d(2)
|
| 162 |
+
)
|
| 163 |
+
self.lstm = nn.LSTM(input_size=64, hidden_size=lstm_hidden_size,batch_first=True)
|
| 164 |
+
self.fc = nn.Linear(lstm_hidden_size,num_classes)
|
| 165 |
+
def forward(self,x):
|
| 166 |
+
b,s,c,h,w = x.size()
|
| 167 |
+
x = self.cnn(x.view(b*s,c,h,w)).mean(dim=[2,3]).view(b,s,-1)
|
| 168 |
+
out,_ = self.lstm(x)
|
| 169 |
+
return self.fc(out[:,-1,:])
|
| 170 |
+
|
| 171 |
+
def extract_mel_spectrogram(audio_path, sr=16000, n_mels=64):
|
| 172 |
+
waveform,_ = librosa.load(audio_path,sr=sr)
|
| 173 |
+
mel_spec = librosa.feature.melspectrogram(waveform,sr,n_mels=n_mels)
|
| 174 |
+
return librosa.power_to_db(mel_spec,ref=np.max)
|
| 175 |
+
|
| 176 |
+
def slice_spectrogram(mel_spec,slice_size=128,step=64):
|
| 177 |
+
return [mel_spec[:,i:i+slice_size] for i in range(0, mel_spec.shape[1]-slice_size, step)]
|
| 178 |
+
|
| 179 |
+
def analyze_audio(audio_path):
|
| 180 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 181 |
+
model = AudioCNNRNN().to(device).eval()
|
| 182 |
+
mel_spec = extract_mel_spectrogram(audio_path)
|
| 183 |
+
slices = slice_spectrogram(mel_spec)
|
| 184 |
+
if not slices: return {"ai_probability":0,"confidence":"Low","explanation":"Audio too short."}
|
| 185 |
+
data = torch.stack([torch.tensor(s).unsqueeze(0) for s in slices]).unsqueeze(0).to(device)
|
| 186 |
+
with torch.no_grad(): logits = model(data)
|
| 187 |
+
probabilities = torch.nn.functional.softmax(logits/3.0, dim=-1)[0]
|
| 188 |
+
ai_prob,human_prob = probabilities[0].item(),probabilities[1].item()
|
| 189 |
+
diff = abs(ai_prob-human_prob)
|
| 190 |
+
confidence = "High" if diff>=0.7 else "Medium" if diff>=0.3 else "Low"
|
| 191 |
+
prompt = f"Audio AI:{ai_prob:.4f} Human:{human_prob:.4f} Confidence:{confidence}. Explain reasoning."
|
| 192 |
+
response = client.chat.completions.create(model="llama-3.3-70b-versatile", messages=[{"role":"user","content":prompt}], temperature=0.6)
|
| 193 |
+
return {"ai_probability":ai_prob,"confidence":confidence,"explanation":response.choices[0].message.content.strip()}
|
| 194 |
+
|
| 195 |
+
# -----------------------------
|
| 196 |
+
# GRADIO UI
|
| 197 |
+
# -----------------------------
|
| 198 |
+
def format_text_results(text):
|
| 199 |
+
res = analyze_text(text)
|
| 200 |
+
conf_map = {"High":"π’ High","Medium":"π‘ Medium","Low":"π΄ Low"}
|
| 201 |
+
return f"### Text Detection\nAI Score: {res['ai_score']:.4f}\nConfidence: {conf_map.get(res['confidence'],res['confidence'])}\nExplanation: {res['explanation']}"
|
| 202 |
+
|
| 203 |
+
def format_image_results(image):
|
| 204 |
+
res = analyze_image(image)
|
| 205 |
+
return f"### Image Detection\nAI Probability: {res['ai_probability']:.4f}\nConfidence: {res['confidence']}\nExplanation: {res['explanation']}"
|
| 206 |
+
|
| 207 |
+
def format_video_results(video_file):
|
| 208 |
+
res = analyze_video(video_file)
|
| 209 |
+
if "error" in res: return res["error"]
|
| 210 |
+
return f"### Video Detection\nAI Probability: {res['ai_probability']:.4f}\nConfidence: {res['confidence']}\nExplanation: {res['explanation']}"
|
| 211 |
+
|
| 212 |
+
def format_audio_results(audio_file):
|
| 213 |
+
res = analyze_audio(audio_file)
|
| 214 |
+
return f"### Audio Detection\nAI Probability: {res['ai_probability']:.4f}\nConfidence: {res['confidence']}\nExplanation: {res['explanation']}"
|
| 215 |
+
|
| 216 |
+
with gr.Blocks() as app:
|
| 217 |
+
home = gr.Column(visible=True)
|
| 218 |
+
with home:
|
| 219 |
+
gr.Markdown("## AI Multi-Modal Detector")
|
| 220 |
+
with gr.Row():
|
| 221 |
+
t_btn = gr.Button("Text")
|
| 222 |
+
i_btn = gr.Button("Image")
|
| 223 |
+
v_btn = gr.Button("Video")
|
| 224 |
+
a_btn = gr.Button("Audio")
|
| 225 |
+
|
| 226 |
+
text_page = gr.Column(visible=False)
|
| 227 |
+
with text_page:
|
| 228 |
+
inp = gr.Textbox(lines=5, placeholder="Paste text...", label="Text")
|
| 229 |
+
out = gr.Markdown()
|
| 230 |
+
gr.Button("Analyze").click(format_text_results, inputs=inp, outputs=out)
|
| 231 |
+
gr.Button("Back").click(lambda: (gr.update(visible=True), gr.update(visible=False)), outputs=[home,text_page])
|
| 232 |
+
|
| 233 |
+
image_page = gr.Column(visible=False)
|
| 234 |
+
with image_page:
|
| 235 |
+
inp = gr.Image(type="pil")
|
| 236 |
+
out = gr.Markdown()
|
| 237 |
+
gr.Button("Analyze").click(format_image_results, inputs=inp, outputs=out)
|
| 238 |
+
gr.Button("Back").click(lambda: (gr.update(visible=True), gr.update(visible=False)), outputs=[home,image_page])
|
| 239 |
+
|
| 240 |
+
video_page = gr.Column(visible=False)
|
| 241 |
+
with video_page:
|
| 242 |
+
inp = gr.Video()
|
| 243 |
+
out = gr.Markdown()
|
| 244 |
+
gr.Button("Analyze").click(format_video_results, inputs=inp, outputs=out)
|
| 245 |
+
gr.Button("Back").click(lambda: (gr.update(visible=True), gr.update(visible=False)), outputs=[home,video_page])
|
| 246 |
+
|
| 247 |
+
audio_page = gr.Column(visible=False)
|
| 248 |
+
with audio_page:
|
| 249 |
+
inp = gr.Audio(type="filepath")
|
| 250 |
+
out = gr.Markdown()
|
| 251 |
+
gr.Button("Analyze").click(format_audio_results, inputs=inp, outputs=out)
|
| 252 |
+
gr.Button("Back").click(lambda: (gr.update(visible=True), gr.update(visible=False)), outputs=[home,audio_page])
|
| 253 |
+
|
| 254 |
+
t_btn.click(lambda: (gr.update(visible=False), gr.update(visible=True)), outputs=[home,text_page])
|
| 255 |
+
i_btn.click(lambda: (gr.update(visible=False), gr.update(visible=True)), outputs=[home,image_page])
|
| 256 |
+
v_btn.click(lambda: (gr.update(visible=False), gr.update(visible=True)), outputs=[home,video_page])
|
| 257 |
+
a_btn.click(lambda: (gr.update(visible=False), gr.update(visible=True)), outputs=[home,audio_page])
|
| 258 |
+
|
| 259 |
+
app.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
torch
|
| 3 |
+
torchvision
|
| 4 |
+
transformers
|
| 5 |
+
Pillow
|
| 6 |
+
opencv-python
|
| 7 |
+
librosa
|
| 8 |
+
numpy
|
| 9 |
+
openai
|
| 10 |
+
groq
|