File size: 12,507 Bytes
38c016b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
486eff6
 
 
5686111
 
38c016b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b88621
38c016b
 
 
 
 
 
 
 
 
486eff6
38c016b
 
486eff6
 
38c016b
 
 
 
 
486eff6
38c016b
 
 
 
486eff6
 
 
 
 
 
 
 
cf76e1a
 
 
 
 
 
 
 
 
 
 
 
 
38c016b
 
 
 
 
 
 
 
 
486eff6
38c016b
 
 
 
486eff6
 
 
38c016b
486eff6
 
 
38c016b
 
 
 
 
 
 
 
486eff6
 
 
 
 
 
 
5686111
 
 
 
 
 
 
38c016b
 
 
486eff6
 
5686111
 
38c016b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
486eff6
38c016b
 
 
 
 
 
 
 
 
 
 
 
 
 
486eff6
 
 
 
 
38c016b
 
 
486eff6
 
 
 
 
38c016b
486eff6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38c016b
486eff6
 
38c016b
 
 
 
 
 
486eff6
38c016b
 
486eff6
 
 
38c016b
3b88621
 
38c016b
3b88621
38c016b
 
 
 
 
 
 
3b88621
 
 
 
 
 
38c016b
486eff6
38c016b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
"""
API routes for crossword puzzle generator.
Matches the existing JavaScript API for frontend compatibility.
"""

import logging
from typing import List, Dict, Any, Optional
from datetime import datetime

from fastapi import APIRouter, HTTPException, Request, Depends
from pydantic import BaseModel, Field

from ..services.crossword_generator_wrapper import CrosswordGenerator

logger = logging.getLogger(__name__)

router = APIRouter()

# Request/Response models
class GeneratePuzzleRequest(BaseModel):
    topics: List[str] = Field(..., description="List of topics for the puzzle")
    difficulty: str = Field(default="medium", description="Difficulty level: easy, medium, hard")
    customSentence: Optional[str] = Field(default=None, description="Optional custom sentence to influence word selection")
    multiTheme: bool = Field(default=True, description="Whether to use multi-theme processing or single-theme blending")
    wordCount: Optional[int] = Field(default=10, description="Number of words to include in the crossword (8-15)")
    similarityTemperature: Optional[float] = Field(default=None, description="Override similarity temperature for word selection randomness (0.1-2.0)")
    difficultyWeight: Optional[float] = Field(default=None, description="Override difficulty weight for similarity vs frequency balance (0.0-1.0)")

class WordInfo(BaseModel):
    word: str
    clue: str
    similarity: Optional[float] = None
    source: Optional[str] = None

class ClueInfo(BaseModel):
    number: int
    word: str
    text: str
    direction: str  # "across" or "down"
    position: Dict[str, int]  # {"row": int, "col": int}

class PuzzleMetadata(BaseModel):
    topics: List[str]
    difficulty: str
    wordCount: int
    size: int
    aiGenerated: bool

class PuzzleResponse(BaseModel):
    grid: List[List[str]]
    clues: List[ClueInfo]
    metadata: PuzzleMetadata
    debug: Optional[Dict[str, Any]] = None

class TopicInfo(BaseModel):
    id: str
    name: str

# Global crossword generator instance (will be initialized in lifespan)
generator = None

def get_crossword_generator(request: Request) -> CrosswordGenerator:
    """Dependency to get the crossword generator with thematic service."""
    global generator
    if generator is None:
        thematic_service = getattr(request.app.state, 'thematic_service', None)
        generator = CrosswordGenerator(thematic_service)
    return generator

@router.get("/topics", response_model=List[TopicInfo])
async def get_topics():
    """Get available topics for puzzle generation."""
    # Return expanded topic list for better user variety
    topics = [
        {"id": "animals", "name": "Animals"},
        {"id": "geography", "name": "Geography"},
        {"id": "science", "name": "Science"},
        {"id": "technology", "name": "Technology"},
        {"id": "sports", "name": "Sports"},
        {"id": "history", "name": "History"},
        {"id": "food", "name": "Food"},
        {"id": "entertainment", "name": "Entertainment"},
        {"id": "nature", "name": "Nature"},
        {"id": "transportation", "name": "Transportation"},
        {"id": "art", "name": "Art"},
        {"id": "medicine", "name": "Medicine"},
        {"id": "philosophy", "name": "Philosophy"},
        {"id": "music", "name": "Music"},
        {"id": "books", "name": "Books"},
        {"id": "movies", "name": "Movies"},
        {"id": "appliances", "name": "Appliances"},
        {"id": "culture", "name": "Culture"},
        {"id": "cuisine", "name": "Cuisine"},
        {"id": "languages", "name": "Languages"},
        {"id": "relations", "name": "Relations"},
        {"id": "space", "name": "Space"},
        {"id": "universe", "name": "Universe"},
        {"id": "meditation", "name": "Meditation"}
    ]
    return topics

@router.post("/generate", response_model=PuzzleResponse)
async def generate_puzzle(
    request: GeneratePuzzleRequest,
    crossword_gen: CrosswordGenerator = Depends(get_crossword_generator)
):
    """
    Generate a crossword puzzle with AI thematic word generation.
    
    This endpoint matches the JavaScript API exactly for frontend compatibility.
    """
    try:
        sentence_info = f", custom sentence: '{request.customSentence}'" if request.customSentence else ""
        theme_mode = "multi-theme" if request.multiTheme else "single-theme"
        logger.info(f"🎯 Generating puzzle for topics: {request.topics}, difficulty: {request.difficulty}{sentence_info}, mode: {theme_mode}")
        
        # Validate topics - require either topics or custom sentence
        if not request.topics and not (request.customSentence and request.customSentence.strip()):
            raise HTTPException(status_code=400, detail="At least one topic or a custom sentence is required")
        
        valid_difficulties = ["easy", "medium", "hard"]
        if request.difficulty not in valid_difficulties:
            raise HTTPException(
                status_code=400, 
                detail=f"Invalid difficulty. Must be one of: {valid_difficulties}"
            )
        
        # Validate word count
        if request.wordCount and (request.wordCount < 8 or request.wordCount > 15):
            raise HTTPException(
                status_code=400,
                detail="Word count must be between 8 and 15"
            )
        
        # Generate puzzle with optional parameter overrides
        advanced_params = {}
        if request.similarityTemperature is not None:
            advanced_params['similarity_temperature'] = request.similarityTemperature
        if request.difficultyWeight is not None:
            advanced_params['difficulty_weight'] = request.difficultyWeight
        
        puzzle_data = await crossword_gen.generate_puzzle(
            topics=request.topics,
            difficulty=request.difficulty,
            custom_sentence=request.customSentence,
            multi_theme=request.multiTheme,
            requested_words=request.wordCount,
            advanced_params=advanced_params
        )
        
        if not puzzle_data:
            raise HTTPException(status_code=500, detail="Failed to generate puzzle")
        
        logger.info(f"✅ Generated puzzle with {puzzle_data['metadata']['wordCount']} words")
        return puzzle_data
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"❌ Error generating puzzle: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/words")
async def generate_words(
    request: GeneratePuzzleRequest,
    crossword_gen: CrosswordGenerator = Depends(get_crossword_generator)
):
    """
    Generate words for given topics (debug endpoint).
    
    This endpoint allows testing word generation without full puzzle creation.
    """
    try:
        words = await crossword_gen.generate_words_for_topics(
            topics=request.topics,
            difficulty=request.difficulty
        )
        
        return {
            "topics": request.topics,
            "difficulty": request.difficulty,
            "wordCount": len(words),
            "words": words
        }
        
    except Exception as e:
        logger.error(f"❌ Error generating words: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/health")
async def api_health(request: Request):
    """API health check with cache status."""
    thematic_service = getattr(request.app.state, 'thematic_service', None)
    
    health_info = {
        "status": "healthy",
        "timestamp": datetime.utcnow().isoformat(),
        "backend": "python",
        "version": "2.0.0",
        "thematic_service": {
            "available": thematic_service is not None,
            "initialized": thematic_service.is_initialized if thematic_service else False
        }
    }
    
    # Add cache status if service is available
    if thematic_service:
        try:
            cache_status = thematic_service.get_cache_status()
            health_info["cache"] = cache_status
        except Exception as e:
            health_info["cache"] = {"error": str(e)}
    
    return health_info

@router.get("/health/cache")
async def cache_health(request: Request):
    """Detailed cache health check and status."""
    thematic_service = getattr(request.app.state, 'thematic_service', None)
    
    if not thematic_service:
        return {"error": "Thematic service not available"}
    
    try:
        cache_status = thematic_service.get_cache_status()
        
        # Add additional diagnostic information
        import os
        cache_dir = cache_status['cache_directory']
        
        diagnostics = {
            "cache_status": cache_status,
            "diagnostics": {
                "cache_dir_exists": os.path.exists(cache_dir),
                "cache_dir_readable": os.access(cache_dir, os.R_OK) if os.path.exists(cache_dir) else False,
                "cache_dir_writable": os.access(cache_dir, os.W_OK) if os.path.exists(cache_dir) else False,
                "service_initialized": thematic_service.is_initialized,
                "vocab_size_limit": thematic_service.vocab_size_limit,
                "model_name": thematic_service.model_name
            }
        }
        
        # Add file listing if directory exists
        if os.path.exists(cache_dir):
            try:
                cache_files = []
                for file in os.listdir(cache_dir):
                    file_path = os.path.join(cache_dir, file)
                    if os.path.isfile(file_path):
                        stat = os.stat(file_path)
                        cache_files.append({
                            "name": file,
                            "size_bytes": stat.st_size,
                            "size_mb": round(stat.st_size / (1024 * 1024), 2),
                            "modified": datetime.fromtimestamp(stat.st_mtime).isoformat()
                        })
                diagnostics["cache_files"] = cache_files
            except Exception as e:
                diagnostics["cache_files_error"] = str(e)
        
        return diagnostics
        
    except Exception as e:
        return {"error": f"Failed to get cache status: {e}"}

@router.post("/health/cache/reinitialize")
async def reinitialize_cache(request: Request):
    """Force re-initialization of the thematic service and cache creation."""
    thematic_service = getattr(request.app.state, 'thematic_service', None)
    
    if not thematic_service:
        return {"error": "Thematic service not available"}
    
    try:
        # Reset initialization flag to force re-initialization
        thematic_service.is_initialized = False
        
        # Force re-initialization
        await thematic_service.initialize_async()
        
        # Get updated cache status
        cache_status = thematic_service.get_cache_status()
        
        return {
            "message": "Cache re-initialization completed",
            "cache_status": cache_status,
            "timestamp": datetime.utcnow().isoformat()
        }
        
    except Exception as e:
        import traceback
        return {
            "error": f"Failed to reinitialize cache: {e}",
            "traceback": traceback.format_exc(),
            "timestamp": datetime.utcnow().isoformat()
        }

@router.get("/debug/thematic-search")
async def debug_thematic_search(
    topic: str,
    difficulty: str = "medium",
    max_words: int = 10,
    request: Request = None
):
    """
    Debug endpoint to test thematic word generation directly.
    """
    try:
        thematic_service = getattr(request.app.state, 'thematic_service', None)
        if not thematic_service or not thematic_service.is_initialized:
            raise HTTPException(status_code=503, detail="Thematic service not available")
        
        result = await thematic_service.find_words_for_crossword([topic], difficulty, max_words)
        words = result["words"]
        
        response = {
            "topic": topic,
            "difficulty": difficulty,
            "max_words": max_words,
            "found_words": len(words),
            "words": words
        }
        
        # Include debug data if available
        if "debug" in result:
            response["debug"] = result["debug"]
        
        return response
        
    except Exception as e:
        logger.error(f"❌ Thematic search debug failed: {e}")
        raise HTTPException(status_code=500, detail=str(e))