File size: 12,145 Bytes
8ff1b66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
"""
Keyword dictionary expansion with exclusive category assignment.

Key principle: Each word can only belong to ONE category.
This prevents cross-contamination where a word like "unplayable"
might be counted in both Bugs and Performance categories.

Algorithm:
1. For each category: find candidate words similar to seed keywords
2. Collect ALL candidates in a global pool
3. Assign each word to the category with highest score
4. Filter by similarity threshold and frequency
"""

import json
import logging
import math
from collections import defaultdict
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path

from gensim.models import FastText

from .config import OUTPUT_DIR, SETTINGS

logger = logging.getLogger(__name__)


@dataclass
class Candidate:
    """A candidate word for dictionary expansion."""

    word: str
    similarity: float
    frequency: int
    source_seeds: list[str] = field(default_factory=list)

    @property
    def score(self) -> float:
        """
        Combined score from similarity and frequency.

        Formula: 0.7 * similarity + 0.3 * normalized_log_frequency
        Frequency factor normalized to ~0-1 range.
        """
        freq_factor = math.log10(max(self.frequency, 1) + 1) / 5
        return self.similarity * 0.7 + freq_factor * 0.3

    def to_dict(self) -> dict:
        return {
            "word": self.word.replace("_", " "),
            "similarity": round(self.similarity, 3),
            "frequency": self.frequency,
            "score": round(self.score, 3),
            "source_seeds": self.source_seeds,
        }


class KeywordExpander:
    """
    Expands keyword dictionary using trained FastText model.

    Uses exclusive category assignment to prevent words
    appearing in multiple categories.
    """

    def __init__(
        self,
        model: FastText,
        existing_keywords: dict[str, list[str]],
        word_frequencies: dict[str, int],
        similarity_threshold: float | None = None,
        max_suggestions_per_seed: int | None = None,
        min_frequency: int | None = None,
    ):
        """
        Initialize expander.

        Args:
            model: Trained FastText model
            existing_keywords: Current TOPIC_KEYWORDS dictionary
            word_frequencies: Word frequency counts from corpus
            similarity_threshold: Minimum similarity for candidates
            max_suggestions_per_seed: Max similar words per seed
            min_frequency: Minimum corpus frequency
        """
        self.model = model
        self.existing = existing_keywords
        self.word_freq = word_frequencies

        self.similarity_threshold = similarity_threshold or SETTINGS["similarity_threshold"]
        self.max_suggestions = max_suggestions_per_seed or SETTINGS["max_suggestions_per_seed"]
        self.min_frequency = min_frequency or SETTINGS["min_frequency"]

        # Build set of all existing words (normalized)
        self.existing_words: set[str] = set()
        for words in existing_keywords.values():
            for w in words:
                self.existing_words.add(w.lower().replace(" ", "_"))

        logger.info(f"Expander initialized with {len(self.existing_words)} existing keywords")

    def _find_candidates_for_category(
        self,
        category: str,
        seeds: list[str],
    ) -> dict[str, Candidate]:
        """
        Find candidate words for a single category.

        Returns dict[word -> Candidate] with best similarity per word.
        """
        candidates: dict[str, Candidate] = {}

        for seed in seeds:
            # Normalize seed (e.g., "frame rate" -> "frame_rate")
            seed_normalized = seed.lower().replace(" ", "_")

            # Skip if seed not in vocabulary
            if seed_normalized not in self.model.wv:
                continue

            # Get similar words
            try:
                similar = self.model.wv.most_similar(
                    seed_normalized,
                    topn=self.max_suggestions,
                )
            except KeyError:
                continue

            for word, similarity in similar:
                # Skip existing words
                if word in self.existing_words:
                    continue

                # Skip below threshold
                if similarity < self.similarity_threshold:
                    continue

                # Check frequency
                freq = self.word_freq.get(word, 0)
                if freq < self.min_frequency:
                    continue

                # Update or add candidate
                if word in candidates:
                    # Keep higher similarity
                    if similarity > candidates[word].similarity:
                        candidates[word].similarity = similarity
                    candidates[word].source_seeds.append(seed)
                else:
                    candidates[word] = Candidate(
                        word=word,
                        similarity=similarity,
                        frequency=freq,
                        source_seeds=[seed],
                    )

        return candidates

    def expand_all_exclusive(self) -> dict[str, list[Candidate]]:
        """
        Expand all categories with exclusive assignment.

        Each word is assigned only to the category where it has
        the highest score.

        Returns:
            Dict mapping category -> list of Candidates (sorted by score)
        """
        logger.info("Starting exclusive expansion...")

        # Step 1: Collect candidates from all categories
        # Format: word -> [(category, Candidate), ...]
        all_candidates: dict[str, list[tuple[str, Candidate]]] = defaultdict(list)

        for category, seeds in self.existing.items():
            category_candidates = self._find_candidates_for_category(category, seeds)
            for word, candidate in category_candidates.items():
                all_candidates[word].append((category, candidate))

            logger.info(f"[{category}] Found {len(category_candidates)} raw candidates")

        # Step 2: Assign each word to category with highest score
        final_assignments: dict[str, list[Candidate]] = defaultdict(list)

        for word, category_candidates in all_candidates.items():
            # Find category with highest score
            best_category, best_candidate = max(
                category_candidates,
                key=lambda x: x[1].score,
            )
            final_assignments[best_category].append(best_candidate)

        # Step 3: Sort candidates in each category by score
        for category in final_assignments:
            final_assignments[category].sort(key=lambda c: c.score, reverse=True)

        # Log results
        total = sum(len(cands) for cands in final_assignments.values())
        logger.info(f"Exclusive assignment complete: {total} total candidates")

        for category, cands in sorted(final_assignments.items()):
            logger.info(f"  {category}: {len(cands)} candidates")

        return dict(final_assignments)

    def export_candidates(
        self,
        path: Path | str | None = None,
        include_threshold_in_name: bool = False,
    ) -> Path:
        """
        Export candidates to JSON for manual review.

        Args:
            path: Output path (default: output/candidates.json)
            include_threshold_in_name: Add threshold to filename for comparison

        Returns:
            Path to exported file
        """
        if path:
            path = Path(path)
        elif include_threshold_in_name:
            path = OUTPUT_DIR / f"candidates_t{self.similarity_threshold:.2f}.json"
        else:
            path = OUTPUT_DIR / "candidates.json"

        results = self.expand_all_exclusive()

        export_data = {
            "metadata": {
                "generated_at": datetime.now().isoformat(),
                "similarity_threshold": self.similarity_threshold,
                "min_frequency": self.min_frequency,
                "total_candidates": sum(len(c) for c in results.values()),
            },
            "categories": {},
        }

        for category, candidates in sorted(results.items()):
            export_data["categories"][category] = [c.to_dict() for c in candidates]

        with open(path, "w", encoding="utf-8") as f:
            json.dump(export_data, f, indent=2, ensure_ascii=False)

        logger.info(f"Exported candidates to {path}")
        return path

    def generate_keywords_py(
        self,
        output_path: Path | str | None = None,
        auto_approve_threshold: float | None = None,
    ) -> Path:
        """
        Generate new keywords.py with expanded dictionary.

        Words with score >= auto_approve_threshold are added directly.
        Words below threshold are added as comments for manual review.

        Args:
            output_path: Output path (default: output/keywords_expanded.py)
            auto_approve_threshold: Score threshold for auto-approval

        Returns:
            Path to generated file
        """
        output_path = Path(output_path) if output_path else OUTPUT_DIR / "keywords_expanded.py"
        auto_approve = auto_approve_threshold or SETTINGS["auto_approve_threshold"]

        results = self.expand_all_exclusive()

        lines = [
            '"""',
            "Expanded keyword dictionary for game review topic detection.",
            f"Generated: {datetime.now().isoformat()}",
            f"Auto-approve threshold: {auto_approve}",
            '"""',
            "",
            "TOPIC_KEYWORDS = {",
        ]

        for category, seeds in self.existing.items():
            lines.append(f'    "{category}": [')

            # Existing keywords
            lines.append("        # Existing")
            for seed in seeds:
                lines.append(f'        "{seed}",')

            # New candidates
            candidates = results.get(category, [])
            if candidates:
                # Auto-approved
                auto_approved = [c for c in candidates if c.score >= auto_approve]
                if auto_approved:
                    lines.append(f"        # NEW (auto-approved, score >= {auto_approve})")
                    for c in auto_approved:
                        word_display = c.word.replace("_", " ")
                        lines.append(f'        "{word_display}",  # score={c.score:.2f}')

                # Candidates requiring review
                review_needed = [c for c in candidates if c.score < auto_approve]
                if review_needed:
                    lines.append(f"        # CANDIDATES (score < {auto_approve}, require review)")
                    for c in review_needed:
                        word_display = c.word.replace("_", " ")
                        lines.append(f'        # "{word_display}",  # score={c.score:.2f}')

            lines.append("    ],")
            lines.append("")

        lines.append("}")
        lines.append("")

        with open(output_path, "w", encoding="utf-8") as f:
            f.write("\n".join(lines))

        logger.info(f"Generated keywords file at {output_path}")
        return output_path

    def get_expansion_stats(self) -> dict:
        """Get statistics about the expansion."""
        results = self.expand_all_exclusive()
        auto_threshold = SETTINGS["auto_approve_threshold"]

        stats = {
            "total_candidates": 0,
            "auto_approved": 0,
            "needs_review": 0,
            "by_category": {},
        }

        for category, candidates in results.items():
            auto = sum(1 for c in candidates if c.score >= auto_threshold)
            review = len(candidates) - auto

            stats["by_category"][category] = {
                "total": len(candidates),
                "auto_approved": auto,
                "needs_review": review,
            }
            stats["total_candidates"] += len(candidates)
            stats["auto_approved"] += auto
            stats["needs_review"] += review

        return stats