ihhereanth commited on
Commit
8126cff
·
verified ·
1 Parent(s): 895603b

Delete main.py

Browse files
Files changed (1) hide show
  1. main.py +0 -330
main.py DELETED
@@ -1,330 +0,0 @@
1
- import os
2
- import time
3
- import threading
4
- import random
5
- import logging
6
- import requests
7
- import torch
8
- from flask import Flask, request, jsonify
9
-
10
- # --- CONFIGURATION ---
11
- MAX_IDLE_TIME = 3600
12
- CLEANUP_INTERVAL = 300
13
-
14
- # 🟢 1. อัปเดตชื่อไฟล์ให้ตรงกับที่เราเพิ่งสร้างจาก Colab
15
- VECTOR_FILE = "contexto_glove_whitened_80k.pt"
16
-
17
- # --- คำศัพท์ลับ (Secret Words) สำหรับภาษาอังกฤษ 1000+ คำ ---
18
- SECRET_WORDS = [
19
- # 👨‍👩‍👧‍👦 Family, People & Professions
20
- "father", "mother", "son", "daughter", "brother", "sister", "grandfather", "grandmother",
21
- "uncle", "aunt", "cousin", "nephew", "niece", "husband", "wife", "boy", "girl", "man", "woman",
22
- "friend", "child", "baby", "neighbor", "teacher", "student", "doctor", "nurse", "police", "soldier",
23
- "king", "queen", "prince", "princess", "actor", "actress", "singer", "dancer", "writer", "artist",
24
- "chef", "pilot", "driver", "farmer", "engineer", "scientist", "lawyer", "judge", "president", "mayor",
25
- "manager", "worker", "boss", "hero", "villain", "wizard", "witch", "ghost", "zombie", "alien",
26
- "monster", "giant", "dwarf", "elf", "fairy", "pirate", "ninja", "knight", "guard", "thief", "spy",
27
- "hunter", "player", "coach", "referee", "fan", "passenger", "guest", "host", "owner", "customer",
28
- "client", "patient", "victim", "winner", "loser", "adult", "teenager", "youth", "orphan", "twin",
29
- "widow", "bride", "groom", "citizen", "human", "person",
30
-
31
- # 🐶 Animals & Insects
32
- "dog", "cat", "bird", "fish", "chicken", "cow", "pig", "horse", "lion", "tiger", "bear",
33
- "elephant", "monkey", "mouse", "rabbit", "snake", "wolf", "fox", "eagle", "shark", "whale",
34
- "dolphin", "butterfly", "spider", "ant", "bee", "fly", "mosquito", "beetle", "worm", "frog",
35
- "toad", "turtle", "lizard", "crocodile", "alligator", "dinosaur", "dragon", "bat", "penguin",
36
- "ostrich", "owl", "parrot", "duck", "goose", "swan", "pigeon", "turkey", "sheep", "goat", "deer",
37
- "camel", "giraffe", "zebra", "rhino", "hippo", "kangaroo", "koala", "panda", "gorilla", "chimpanzee",
38
- "ape", "seal", "walrus", "crab", "lobster", "shrimp", "octopus", "squid", "jellyfish", "starfish",
39
- "seahorse", "snail", "slug", "cheetah", "leopard", "panther", "puma", "jaguar", "hyena", "badger",
40
- "beaver", "otter", "squirrel", "chipmunk", "raccoon", "skunk", "porcupine", "hedgehog", "mole", "rat",
41
- "pony", "donkey", "mule", "puppy", "kitten", "calf", "foal", "cub",
42
-
43
- # 🏠 House, Furniture & Objects
44
- "house", "home", "apartment", "building", "room", "kitchen", "bathroom", "bedroom", "livingroom",
45
- "basement", "attic", "roof", "wall", "floor", "ceiling", "door", "window", "stairs", "elevator",
46
- "table", "chair", "bed", "desk", "sofa", "couch", "cabinet", "shelf", "closet", "drawer", "mirror",
47
- "clock", "lamp", "light", "fan", "heater", "airconditioner", "television", "radio", "computer",
48
- "laptop", "phone", "camera", "battery", "charger", "wire", "plug", "socket", "key", "lock", "frame",
49
- "picture", "painting", "rug", "carpet", "curtain", "blanket", "pillow", "towel", "sheet", "soap",
50
- "shampoo", "brush", "comb", "toothbrush", "toothpaste", "sponge", "trash", "bin", "bucket", "basket",
51
- "broom", "mop", "vacuum", "iron", "board", "scissors", "knife", "fork", "spoon", "plate", "bowl",
52
- "cup", "glass", "mug", "pitcher", "pot", "pan", "oven", "stove", "microwave", "fridge", "freezer",
53
- "sink", "toilet", "shower", "bathtub", "pipe", "tap", "chimney", "fence", "gate", "pool", "garden", "yard",
54
-
55
- # 👕 Clothing & Accessories
56
- "clothes", "shirt", "pants", "jeans", "shorts", "dress", "skirt", "suit", "tie", "coat", "jacket",
57
- "sweater", "hoodie", "sock", "shoe", "boot", "sandal", "slipper", "hat", "cap", "helmet", "glove",
58
- "scarf", "belt", "glasses", "sunglasses", "ring", "necklace", "bracelet", "earring", "watch", "wallet",
59
- "purse", "bag", "backpack", "umbrella", "zipper", "button", "pocket", "sleeve", "collar", "cotton",
60
- "silk", "wool", "leather", "uniform", "costume", "pajamas", "underwear", "bra",
61
-
62
- # 🚗 Transport & Travel
63
- "car", "bus", "train", "airplane", "boat", "ship", "bicycle", "motorcycle", "truck", "van", "taxi",
64
- "ambulance", "policecar", "firetruck", "helicopter", "rocket", "spaceship", "submarine", "yacht",
65
- "ferry", "raft", "sail", "wheel", "tire", "engine", "motor", "steering", "brake", "pedal", "seat",
66
- "street", "road", "highway", "bridge", "tunnel", "path", "trail", "track", "station", "airport",
67
- "port", "harbor", "ticket", "passport", "luggage", "suitcase", "map", "compass",
68
-
69
- # 🌳 Nature, Weather & Space
70
- "sun", "moon", "star", "planet", "earth", "mars", "jupiter", "venus", "galaxy", "universe", "space",
71
- "sky", "cloud", "rain", "snow", "hail", "ice", "frost", "wind", "storm", "thunder", "lightning",
72
- "hurricane", "tornado", "fog", "mist", "weather", "climate", "season", "spring", "summer", "autumn",
73
- "winter", "day", "night", "morning", "evening", "afternoon", "midnight", "dawn", "dusk", "light",
74
- "dark", "shadow", "ray", "beam", "water", "fire", "air", "sea", "ocean", "river", "lake", "pond",
75
- "stream", "waterfall", "wave", "tide", "beach", "coast", "shore", "island", "mountain", "hill",
76
- "valley", "canyon", "cave", "forest", "jungle", "woods", "desert", "plain", "field", "meadow", "swamp",
77
- "rock", "stone", "pebble", "sand", "dirt", "soil", "mud", "clay", "dust", "ash", "smoke", "steam",
78
-
79
- # 🌿 Plants & Agriculture
80
- "tree", "flower", "leaf", "grass", "plant", "bush", "shrub", "branch", "root", "trunk", "bark",
81
- "stem", "seed", "thorn", "vine", "weed", "moss", "fern", "rose", "lily", "tulip", "daisy", "sunflower",
82
- "orchid", "lotus", "bamboo", "pine", "oak", "maple", "palm", "crop", "harvest", "farm", "barn",
83
- "tractor", "plow", "hay", "straw", "grain", "wheat", "corn", "rice", "oat", "fertilizer", "greenhouse",
84
-
85
- # 🍔 Food & Drink
86
- "food", "drink", "milk", "coffee", "tea", "juice", "soda", "beer", "wine", "alcohol", "soup",
87
- "salad", "meat", "beef", "pork", "seafood", "egg", "cheese", "butter", "yogurt", "cream", "bread",
88
- "toast", "sandwich", "burger", "hotdog", "pizza", "pasta", "noodle", "bean", "nut", "peanut",
89
- "almond", "walnut", "fruit", "apple", "banana", "orange", "lemon", "lime", "grape", "berry",
90
- "strawberry", "blueberry", "cherry", "peach", "plum", "melon", "watermelon", "pineapple", "mango",
91
- "coconut", "vegetable", "tomato", "potato", "onion", "garlic", "carrot", "pea", "pepper", "cabbage",
92
- "lettuce", "spinach", "broccoli", "mushroom", "cucumber", "pumpkin", "spice", "salt", "sugar",
93
- "honey", "syrup", "sauce", "ketchup", "mustard", "mayo", "oil", "vinegar", "dessert", "cake", "cookie",
94
- "pie", "candy", "chocolate", "icecream", "pudding", "jelly", "gum", "snack", "chip", "popcorn",
95
-
96
- # 🏃‍♂️ Body & Health
97
- "body", "head", "face", "eye", "ear", "nose", "mouth", "lip", "tooth", "tongue", "chin", "cheek",
98
- "jaw", "neck", "throat", "shoulder", "arm", "elbow", "wrist", "hand", "finger", "thumb", "chest",
99
- "breast", "back", "spine", "belly", "stomach", "waist", "hip", "leg", "knee", "ankle", "foot", "toe",
100
- "heel", "skin", "hair", "nail", "bone", "muscle", "joint", "skull", "rib", "blood", "vein", "heart",
101
- "lung", "brain", "liver", "kidney", "sweat", "tear", "breath", "voice", "disease", "illness",
102
- "sickness", "cold", "flu", "fever", "cough", "pain", "ache", "wound", "cut", "bruise", "scar",
103
- "injury", "medicine", "pill", "drug", "poison", "cure", "health", "clinic", "pharmacy", "surgery",
104
- "operation", "bandage", "cast", "wheelchair", "crutch",
105
-
106
- # 🎨 Colors, Shapes & Math
107
- "color", "red", "blue", "green", "yellow", "white", "black", "gray", "orange", "pink", "purple",
108
- "brown", "silver", "gold", "clear", "bright", "pale", "shape", "circle", "square", "triangle",
109
- "rectangle", "oval", "sphere", "cube", "pyramid", "cone", "cylinder", "line", "point", "angle",
110
- "edge", "corner", "center", "cross", "math", "number", "zero", "one", "two", "three", "four", "five",
111
- "ten", "hundred", "thousand", "million",
112
-
113
- # 🏙️ Places & Buildings
114
- "place", "location", "spot", "area", "region", "country", "state", "city", "town", "village",
115
- "capital", "neighborhood", "avenue", "square", "block", "castle", "palace", "tower", "fort", "base",
116
- "camp", "tent", "school", "college", "university", "library", "museum", "theater", "cinema",
117
- "stadium", "arena", "park", "zoo", "factory", "plant", "mill", "mine", "office", "bank", "prison",
118
- "jail", "court", "church", "temple", "mosque", "shrine", "store", "shop", "market", "mall",
119
- "supermarket", "bakery", "cafe", "restaurant", "bar", "pub", "club", "hotel", "motel", "resort",
120
- "pier", "dock", "stop", "garage", "parking", "gas", "center", "plaza", "gym", "ruin", "monument", "statue",
121
-
122
- # ⚽ Sports, Games & Entertainment
123
- "sport", "game", "play", "match", "race", "tournament", "team", "score", "goal", "win", "loss", "tie",
124
- "ball", "bat", "racket", "net", "glove", "field", "court", "track", "ring", "soccer", "football",
125
- "basketball", "baseball", "tennis", "golf", "volleyball", "hockey", "cricket", "rugby", "boxing",
126
- "wrestling", "swimming", "running", "jumping", "cycling", "skiing", "skating", "surfing", "sailing",
127
- "fishing", "hunting",
128
-
129
- # 🎸 Art, Music & Media
130
- "art", "music", "song", "sound", "noise", "silence", "tune", "beat", "rhythm", "melody", "harmony",
131
- "instrument", "piano", "guitar", "drum", "violin", "flute", "trumpet", "band", "choir", "concert",
132
- "dance", "ballet", "painting", "drawing", "sketch", "sculpture", "photo", "movie", "film", "video",
133
- "show", "drama", "comedy", "tragedy", "book", "poem", "story", "novel", "magazine", "newspaper",
134
- "news", "letter", "card", "sign", "symbol",
135
-
136
- # 🔧 Tools, Materials & Weapons
137
- "tool", "hammer", "nail", "screw", "screwdriver", "wrench", "saw", "drill", "axe", "shovel", "spade",
138
- "rake", "hose", "rope", "string", "chain", "tape", "glue", "paint", "blade", "sword", "shield",
139
- "bow", "arrow", "spear", "gun", "rifle", "pistol", "bullet", "bomb", "weapon", "armor", "metal",
140
- "iron", "steel", "copper", "brass", "wood", "plastic", "rubber", "cloth",
141
-
142
- # 🧠 Abstract & Concepts
143
- "time", "moment", "second", "minute", "hour", "week", "month", "year", "decade", "century", "today",
144
- "tomorrow", "yesterday", "past", "present", "future", "history", "era", "age", "life", "death",
145
- "birth", "mind", "soul", "spirit", "thought", "idea", "concept", "memory", "dream", "hope", "fear",
146
- "love", "hate", "joy", "sorrow", "anger", "surprise", "disgust", "truth", "lie", "secret", "fact",
147
- "fiction", "real", "fake", "good", "bad", "right", "wrong", "true", "false", "yes", "no", "up",
148
- "down", "left", "front", "top", "bottom", "high", "low", "far", "near", "in", "out", "on", "off",
149
- "over", "under", "big", "small", "large", "tiny", "heavy", "fast", "slow", "hot", "cold", "warm",
150
- "cool", "hard", "soft", "easy", "simple", "complex", "safe", "danger", "peace", "war", "fight",
151
- "battle", "victory", "defeat"
152
- ]
153
-
154
- # --- SETUP ---
155
- log = logging.getLogger('werkzeug')
156
- log.setLevel(logging.ERROR)
157
-
158
- app = Flask(__name__)
159
-
160
- # ตัวแปร Global
161
- vocabulary = []
162
- vocab_vectors = None
163
- valid_secret_words = [] # 🟢 เก็บคำลับที่มีอยู่ในดิกชันนารีแน่ๆ เท่านั้น
164
- active_servers = {}
165
-
166
- def initialize_system():
167
- global vocabulary, vocab_vectors, valid_secret_words
168
- print("------------------------------------------------")
169
- print("🚀 System Initializing... (Contexto Custom GloVe 80k)")
170
-
171
- # โหลด Vectors จากไฟล์
172
- if os.path.exists(VECTOR_FILE):
173
- print(f"💾 Found {VECTOR_FILE}! Loading pre-computed data...")
174
- try:
175
- data = torch.load(VECTOR_FILE, map_location=torch.device('cpu'), weights_only=False)
176
-
177
- vocabulary = data['vocabulary']
178
- vocab_vectors = data['vectors'] # Tensor Shape: [80000, 300]
179
-
180
- # 🟢 ป้องกัน Error: คัดเลือกเฉพาะ SECRET_WORDS ที่มีอยู่ใน vocabulary จริงๆ
181
- valid_secret_words = [w for w in SECRET_WORDS if w in vocabulary]
182
-
183
- print(f"✅ Loaded {len(vocabulary)} words and vectors instantly!")
184
- print(f"🎯 Valid Secret Words pool: {len(valid_secret_words)} words ready.")
185
- except Exception as e:
186
- print(f"❌ Error loading file: {e}")
187
- raise e
188
- else:
189
- print(f"⚠️ {VECTOR_FILE} NOT FOUND! Please upload the file.")
190
- return
191
-
192
- # เริ่มระบบ Garbage Collector
193
- threading.Thread(target=garbage_collector, daemon=True).start()
194
- print("✅ SERVER READY! (Super Fast Mode Activated ⚡)")
195
- print("------------------------------------------------")
196
-
197
- def garbage_collector():
198
- while True:
199
- time.sleep(CLEANUP_INTERVAL)
200
- try:
201
- now = time.time()
202
- to_delete = [sid for sid, data in active_servers.items() if now - data['last_active'] > MAX_IDLE_TIME]
203
- for sid in to_delete:
204
- del active_servers[sid]
205
- if to_delete:
206
- print(f"🧹 Cleaned up {len(to_delete)} inactive servers.", flush=True)
207
- except Exception as e:
208
- print(f"Error in cleanup: {e}", flush=True)
209
-
210
- # เรียก Initializer
211
- initialize_system()
212
-
213
- @app.get("/")
214
- def home():
215
- return f"Contexto High-Speed Server Running! Dict Size: {len(vocabulary)}"
216
-
217
- @app.route('/new_game', methods=['POST'])
218
- def start_new_game():
219
- try:
220
- data = request.json
221
- server_id = data.get('server_id')
222
- if not server_id: return jsonify({"error": "No server_id"}), 400
223
-
224
- if not valid_secret_words:
225
- return jsonify({"error": "SECRET_WORDS is empty or invalid"}), 500
226
-
227
- # 🟢 1. สุ่มคำตอบจากคลัง
228
- secret_word = random.choice(valid_secret_words)
229
-
230
- # 🟢 2. ดึง Vector ของคำลับออกมาจาก Tensor ตรงๆ (ไม่ต้องพึ่ง Model Encode แล้ว!)
231
- secret_idx = vocabulary.index(secret_word)
232
- secret_vec = vocab_vectors[secret_idx]
233
-
234
- # 🟢 3. พลังของคณิตศาสตร์: ทำ Dot Product รวดเดียว 80,000 ตัว (เร็วกว่า for-loop 1,000 เท่า)
235
- # เนื่องจาก Vector ถูกทำ L2 Norm มาแล้ว Dot Product จึงมีค่าเท่ากับ Cosine Similarity เป๊ะ!
236
- scores = torch.mv(vocab_vectors, secret_vec)
237
-
238
- # 🟢 4. เรียงลำดับตัวเลข Index จากคะแนนมากสุด��ปน้อยสุด
239
- sorted_indices = torch.argsort(scores, descending=True).tolist()
240
-
241
- # 🟢 5. แปลง Index กลับเป็นคำศัพท์
242
- sorted_words = [vocabulary[i] for i in sorted_indices]
243
-
244
- # บันทึกสถานะเกม
245
- active_servers[server_id] = {
246
- "words": sorted_words,
247
- "last_active": time.time()
248
- }
249
-
250
- print(f"🔥 GAME START: Server [{server_id}] | Secret: {secret_word}", flush=True)
251
- return jsonify({"message": "OK", "server_id": server_id})
252
-
253
- except Exception as e:
254
- print(f"❌ ERROR: {e}", flush=True)
255
- return jsonify({"error": str(e)}), 500
256
-
257
- @app.route('/guess', methods=['POST'])
258
- def guess_word():
259
- try:
260
- data = request.json
261
- server_id = data.get('server_id')
262
- guess = data.get('word', '').strip().lower()
263
-
264
- if server_id not in active_servers:
265
- return jsonify({"error": "Server not found"}), 404
266
-
267
- active_servers[server_id]['last_active'] = time.time()
268
- ranked_list = active_servers[server_id]['words']
269
-
270
- if guess == ranked_list[0]:
271
- return jsonify({"rank": 1, "word": guess})
272
-
273
- try:
274
- rank = ranked_list.index(guess) + 1
275
- return jsonify({"rank": rank, "word": guess})
276
- except ValueError:
277
- # คำศัพท์ไม่มีในฐานข้อมูล 80k
278
- return jsonify({"rank": 99999, "word": guess})
279
-
280
- except Exception as e:
281
- return jsonify({"error": str(e)}), 500
282
-
283
- @app.route('/hint', methods=['POST'])
284
- def get_hint():
285
- try:
286
- data = request.json
287
- server_id = data.get('server_id')
288
- current_rank = data.get('current_rank')
289
-
290
- if not server_id or server_id not in active_servers:
291
- return jsonify({"error": "Game not found"}), 404
292
-
293
- if current_rank is None:
294
- return jsonify({"error": "current_rank is required"}), 400
295
-
296
- current_rank = int(current_rank)
297
- hint_rank = current_rank // 2
298
-
299
- if hint_rank < 1:
300
- hint_rank = 1
301
-
302
- word_list = active_servers[server_id]['words']
303
-
304
- if hint_rank > len(word_list):
305
- hint_rank = len(word_list)
306
-
307
- hint_word = word_list[hint_rank - 1]
308
-
309
- return jsonify({"rank": hint_rank, "word": hint_word})
310
-
311
- except Exception as e:
312
- return jsonify({"error": str(e)}), 500
313
-
314
- @app.route('/answer', methods=['POST'])
315
- def get_answer():
316
- try:
317
- data = request.json
318
- server_id = data.get('server_id')
319
-
320
- if server_id not in active_servers:
321
- return jsonify({"error": "Game not found"}), 404
322
-
323
- answer = active_servers[server_id]['words'][0]
324
- return jsonify({"answer": answer})
325
-
326
- except Exception as e:
327
- return jsonify({"error": str(e)}), 500
328
-
329
- if __name__ == '__main__':
330
- app.run(host='0.0.0.0', port=7860)