root39058 commited on
Commit
f3d8e75
·
verified ·
1 Parent(s): 14f0f34

Create Example_Loader.py

Browse files
Files changed (1) hide show
  1. Example_Loader.py +356 -0
Example_Loader.py ADDED
@@ -0,0 +1,356 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import numpy as np
4
+ import random
5
+ import os
6
+ import io
7
+ import http.server
8
+ import socketserver
9
+ from PIL import Image, ImageDraw, ImageFont
10
+ import json
11
+
12
+ # ============================================================
13
+ # 1. НЕЙРОСЕТЬ
14
+ # ============================================================
15
+
16
+ class AndreyNN(nn.Module):
17
+ def __init__(self, vocab_size):
18
+ super().__init__()
19
+ self.fc1 = nn.Linear(vocab_size, 128)
20
+ self.fc2 = nn.Linear(128, 128)
21
+ self.fc3 = nn.Linear(128, 64)
22
+ self.fc4 = nn.Linear(64, 32)
23
+ self.fc5 = nn.Linear(32, vocab_size)
24
+ self.relu = nn.ReLU()
25
+ self.dropout = nn.Dropout(0.2)
26
+ self.softmax = nn.Softmax(dim=1)
27
+
28
+ def forward(self, x):
29
+ x = self.relu(self.fc1(x))
30
+ x = self.dropout(x)
31
+ x = self.relu(self.fc2(x))
32
+ x = self.dropout(x)
33
+ x = self.relu(self.fc3(x))
34
+ x = self.dropout(x)
35
+ x = self.relu(self.fc4(x))
36
+ x = self.softmax(self.fc5(x))
37
+ return x
38
+
39
+ # ============================================================
40
+ # 2. ЗАГРУЗЧИК
41
+ # ============================================================
42
+
43
+ class AndreyWorldLoader:
44
+ def __init__(self, model_path='andrey_world_model.pt', device='cpu'):
45
+ self.device = torch.device(device)
46
+
47
+ if not os.path.exists(model_path):
48
+ raise FileNotFoundError(f"Файл {model_path} не найден!")
49
+
50
+ checkpoint = torch.load(model_path, map_location='cpu')
51
+
52
+ self.vocab = checkpoint['vocab']
53
+ self.word_to_idx = checkpoint['word_to_idx']
54
+ self.idx_to_word = checkpoint['idx_to_word']
55
+ self.vocab_size = checkpoint['vocab_size']
56
+ self.is_trained = checkpoint['is_trained']
57
+
58
+ self.model = AndreyNN(self.vocab_size).to(self.device)
59
+ self.model.load_state_dict(checkpoint['model_state'])
60
+ self.model.eval()
61
+
62
+ self.themes = ['свет', 'тьма', 'вода', 'огонь', 'ветер', 'земля']
63
+ self.colors = ['золотой', 'синий', 'зелёный', 'розовый', 'фиолетовый', 'голубой']
64
+ self.creatures = ['существа', 'птицы', 'змеи', 'великаны', 'духи', 'кони']
65
+ self.places = ['долина', 'гора', 'лес', 'пустыня', 'океан', 'небо']
66
+
67
+ print(f"[ГОТОВО] Модель загружена! Словарь: {self.vocab_size} слов")
68
+
69
+ def generate_word(self, context=None):
70
+ x = np.zeros(self.vocab_size)
71
+ if context:
72
+ for word in context:
73
+ if word in self.word_to_idx:
74
+ x[self.word_to_idx[word]] = 1
75
+
76
+ if np.sum(x) == 0:
77
+ x[np.random.randint(0, self.vocab_size)] = 1
78
+
79
+ x_tensor = torch.tensor(x, dtype=torch.float32).to(self.device).unsqueeze(0)
80
+
81
+ with torch.no_grad():
82
+ output = self.model(x_tensor)
83
+ probs = output.cpu().numpy()[0]
84
+ probs = probs / np.sum(probs)
85
+ idx = np.random.choice(self.vocab_size, p=probs)
86
+ return self.idx_to_word[idx]
87
+
88
+ def generate_world(self):
89
+ theme = self.generate_word(['мир', 'из'])
90
+ color = self.generate_word(['цвет', 'как'])
91
+ creature = self.generate_word(['существо', 'живёт'])
92
+ place = self.generate_word(['место', 'где'])
93
+
94
+ if theme not in self.themes:
95
+ theme = random.choice(self.themes)
96
+ if color not in self.colors:
97
+ color = random.choice(self.colors)
98
+ if creature not in self.creatures:
99
+ creature = random.choice(self.creatures)
100
+ if place not in self.places:
101
+ place = random.choice(self.places)
102
+
103
+ prefixes = ["Великий", "Тихий", "Золотой", "Древний", "Светлый", "Тёмный"]
104
+ name = f"{random.choice(prefixes)} {place.capitalize()}"
105
+
106
+ desc_parts = [
107
+ f"Мир, где всё состоит из {theme}.",
108
+ f"Здесь {creature} охраняют {place}.",
109
+ f"{color.capitalize()} {place} наполнен {theme}.",
110
+ f"{creature} танцуют в {place}."
111
+ ]
112
+ description = ' '.join(random.sample(desc_parts, 2))
113
+
114
+ return {
115
+ 'name': name,
116
+ 'description': description,
117
+ 'theme': theme,
118
+ 'color': color,
119
+ 'creature': creature,
120
+ 'place': place
121
+ }
122
+
123
+ # ============================================================
124
+ # 3. ГЕНЕРАЦИЯ КАРТИНКИ МИРА
125
+ # ============================================================
126
+
127
+ def generate_world_image(world_data, size=(640, 480)):
128
+ img = Image.new('RGB', size, color=(20, 20, 40))
129
+ draw = ImageDraw.Draw(img)
130
+
131
+ colors = {
132
+ 'свет': (255, 240, 200),
133
+ 'тьма': (30, 30, 60),
134
+ 'вода': (0, 100, 200),
135
+ 'огонь': (255, 100, 50),
136
+ 'ветер': (180, 200, 220),
137
+ 'земля': (120, 80, 40)
138
+ }
139
+
140
+ base_color = colors.get(world_data.get('theme', 'свет'), (50, 50, 80))
141
+
142
+ for y in range(size[1]):
143
+ r = int(base_color[0] * (0.5 + 0.5 * y / size[1]))
144
+ g = int(base_color[1] * (0.5 + 0.5 * y / size[1]))
145
+ b = int(base_color[2] * (0.5 + 0.5 * y / size[1]))
146
+ draw.line([(0, y), (size[0], y)], fill=(r, g, b))
147
+
148
+ ground_y = int(size[1] * 0.6)
149
+ draw.rectangle([(0, ground_y), (size[0], size[1])], fill=(60, 40, 20))
150
+
151
+ for _ in range(30):
152
+ x = random.randint(0, size[0])
153
+ y = random.randint(ground_y, size[1])
154
+ h = random.randint(5, 15)
155
+ draw.line([(x, y), (x + random.randint(-3, 3), y - h)], fill=(50, 150, 50), width=1)
156
+
157
+ for _ in range(random.randint(3, 5)):
158
+ cx = random.randint(100, size[0] - 100)
159
+ cy = ground_y - random.randint(30, 100)
160
+ r = random.randint(60, 150)
161
+ draw.ellipse([(cx - r, cy - r), (cx + r, cy + r)], fill=(100, 80, 60))
162
+
163
+ sx = random.randint(50, 200)
164
+ sy = random.randint(30, 100)
165
+ draw.ellipse([(sx - 30, sy - 30), (sx + 30, sy + 30)], fill=(255, 200, 100))
166
+
167
+ if world_data.get('theme') == 'тьма':
168
+ for _ in range(50):
169
+ sx2 = random.randint(0, size[0])
170
+ sy2 = random.randint(0, ground_y)
171
+ br = random.randint(1, 3)
172
+ draw.ellipse([(sx2 - br, sy2 - br), (sx2 + br, sy2 + br)], fill=(255, 255, 200))
173
+
174
+ for _ in range(random.randint(8, 15)):
175
+ tx = random.randint(0, size[0])
176
+ ty = ground_y + random.randint(0, 30)
177
+ draw.rectangle([(tx - 3, ty - 20), (tx + 3, ty)], fill=(80, 50, 30))
178
+ cr = random.randint(15, 30)
179
+ draw.ellipse([(tx - cr, ty - 20 - cr), (tx + cr, ty - 20 + cr)], fill=(40, 140, 40))
180
+
181
+ for _ in range(random.randint(3, 6)):
182
+ ox = random.randint(0, size[0])
183
+ oy = random.randint(20, ground_y - 50)
184
+ ow = random.randint(60, 120)
185
+ oh = random.randint(20, 40)
186
+ draw.ellipse([(ox, oy), (ox + ow, oy + oh)], fill=(200, 200, 220, 100))
187
+
188
+ try:
189
+ font = ImageFont.load_default()
190
+ draw.text((20, 20), f"🌍 {world_data.get('name', '')}", fill=(255, 255, 255), font=font)
191
+ draw.text((20, 50), f"🏷️ {world_data.get('theme', '')} | {world_data.get('color', '')}", fill=(200, 200, 200), font=font)
192
+ draw.text((20, 80), f"🦄 {world_data.get('description', '')[:50]}...", fill=(180, 180, 180), font=font)
193
+ except:
194
+ pass
195
+
196
+ draw.rectangle([(0, 0), (size[0]-1, size[1]-1)], outline=(100, 100, 150), width=2)
197
+
198
+ return img
199
+
200
+ # ============================================================
201
+ # 4. HTTP-СЕРВЕР
202
+ # ============================================================
203
+
204
+ # Загружаем модель
205
+ loader = AndreyWorldLoader('andrey_world_model.pt')
206
+
207
+ class WorldHandler(http.server.BaseHTTPRequestHandler):
208
+ def log_message(self, format, *args):
209
+ pass
210
+
211
+ def do_GET(self):
212
+ if self.path == '/':
213
+ # Генерируем мир
214
+ world = loader.generate_world()
215
+ img = generate_world_image(world)
216
+
217
+ # Сохраняем в буфер
218
+ buffer = io.BytesIO()
219
+ img.save(buffer, format='PNG')
220
+ img_data = buffer.getvalue()
221
+
222
+ # Страница
223
+ html = f'''
224
+ <!DOCTYPE html>
225
+ <html>
226
+ <head>
227
+ <title>AndreyWorld</title>
228
+ <meta http-equiv="refresh" content="10">
229
+ <style>
230
+ body {{
231
+ background: #0d0d1a;
232
+ color: #e0e0e0;
233
+ font-family: 'Segoe UI', sans-serif;
234
+ display: flex;
235
+ justify-content: center;
236
+ align-items: center;
237
+ height: 100vh;
238
+ margin: 0;
239
+ padding: 20px;
240
+ }}
241
+ .container {{
242
+ max-width: 900px;
243
+ width: 100%;
244
+ background: #1a1a2e;
245
+ padding: 30px;
246
+ border-radius: 20px;
247
+ border: 1px solid #2a2a4e;
248
+ box-shadow: 0 0 50px rgba(0,0,0,0.8);
249
+ text-align: center;
250
+ }}
251
+ h1 {{
252
+ color: #6a8fbd;
253
+ margin-top: 0;
254
+ }}
255
+ img {{
256
+ width: 100%;
257
+ border-radius: 15px;
258
+ border: 2px solid #2a2a4e;
259
+ margin: 15px 0;
260
+ }}
261
+ .info {{
262
+ background: #0d0d1a;
263
+ padding: 15px;
264
+ border-radius: 10px;
265
+ margin: 10px 0;
266
+ }}
267
+ .tag {{
268
+ display: inline-block;
269
+ background: #2a2a4e;
270
+ padding: 4px 12px;
271
+ border-radius: 12px;
272
+ margin: 3px;
273
+ font-size: 0.9em;
274
+ }}
275
+ .meta {{
276
+ color: #666;
277
+ font-size: 0.85em;
278
+ margin-top: 15px;
279
+ }}
280
+ .refresh {{
281
+ color: #4a6fa5;
282
+ text-decoration: none;
283
+ }}
284
+ </style>
285
+ </head>
286
+ <body>
287
+ <div class="container">
288
+ <h1>🌍 AndreyWorld</h1>
289
+ <div class="info">
290
+ <h2>🌍 {world.get('name', '')}</h2>
291
+ <p>{world.get('description', '')}</p>
292
+ <div>
293
+ <span class="tag">🏷️ {world.get('theme', '')}</span>
294
+ <span class="tag">🎨 {world.get('color', '')}</span>
295
+ <span class="tag">🦄 {world.get('creature', '')}</span>
296
+ <span class="tag">📍 {world.get('place', '')}</span>
297
+ </div>
298
+ </div>
299
+ <img src="/world.png" alt="AndreyWorld">
300
+ <div class="meta">
301
+ 🔄 Страница обновляется каждые 10 секунд<br>
302
+ 📡 <a href="/" class="refresh">Обновить сейчас</a>
303
+ </div>
304
+ </div>
305
+ </body>
306
+ </html>
307
+ '''
308
+
309
+ self.send_response(200)
310
+ self.send_header('Content-Type', 'text/html; charset=utf-8')
311
+ self.end_headers()
312
+ self.wfile.write(html.encode('utf-8'))
313
+
314
+ elif self.path == '/world.png':
315
+ # Генерируем новый мир и отдаём картинку
316
+ world = loader.generate_world()
317
+ img = generate_world_image(world)
318
+
319
+ buffer = io.BytesIO()
320
+ img.save(buffer, format='PNG')
321
+ img_data = buffer.getvalue()
322
+
323
+ self.send_response(200)
324
+ self.send_header('Content-Type', 'image/png')
325
+ self.end_headers()
326
+ self.wfile.write(img_data)
327
+
328
+ else:
329
+ self.send_response(404)
330
+ self.end_headers()
331
+ self.wfile.write(b'Not Found')
332
+
333
+ # ============================================================
334
+ # 5. ЗАПУСК
335
+ # ============================================================
336
+
337
+ def main():
338
+ PORT = 6767
339
+
340
+ print("\n" + "="*50)
341
+ print("🌍 ANDREYWORLD")
342
+ print(" http://localhost:" + str(PORT))
343
+ print("="*50 + "\n")
344
+
345
+ with socketserver.TCPServer(("", PORT), WorldHandler) as httpd:
346
+ print(f"[ГОТОВО] Сервер запущен на порту {PORT}")
347
+ print(f"[ССЫЛКА] Открой http://localhost:{PORT}")
348
+ print("[ИНФО] Страница обновляется каждые 10 секунд\n")
349
+ try:
350
+ httpd.serve_forever()
351
+ except KeyboardInterrupt:
352
+ print("\n[СТОП] Остановка...")
353
+ httpd.shutdown()
354
+
355
+ if __name__ == "__main__":
356
+ main()