Skip to content

NextGenXplorer/Dr_DetectiveAPI

Repository files navigation

Dr. Detective API 🕵️

Flask REST API wrapper for Akinator - the web genius that can guess any character you're thinking of!

Features

  • ✅ RESTful API design with JSON responses
  • 🌍 Multi-language support (16+ languages)
  • 🎯 Multiple game themes (Characters, Animals, Objects)
  • 👶 Child-friendly mode option
  • 🖥️ Beautiful web interface included
  • 🔐 Session-based game management
  • 🌐 CORS support for web clients
  • 🛡️ Comprehensive error handling
  • 📝 Full documentation and examples
  • 🐍 Python client library included

Quick Start

Installation

# Install dependencies
pip install flask flask-cors akinator.py

# Run the server
python app.py

The API will be available at http://localhost:5000

Web Interface

The easiest way to play! Just open the web interface in your browser:

# Start the server
python app.py

# Open in your browser
# Simply open index.html in your browser or navigate to:
# file:///path/to/Dr_DetectiveAPI/index.html

Features:

  • 🎨 Modern, responsive design
  • 🌍 Language selector (16+ languages)
  • 🎯 Theme selection (Characters, Animals, Objects)
  • 👶 Child mode toggle
  • 📊 Real-time progress tracking
  • ⌨️ Keyboard shortcuts (y/n/i/p/b)
  • 📱 Mobile-friendly

How to Use:

  1. Start the Flask server: python app.py
  2. Open index.html in any modern web browser
  3. Select your language, theme, and options
  4. Click "Start Game" and answer the questions!

Environment Variables

PORT=5000          # Server port (default: 5000)
DEBUG=False        # Debug mode (default: False)
SECRET_KEY=...     # Flask secret key (auto-generated if not set)

API Endpoints

1. Get API Info

GET /

Returns API information and available endpoints.

Response:

{
  "name": "Dr. Detective API",
  "version": "2.0",
  "endpoints": {...},
  "answer_options": ["y", "n", "i", "p", "pn"]
}

2. Start New Game

POST /api/start
Content-Type: application/json

{
  "language": "en",
  "theme": "c",
  "child_mode": false
}

Starts a new Akinator game session with optional language, theme, and child mode settings.

Parameters (all optional):

  • language (string): Language code (default: "en")
  • theme (string): Game theme - "c" (characters), "a" (animals), "o" (objects) (default: "c")
  • child_mode (boolean): Enable child-friendly mode (default: false)

Response:

{
  "success": true,
  "session_id": "abc123...",
  "language": "en",
  "theme": "c",
  "child_mode": false,
  "finished": false,
  "question": "Is your character real?",
  "progression": 0.0,
  "step": 0
}

Supported Languages:

en - English       es - Spanish (Español)      fr - French (Français)
de - German        pt - Portuguese (Português) it - Italian (Italiano)
ru - Russian       ar - Arabic (العربية)       jp - Japanese (日本語)
cn - Chinese (中文) kr - Korean (한국어)          tr - Turkish (Türkçe)
nl - Dutch         pl - Polish (Polski)        he - Hebrew (עברית)
id - Indonesian

3. Answer Question

POST /api/answer
Content-Type: application/json

{
  "session_id": "abc123...",
  "answer": "y"
}

Answer Options:

  • y - Yes
  • n - No
  • i - I don't know
  • p - Probably
  • pn - Probably not

Response (In Progress):

{
  "success": true,
  "session_id": "abc123...",
  "finished": false,
  "question": "Is your character from a video game?",
  "progression": 15.5,
  "step": 1
}

Response (Finished):

{
  "success": true,
  "session_id": "abc123...",
  "finished": true,
  "result": {
    "name": "Mario",
    "description": "Plumber from Nintendo",
    "pseudo": "Mario",
    "photo": "https://...",
    "message": "Is this your character?"
  }
}

4. Go Back

POST /api/back
Content-Type: application/json

{
  "session_id": "abc123..."
}

Goes back to the previous question.

Response:

{
  "success": true,
  "session_id": "abc123...",
  "finished": false,
  "question": "Previous question...",
  "progression": 10.0,
  "step": 0
}

5. Get Status

GET /api/status?session_id=abc123...

Gets the current game state without making a move.

Response: Same format as answer endpoint

6. End Session

DELETE /api/end
Content-Type: application/json

{
  "session_id": "abc123..."
}

Ends the game session and cleans up resources.

Response:

{
  "success": true,
  "message": "Session ended"
}

7. List Sessions (Debug)

GET /api/sessions

Lists all active game sessions.

Response:

{
  "success": true,
  "active_sessions": 3,
  "session_ids": ["abc123...", "def456...", "ghi789..."]
}

Multi-Language Support

Quick Example

# Start game in Spanish
curl -X POST http://localhost:5000/api/start \
  -H "Content-Type: application/json" \
  -d '{"language": "es", "theme": "c"}'

# Start game in Japanese with animals theme
curl -X POST http://localhost:5000/api/start \
  -H "Content-Type: application/json" \
  -d '{"language": "jp", "theme": "a"}'

# Start game with child-friendly mode
curl -X POST http://localhost:5000/api/start \
  -H "Content-Type: application/json" \
  -d '{"child_mode": true}'

Interactive Multi-Language Demo

# Interactive language selector
python multilang_example.py

# Test all languages
python multilang_example.py --demo

# Test all themes
python multilang_example.py --themes

# Test child mode
python multilang_example.py --child

Python Multi-Language Client

import requests

# Start game in French
response = requests.post('http://localhost:5000/api/start', json={
    "language": "fr",
    "theme": "c",
    "child_mode": False
})
data = response.json()
print(data['question'])  # Question in French

Usage Examples

Python Client

from client_example import AkinatorClient

# Create client
client = AkinatorClient("http://localhost:5000")

# Start game
state = client.start_game()
print(state['question'])

# Answer questions
state = client.answer('y')
print(state['question'])

state = client.answer('n')

# Go back if needed
state = client.go_back()

# End session
client.end_game()

Interactive Mode:

python client_example.py

Programmatic Demo:

python client_example.py --demo

cURL Examples

# Make the script executable
chmod +x curl_examples.sh

# Run all examples
./curl_examples.sh

Manual cURL:

# Start game
SESSION=$(curl -s -X POST http://localhost:5000/api/start | jq -r '.session_id')

# Answer question
curl -X POST http://localhost:5000/api/answer \
  -H "Content-Type: application/json" \
  -d "{\"session_id\": \"$SESSION\", \"answer\": \"y\"}"

# Get status
curl "http://localhost:5000/api/status?session_id=$SESSION"

# End session
curl -X DELETE http://localhost:5000/api/end \
  -H "Content-Type: application/json" \
  -d "{\"session_id\": \"$SESSION\"}"

JavaScript/Web

// Start game
const startResponse = await fetch('http://localhost:5000/api/start', {
  method: 'POST'
});
const { session_id, question } = await startResponse.json();

// Answer question
const answerResponse = await fetch('http://localhost:5000/api/answer', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ session_id, answer: 'y' })
});
const state = await answerResponse.json();

// End session
await fetch('http://localhost:5000/api/end', {
  method: 'DELETE',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ session_id })
});

Error Handling

All endpoints return consistent error responses:

{
  "success": false,
  "error": "Error message here"
}

Common Error Codes:

  • 400 - Bad Request (missing/invalid parameters)
  • 404 - Not Found (invalid session_id or endpoint)
  • 500 - Internal Server Error

Common Errors:

  • "Missing session_id or answer" - Required fields not provided
  • "Invalid session_id" - Session not found or expired
  • "Game not started" - Trying to answer before starting
  • "Invalid answer: ..." - Answer not in [y, n, i, p, pn]
  • "Cannot go back any further" - At first question

Architecture

Session Management

Each game creates a GameSession object stored in memory with a unique session ID:

sessions = {
  "abc123...": GameSession(),
  "def456...": GameSession(),
}

Note: Sessions are stored in memory and will be lost on server restart. For production, consider using Redis or database storage.

GameSession Class

class GameSession:
    def __init__(self)         # Create new session
    def start(self)            # Start game
    def answer(response)       # Answer question
    def back(self)             # Go back
    def get_current_state()    # Get current state

State Flow

Start → Question → Answer → Question → ... → Result
              ↑        ↓
              └─ Back ─┘

Development

Project Structure

Dr_DetectiveAPI/
├── app.py                 # Flask API server with multi-language support
├── index.html             # Web interface (open in browser)
├── client_example.py      # Python client & examples
├── multilang_example.py   # Multi-language interactive demo
├── curl_examples.sh       # cURL test script
├── aki.py                 # Original CLI version
├── requirements.txt       # Python dependencies
└── README.md              # This file

Running Tests

Test all endpoints:

./curl_examples.sh

Test Python client:

python client_example.py --demo

Adding Features

The API is designed to be extensible. Common additions:

  1. Persistent Sessions: Add Redis or database backend
  2. Authentication: Add API keys or OAuth
  3. Rate Limiting: Add Flask-Limiter
  4. Logging: Add structured logging
  5. Metrics: Add Prometheus metrics
  6. User Accounts: Add user registration and game history

Production Deployment

Using Gunicorn

pip install gunicorn
gunicorn -w 4 -b 0.0.0.0:5000 app:app

Using Docker

FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["gunicorn", "-w", "4", "-b", "0.0.0.0:5000", "app:app"]

Environment Configuration

Create .env file:

PORT=5000
DEBUG=False
SECRET_KEY=your-secret-key-here

API Response Times

Typical response times on modern hardware:

  • /api/start: 500-1000ms (initial connection to Akinator)
  • /api/answer: 300-800ms (network request to Akinator)
  • /api/back: 200-500ms
  • /api/status: <50ms (local state)
  • /api/end: <50ms (local cleanup)

Limitations

  • Sessions stored in memory (lost on restart)
  • No authentication/authorization
  • No rate limiting
  • Dependent on Akinator API availability
  • Single-threaded Flask dev server (use Gunicorn for production)

Credits

License

MIT License - See original Akinator.py license for API wrapper terms.

Support

For issues or questions:

  1. Check this README
  2. Review example code
  3. Test with curl_examples.sh
  4. Check Flask and Akinator.py documentation

Version History

  • v2.1 - Added multi-language support (16+ languages), themes, and child mode
  • v2.0 - Complete Flask REST API with session management
  • v1.0 - Original CLI implementation (aki.py)

About

by NextgenX

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 3

  •  
  •  
  •