Celeskry commited on
Commit
08a412f
·
verified ·
1 Parent(s): e24dad0

Update app/noi_tu.py

Browse files
Files changed (1) hide show
  1. app/noi_tu.py +46 -27
app/noi_tu.py CHANGED
@@ -1,30 +1,49 @@
1
- # Thêm vào đầu file main.py (sau các import hiện có)
2
  import httpx
3
- from cachetools import TTLCache
4
- from fastapi import Querẻy
5
 
6
- word_cache = TTLCache(maxsize=1, ttl=86400)
 
 
 
7
 
8
- async def load_noi_tu_words():
9
- if "words" in word_cache:
10
- return word_cache["words"]
11
-
12
- url = "https://github.com/NNBnh/noi-tu/raw/refs/heads/main/words/words.txt"
13
-
14
- try:
15
- async with httpx.AsyncClient() as client:
16
- resp = await client.get(url, timeout=10.0)
17
- resp.raise_for_status()
18
- lines = resp.text.strip().splitlines()
19
- # Filter chỉ giữ từ có đúng 2 âm tiết (split() == 2)
20
- filtered = []
21
- for line in lines:
22
- tu = line.strip().lower()
23
- if tu and len(tu.split()) == 2: # chỉ 2 âm tiết
24
- filtered.append(tu)
25
- word_cache["words"] = set(filtered) # dùng set để check nhanh
26
- print(f"Loaded {len(word_cache['words'])} từ ghép 2 âm tiết từ NNBnh/noi-tu")
27
- return word_cache["words"]
28
- except Exception as e:
29
- print(f"Error loading words: {e}")
30
- return set()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import httpx
2
+ import random
3
+ from typing import Optional
4
 
5
+ class NoiTuApp:
6
+ def __init__(self):
7
+ self.url = "https://github.com/NNBnh/noi-tu/raw/refs/heads/main/words/words.txt"
8
+ self.words = set()
9
 
10
+ async def start(self):
11
+ """Tải dữ liệu từ vựng khi khởi động server"""
12
+ try:
13
+ async with httpx.AsyncClient(timeout=30.0) as client:
14
+ response = await client.get(self.url)
15
+ if response.status_code == 200:
16
+ # Tách từ theo dòng, chuyển về chữ thường và strip khoảng trắng
17
+ self.words = {line.strip().lower() for line in response.text.splitlines() if line.strip()}
18
+ print(f"Loaded {len(self.words)} words for NoiTuApp")
19
+ else:
20
+ print(f"Failed to load words: {response.status_code}")
21
+ except Exception as e:
22
+ print(f"Error loading words: {e}")
23
+
24
+ async def stop(self):
25
+ self.words.clear()
26
+
27
+ def get_next_word(self, current_word: str) -> Optional[str]:
28
+ """Tìm một từ bắt đầu bằng tiếng cuối của từ hiện tại"""
29
+ current_word = current_word.lower().strip()
30
+ parts = current_word.split()
31
+
32
+ # Lấy tiếng cuối cùng (ví dụ: "học sinh" -> "sinh")
33
+ last_syllable = parts[-1]
34
+
35
+ # Tìm các từ trong danh sách bắt đầu bằng last_syllable
36
+ # Và phải là từ có ít nhất 2 tiếng (để game tiếp tục được)
37
+ candidates = [
38
+ w for w in self.words
39
+ if w.startswith(last_syllable + " ") and w != current_word
40
+ ]
41
+
42
+ if not candidates:
43
+ return None
44
+
45
+ return random.choice(candidates)
46
+
47
+ def is_valid_word(self, word: str) -> bool:
48
+ """Kiểm tra từ có trong từ điển không"""
49
+ return word.lower().strip() in self.words