Spaces:
Sleeping
Sleeping
| """ | |
| AI vs Real Face Detection Game - Simplified Version | |
| Interactive Gradio web application that allows users to test their ability to distinguish | |
| between AI-generated faces and real human faces through a game-based approach. | |
| """ | |
| import os | |
| import sys | |
| import logging | |
| import argparse | |
| import gradio as gr | |
| # Add src directory to Python path | |
| sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src')) | |
| from src.image_manager import ImagePool | |
| from src.model_inference import FaceDetectorModel | |
| from src.game_logic import GameState | |
| from src.utils import calculate_bg_color | |
| # Configure logging | |
| logging.basicConfig( | |
| level=logging.INFO, | |
| format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' | |
| ) | |
| logger = logging.getLogger(__name__) | |
| def initialize_app(): | |
| """Initialize application, load model and image pool""" | |
| logger.info("Starting application initialization...") | |
| try: | |
| # Load image pool | |
| logger.info("Loading image pool...") | |
| image_pool = ImagePool(ai_dir="image/ai", real_dir="image/real") | |
| logger.info(f"Image pool loaded successfully: {image_pool.total_ai} AI images, {image_pool.total_real} real images") | |
| # Load AI model | |
| logger.info("Loading AI detection model...") | |
| model = FaceDetectorModel(model_path="model/best_mobilenet_finetuned.keras") | |
| logger.info("Model loaded successfully") | |
| # Warmup model | |
| logger.info("Warming up model...") | |
| model.warmup() | |
| # Create game state | |
| game_state = GameState() | |
| game_state.images = image_pool.create_game_set() | |
| game_state.next_round() | |
| logger.info("Application initialization complete!") | |
| return image_pool, model, game_state | |
| except Exception as e: | |
| error_msg = f"Application initialization failed: {e}" | |
| logger.error(error_msg) | |
| raise RuntimeError(error_msg) | |
| def format_score(player_score, ai_score, current_round, total_rounds): | |
| """Format score display""" | |
| return f"""### Score | |
| **You**: {player_score} | |
| **AI**: {ai_score} \n | |
| **Progress**: {current_round}/{total_rounds} | |
| """ | |
| def create_app(): | |
| """Create Gradio application""" | |
| image_pool, model, game_state = initialize_app() | |
| with gr.Blocks( | |
| title="AI vs Real Face Detection Game", | |
| delete_cache=(86400,86400) | |
| ) as app: | |
| gr.Markdown("# AI vs Real Face Detection Game") | |
| gr.Markdown("Test your ability to distinguish AI-generated faces from real human faces!") | |
| state = gr.State(game_state) | |
| with gr.Tabs(): | |
| # ==================== Game Mode ==================== | |
| with gr.Tab("Game Mode"): | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| score_display = gr.Markdown( | |
| value=format_score(0, 0, 1, 20) | |
| ) | |
| ai_button = gr.Button("AI Generated", variant="primary", size="lg") | |
| human_button = gr.Button("Real Human", variant="secondary", size="lg") | |
| next_button = gr.Button("Next", size="lg") | |
| reset_button = gr.Button("Reset Game", size="sm") | |
| feedback_display = gr.Markdown(value="Guess if this is AI-generated or a real human?") | |
| with gr.Column(scale=3): | |
| image_display = gr.Image( | |
| label="Face Image", | |
| value=game_state.current_image_path | |
| ) | |
| # ==================== Detector Mode ==================== | |
| with gr.Tab("Detector Mode"): | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| detector_result_display = gr.Markdown(value="Click button to view random image") | |
| detector_next_button = gr.Button("Next Random Image", variant="primary", size="lg") | |
| detector_confidence_display = gr.Markdown(value="") | |
| with gr.Column(scale=3): | |
| detector_image_display = gr.Image(label="Face Image") | |
| # ==================== Game Mode Event Handlers ==================== | |
| def on_guess_ai(state_value): | |
| ai_prediction, ai_confidence = model.predict(state_value.current_image_path) | |
| state_value.record_guess("AI", ai_prediction, ai_confidence) | |
| feedback = state_value.last_result | |
| if state_value.game_over: | |
| feedback = state_value.get_final_result() | |
| return [ | |
| format_score(state_value.player_score, state_value.ai_score, | |
| state_value.current_round, state_value.total_rounds), | |
| feedback, | |
| gr.update(interactive=False), | |
| gr.update(interactive=False), | |
| gr.update(visible=not state_value.game_over), | |
| state_value | |
| ] | |
| def on_guess_human(state_value): | |
| ai_prediction, ai_confidence = model.predict(state_value.current_image_path) | |
| state_value.record_guess("Human", ai_prediction, ai_confidence) | |
| feedback = state_value.last_result | |
| if state_value.game_over: | |
| feedback = state_value.get_final_result() | |
| return [ | |
| format_score(state_value.player_score, state_value.ai_score, | |
| state_value.current_round, state_value.total_rounds), | |
| feedback, | |
| gr.update(interactive=False), | |
| gr.update(interactive=False), | |
| gr.update(visible=not state_value.game_over), | |
| state_value | |
| ] | |
| def on_next_picture(state_value): | |
| state_value.next_round() | |
| return [ | |
| state_value.current_image_path, | |
| "", | |
| gr.update(interactive=True), | |
| gr.update(interactive=True), | |
| gr.update(visible=False), | |
| format_score(state_value.player_score, state_value.ai_score, | |
| state_value.current_round, state_value.total_rounds), | |
| state_value | |
| ] | |
| def on_reset_game(state_value): | |
| state_value.reset() | |
| state_value.images = image_pool.create_game_set() | |
| state_value.current_round = 0 | |
| state_value.next_round() | |
| return [ | |
| state_value.current_image_path, | |
| format_score(0, 0, 1, 20), | |
| "New game started! Guess if this is AI-generated or a real human?", | |
| gr.update(interactive=True), | |
| gr.update(interactive=True), | |
| gr.update(visible=False), | |
| state_value | |
| ] | |
| # ==================== Detector Mode Event Handlers ==================== | |
| def on_detector_next(): | |
| import random | |
| label = random.choice(["AI", "Human"]) | |
| image_path = image_pool.get_random_image(label) | |
| prediction, confidence = model.predict(image_path) | |
| result_text = f"### AI Prediction: {prediction}\n\n**True Label**: {label}\n\n" | |
| if prediction == label: | |
| result_text += "✓ Correct prediction!" | |
| else: | |
| result_text += "✗ Incorrect prediction" | |
| confidence_text = f"**Confidence**: {confidence * 100:.1f}%" | |
| return [image_path, result_text, confidence_text] | |
| # Bind events | |
| ai_button.click( | |
| fn=on_guess_ai, | |
| inputs=[state], | |
| outputs=[score_display, feedback_display, ai_button, human_button, next_button, state] | |
| ) | |
| human_button.click( | |
| fn=on_guess_human, | |
| inputs=[state], | |
| outputs=[score_display, feedback_display, ai_button, human_button, next_button, state] | |
| ) | |
| next_button.click( | |
| fn=on_next_picture, | |
| inputs=[state], | |
| outputs=[image_display, feedback_display, ai_button, human_button, next_button, score_display, state] | |
| ) | |
| reset_button.click( | |
| fn=on_reset_game, | |
| inputs=[state], | |
| outputs=[image_display, score_display, feedback_display, ai_button, human_button, next_button, state] | |
| ) | |
| detector_next_button.click( | |
| fn=on_detector_next, | |
| inputs=[], | |
| outputs=[detector_image_display, detector_result_display, detector_confidence_display] | |
| ) | |
| return app | |
| def main(): | |
| """Main entry function""" | |
| parser = argparse.ArgumentParser(description="AI vs Real Face Detection Game") | |
| parser.add_argument("--port", type=int, default=7860, help="Server port") | |
| parser.add_argument("--share", action="store_true", help="Create public URL") | |
| parser.add_argument("--debug", action="store_true", help="Debug mode") | |
| args = parser.parse_args() | |
| if args.debug: | |
| logging.getLogger().setLevel(logging.DEBUG) | |
| try: | |
| app = create_app() | |
| logger.info(f"Launching application on port: {args.port}") | |
| app.launch( | |
| server_port=args.port, | |
| share=args.share, | |
| ) | |
| except Exception as e: | |
| logger.error(f"Application launch failed: {e}") | |
| sys.exit(1) | |
| if __name__ == "__main__": | |
| main() | |