Download app.py from celaphee/AI-Generated_Face_Detection: direct link, hf CLI and curl.
- Browser
- Download file 1.93 kB
-
https://huggingface.co/spaces/celaphee/AI-Generated_Face_Detection/resolve/main/app.py
- Command line
-
hf download hf://spaces/celaphee/AI-Generated_Face_Detection/app.py
-
curl -L -o app.py https://huggingface.co/spaces/celaphee/AI-Generated_Face_Detection/resolve/main/app.py
1.93 kB
| import streamlit as st | |
| import random | |
| import os | |
| import torch | |
| import numpy as np | |
| from PIL import Image | |
| from torchvision.transforms import v2 | |
| from torchvision.models import resnet18, ResNet18_Weights | |
| def load_model(): | |
| model = resnet18(weights=None) | |
| model.fc = torch.nn.Linear(512, 2) | |
| model.load_state_dict(torch.load('best_model.pth', map_location='cpu', weights_only=True)) | |
| model.eval() | |
| return model | |
| model = load_model() | |
| transform = v2.Compose([ | |
| v2.Resize((224, 224)), | |
| v2.ToImage(), | |
| v2.ToDtype(torch.float32, scale=True), | |
| v2.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), | |
| ]) | |
| def predict(img_path): | |
| img = Image.open(img_path).convert("RGB") | |
| tensor = transform(img).unsqueeze(0) | |
| with torch.no_grad(): | |
| output = model(tensor) | |
| pred = torch.argmax(output, dim=1).item() | |
| return "Real" if pred == 1 else "Fake" | |
| directory = "data/sample" | |
| if "filename" not in st.session_state: | |
| st.session_state.filename = random.choice(os.listdir(directory)) | |
| filename = st.session_state.filename | |
| st.title("AI-Face-Detection") | |
| st.header("Try to find which face is generated and which is real") | |
| left, center, right = st.columns(3) | |
| _, _, col1, col2, col3, _ = st.columns([2, 1, 1, 1, 1, 2]) | |
| with center: | |
| st.image(directory + "/" + filename) | |
| with col1: | |
| button1 = st.button("Real") | |
| with col2: | |
| button2 = st.button("Fake") | |
| with col3: | |
| button3 = st.button("Next") | |
| if button1 or button2: | |
| user_guess = "Real" if button1 else "Fake" | |
| true_label = "Real" if "real" in filename.lower() else "Fake" | |
| model_pred = predict(directory + "/" + filename) | |
| st.write(f"This face was **{true_label}**") | |
| st.write(f"The model predicted: **{model_pred}**") | |
| st.write("Correct!" if user_guess == true_label else "Wrong!") | |
| if button3: | |
| st.session_state.filename = random.choice(os.listdir(directory)) | |
| st.rerun() |