AlphaCNN commited on
Commit
f27802a
Β·
verified Β·
1 Parent(s): 4d99ddc

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +330 -0
  2. requirements.txt +13 -0
app.py ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import numpy as np
3
+ import tensorflow as tf
4
+ from tensorflow.keras import layers
5
+ import sentencepiece as spm
6
+ import requests
7
+ from flask import Flask, request, Response, session, jsonify
8
+ from bs4 import BeautifulSoup
9
+ from huggingface_hub import hf_hub_download
10
+ import uuid
11
+ import os
12
+ import time
13
+ from collections import Counter
14
+
15
+ app = Flask(__name__, static_folder="static")
16
+ app.secret_key = os.urandom(32)
17
+
18
+ # =====================
19
+ # λͺ¨λΈ/ν† ν¬λ‚˜μ΄μ € λ‹€μš΄λ‘œλ“œ
20
+ # =====================
21
+ os.environ["HF_HOME"] = "/tmp/hf_cache"
22
+ hf_token = os.getenv("HF_TOKEN")
23
+
24
+ CHAT_MODEL_PATH = hf_hub_download(
25
+ repo_id="Yuchan5386/lamko-prototype",
26
+ filename="Lamko.weights.h5",
27
+ repo_type="model",
28
+ token=hf_token
29
+ )
30
+ CHAT_TOKENIZER_PATH = hf_hub_download(
31
+ repo_id="Yuchan5386/lamko-prototype",
32
+ filename="ko_unigram.model",
33
+ repo_type="model",
34
+ token=hf_token
35
+ )
36
+
37
+ print(CHAT_MODEL_PATH)
38
+ sp = spm.SentencePieceProcessor()
39
+ sp.load(CHAT_TOKENIZER_PATH)
40
+ pad_id = sp.piece_to_id("<pad>") or 0
41
+ start_id = sp.piece_to_id("<start>") or 1
42
+ end_id = sp.piece_to_id("<end>") or 2
43
+ unk_id = sp.piece_to_id("<unk>") or 3
44
+ sep_id = sp.piece_to_id("<sep>")
45
+ vocab_size = sp.get_piece_size()
46
+ max_len = 125
47
+
48
+ def text_to_ids(text):
49
+ return sp.encode(text, out_type=int)
50
+
51
+ def ids_to_text(ids):
52
+ return sp.decode(ids)
53
+
54
+ class SwiGLU(layers.Layer):
55
+ def __init__(self, d_model, f_d=8/3):
56
+ super().__init__()
57
+ hidden_dim = int(d_model * f_d)
58
+ self.proj = layers.Dense(hidden_dim * 2, use_bias=False, dtype='float32')
59
+ self.out = layers.Dense(d_model, use_bias=False, dtype='float32')
60
+
61
+ def call(self, x):
62
+ x_val, x_gate = tf.split(self.proj(x), 2, axis=-1)
63
+ return self.out(x_val * tf.nn.silu(x_gate))
64
+
65
+ class DilatedConvLayer(layers.Layer):
66
+ def __init__(self, d_model, dilation_rate, dropout_rate=0.1):
67
+ super().__init__()
68
+ self.conv = layers.Conv1D(
69
+ filters=d_model,
70
+ kernel_size=3,
71
+ dilation_rate=dilation_rate,
72
+ padding='causal',
73
+ use_bias=True,
74
+ kernel_initializer='he_normal',
75
+ dtype='float32'
76
+ )
77
+ self.ln = layers.LayerNormalization(epsilon=1e-5, dtype='float32')
78
+ self.dropout = layers.Dropout(dropout_rate)
79
+
80
+ def call(self, x, training=False):
81
+ residual = x
82
+ x = self.conv(x)
83
+ x = self.ln(x + residual)
84
+ x = self.dropout(x, training=training)
85
+ return x
86
+
87
+ class Lamko(tf.keras.Model):
88
+ def __init__(self, vocab_size, max_seq_len, d_model, n_layers, dropout_rate=0.1):
89
+ super().__init__()
90
+ self.token_embedding = layers.Embedding(vocab_size, d_model, dtype='float32')
91
+ self.pos_embedding = layers.Embedding(max_seq_len, d_model, dtype='float32')
92
+
93
+ self.blocks = []
94
+ for i in range(n_layers):
95
+ self.blocks.append(DilatedConvLayer(d_model, 2 ** i, dropout_rate))
96
+ if (i + 1) % 3 == 0:
97
+ self.blocks.append(SwiGLU(d_model))
98
+ self.blocks.append(layers.LayerNormalization(epsilon=1e-5, dtype='float32'))
99
+
100
+ self.ln_f = layers.LayerNormalization(epsilon=1e-5, dtype='float32')
101
+
102
+ def call(self, x, training=False):
103
+ batch_size, seq_len = tf.shape(x)[0], tf.shape(x)[1]
104
+ positions = tf.range(seq_len)[tf.newaxis, :]
105
+ positions = tf.clip_by_value(positions, 0, self.pos_embedding.input_dim - 1)
106
+
107
+ x = self.token_embedding(x) + self.pos_embedding(positions)
108
+
109
+ for block in self.blocks:
110
+ if isinstance(block, SwiGLU):
111
+ x = x + block(x)
112
+ else:
113
+ x = block(x, training=training) if hasattr(block, 'training') else block(x)
114
+
115
+ x = self.ln_f(x)
116
+ logits = tf.matmul(x, self.token_embedding.weights[0], transpose_b=True)
117
+ return logits
118
+
119
+ model = Lamko(vocab_size=vocab_size, max_seq_len=max_len, d_model=384, n_layers=9)
120
+ dummy_input = tf.zeros((1, max_len), dtype=tf.int32)
121
+ _ = model(dummy_input)
122
+ model.load_weights(CHAT_MODEL_PATH)
123
+ print("λͺ¨λΈ κ°€μ€‘μΉ˜ λ‘œλ“œ μ™„λ£Œ!")
124
+
125
+ @tf.function(input_signature=[
126
+ tf.TensorSpec(shape=(1, None), dtype=tf.int32), # input_ids
127
+ tf.TensorSpec(shape=(vocab_size,), dtype=tf.int32), # token_counts
128
+ tf.TensorSpec(shape=(), dtype=tf.int32), # current_length
129
+ tf.TensorSpec(shape=(), dtype=tf.float32), # temperature
130
+ tf.TensorSpec(shape=(), dtype=tf.float32), # repetition_penalty
131
+ tf.TensorSpec(shape=(), dtype=tf.float32), # top_p
132
+ tf.TensorSpec(shape=(), dtype=tf.int32), # top_k
133
+ tf.TensorSpec(shape=(), dtype=tf.int32), # min_len
134
+ tf.TensorSpec(shape=(), dtype=tf.int32), # step
135
+ ])
136
+ def generate_step(input_ids, token_counts, current_length, temperature, repetition_penalty, top_p, top_k, min_len, step):
137
+ pad_len = max_len - tf.shape(input_ids)[1]
138
+ input_padded = tf.pad(input_ids, [[0,0],[0,pad_len]], constant_values=pad_id)
139
+ logits = model(input_padded, training=False)
140
+ next_logits = logits[0, current_length - 1]
141
+
142
+ penalty = tf.pow(repetition_penalty, tf.cast(token_counts, tf.float32))
143
+ next_logits = next_logits / penalty
144
+
145
+ # μ΅œμ†Œ 길이와 pad λ§ˆμŠ€ν‚Ή
146
+ if current_length < min_len:
147
+ next_logits = tf.tensor_scatter_nd_update(next_logits, [[end_id]], [-1e9])
148
+ next_logits = tf.tensor_scatter_nd_update(next_logits, [[pad_id]], [-1e9])
149
+
150
+ # top-k 필터링
151
+ if top_k > 0:
152
+ kth_val = tf.math.top_k(next_logits, k=top_k).values[-1]
153
+ mask = next_logits < kth_val
154
+ next_logits = tf.where(mask, -1e9, next_logits)
155
+
156
+ # top-p (nucleus) 필터링 + temperature
157
+ next_logits = next_logits / temperature
158
+ probs = tf.nn.softmax(next_logits)
159
+ sorted_probs, sorted_idx = tf.math.top_k(probs, k=vocab_size)
160
+ cum_probs = tf.cumsum(sorted_probs)
161
+ cutoff_mask = cum_probs <= top_p
162
+ cutoff_idx = tf.reduce_sum(tf.cast(cutoff_mask, tf.int32)) + 1
163
+ cutoff_idx = tf.minimum(cutoff_idx, vocab_size)
164
+ filtered_idx = sorted_idx[:cutoff_idx]
165
+ filtered_probs = sorted_probs[:cutoff_idx]
166
+ filtered_probs = filtered_probs / tf.reduce_sum(filtered_probs)
167
+
168
+ # πŸ”Ή 50%λŠ” argmax, 50%λŠ” μƒ˜ν”Œλ§
169
+ rand_val = tf.random.uniform([], 0, 1)
170
+ def sample():
171
+ sampled_id = tf.random.categorical(tf.math.log([filtered_probs]), 1)[0,0]
172
+ return filtered_idx[sampled_id]
173
+ def argmax():
174
+ return filtered_idx[tf.argmax(filtered_probs)]
175
+ sampled_id = tf.cond(rand_val < 0.5536, argmax, sample)
176
+ sampled_id = tf.cast(sampled_id, tf.int32)
177
+
178
+ # token_counts μ—…λ°μ΄νŠΈ
179
+ token_counts = tf.tensor_scatter_nd_add(token_counts, [[sampled_id]], [1])
180
+ return sampled_id, token_counts
181
+
182
+
183
+ # =====================
184
+ # 슀트리밍 생성기 (CPU μ΅œμ ν™” 버전)
185
+ # =====================
186
+ def generate_text_streaming(model, prompt, max_len=115, max_gen=100,
187
+ temperature=0.75, min_len=20,
188
+ repetition_penalty=1.2, top_p=0.9, top_k=50):
189
+ model_input = text_to_ids(f"<start> {prompt} <sep>")
190
+ model_input = model_input[:max_len]
191
+ generated = list(model_input)
192
+ start_output_idx = len(model_input)
193
+
194
+ # TF λ³€μˆ˜λ‘œ 토큰 카운트 관리
195
+ token_counts_np = np.zeros(vocab_size, dtype=np.int32)
196
+ for t in generated:
197
+ token_counts_np[t] += 1
198
+ token_counts = tf.Variable(token_counts_np, dtype=tf.int32)
199
+
200
+ prev_decoded = ""
201
+
202
+ for step in range(max_gen):
203
+ input_tensor = tf.expand_dims(generated, axis=0) # [1, seq_len]
204
+
205
+ sampled_id, token_counts = generate_step(
206
+ input_tensor,
207
+ token_counts,
208
+ tf.constant(len(generated), dtype=tf.int32),
209
+ tf.constant(temperature, dtype=tf.float32),
210
+ tf.constant(repetition_penalty, dtype=tf.float32),
211
+ tf.constant(top_p, dtype=tf.float32),
212
+ tf.constant(top_k, dtype=tf.int32),
213
+ tf.constant(min_len, dtype=tf.int32),
214
+ tf.constant(step, dtype=tf.int32)
215
+ )
216
+
217
+ sampled_id = int(sampled_id.numpy())
218
+ generated.append(sampled_id)
219
+
220
+ # 디코딩은 좜λ ₯ μ‹œμ μ—λ§Œ
221
+ if len(generated) > start_output_idx:
222
+ decoded_full = sp.decode(generated[start_output_idx:])
223
+ decoded_full = decoded_full.replace("▁", " ").strip()
224
+ for t in ["<start>", "<sep>", "<end>"]:
225
+ decoded_full = decoded_full.replace(t, "")
226
+ decoded_full = decoded_full.lstrip(",!?.λŠ”μ€ ")
227
+
228
+ new_output = decoded_full[len(prev_decoded):]
229
+ if new_output:
230
+ yield new_output
231
+ prev_decoded = decoded_full
232
+
233
+ # μ’…λ£Œ 쑰건
234
+ if len(generated) >= min_len and (sampled_id == end_id or decoded_full.endswith(('.', '!', '?'))):
235
+ break
236
+
237
+ token_map = {
238
+ "ν•˜μ΄": "μ•ˆλ…•ν•˜μ„Έμš”!",
239
+ "γ…Žγ…‡": "μ•ˆλ…•ν•˜μ„Έμš”!",
240
+ "ν•˜μ΄~": "μ•ˆλ…•ν•˜μ„Έμš”!",
241
+ "μ•ˆλ…•": "μ•ˆλ…•ν•˜μ„Έμš”!",
242
+ "μ•ˆλ…•!": "μ•ˆλ…•ν•˜μ„Έμš”!",
243
+ "μž˜κ°€": "μž˜κ°€. λ‚˜μ€‘μ— 보자",
244
+ "잘 κ°€": "잘 κ°€. λ‚˜μ€‘μ— 보자"
245
+ }
246
+
247
+ def preprocess_text(text):
248
+ for key, val in token_map.items():
249
+ text = text.replace(key, val)
250
+ return text
251
+
252
+ # =====================
253
+ @app.route('/')
254
+ def index():
255
+ return app.send_static_file('index.html')
256
+
257
+ @app.route('/api/search')
258
+ def search_api():
259
+ query = request.args.get("query", "").strip()
260
+ if not query:
261
+ return jsonify({"results": []})
262
+
263
+ search_url = f"https://ko.wikipedia.org/w/index.php?search={query}"
264
+ headers = {"User-Agent": "Mozilla/5.0"}
265
+ resp = requests.get(search_url, headers=headers)
266
+ soup = BeautifulSoup(resp.text, "html.parser")
267
+
268
+ results = []
269
+
270
+ # 1. 검색 κ²°κ³Ό λ¦¬μŠ€νŠΈκ°€ μžˆλŠ” 경우
271
+ search_items = soup.select(".mw-search-result-heading a")
272
+ if search_items:
273
+ for item in search_items[:5]:
274
+ title = item.text
275
+ link = "https://ko.wikipedia.org" + item.get("href")
276
+ snippet_tag = item.find_parent().find("div", class_="searchresult")
277
+ snippet = snippet_tag.text.strip() if snippet_tag else ""
278
+ results.append({"title": title, "link": link, "snippet": snippet})
279
+
280
+ # 2. 검색어와 μ •ν™•νžˆ μΌμΉ˜ν•˜λŠ” νŽ˜μ΄μ§€λ‘œ λ°”λ‘œ μ΄λ™ν•œ 경우
281
+ elif soup.select("#firstHeading"):
282
+ title = soup.select_one("#firstHeading").text.strip()
283
+ link = resp.url
284
+ # λ¬Έμ„œ 첫 번째 단락 μΆ”μΆœ
285
+ content_paragraph = soup.select_one(".mw-parser-output > p")
286
+ snippet = content_paragraph.text.strip() if content_paragraph else ""
287
+ results.append({"title": title, "link": link, "snippet": snippet})
288
+
289
+ return jsonify({"results": results})
290
+
291
+ @app.before_request
292
+ def ensure_user_id():
293
+ if 'user_id' not in session:
294
+ session['user_id'] = str(uuid.uuid4())
295
+
296
+ @app.route('/api/chat', methods=['GET','POST'])
297
+ def chat_api():
298
+ user_msg = (request.json.get("message") if request.method=="POST" else request.args.get("message") or "").strip()
299
+ if not user_msg:
300
+ return Response((f'data: {{"error":"λ©”μ‹œμ§€λ₯Ό μž…λ ₯ν•΄μ£Όμ„Έμš”."}}\n\n' for _ in range(1)),
301
+ mimetype='text/event-stream')
302
+ user_id = session['user_id']
303
+
304
+ user_msg = preprocess_text(user_msg)
305
+
306
+ def gen():
307
+ try:
308
+ # μ™ΈλΆ€ 검색 제거, search_resultλŠ” 항상 빈 λ¬Έμžμ—΄
309
+ search_result = ""
310
+ for token in generate_text_streaming(
311
+ model, user_msg,
312
+ max_len=max_len,
313
+ max_gen=115,
314
+ temperature=0.8,
315
+ min_len=10,
316
+ repetition_penalty=1.1,
317
+ top_p=0.9,
318
+ top_k=5
319
+ ):
320
+ safe_token = json.dumps(token)
321
+ yield f'data: {{"char":{safe_token}}}\n\n'
322
+
323
+ yield 'data: {"done":true}\n\n'
324
+ except Exception as e:
325
+ yield f'data: {{"error":{json.dumps(str(e))}}}\n\n'
326
+
327
+ return Response(gen(), mimetype='text/event-stream')
328
+
329
+ if __name__=="__main__":
330
+ app.run(host="0.0.0.0", port=7860)
requirements.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ numpy
2
+ pandas
3
+ flask
4
+ huggingface-hub
5
+ sympy
6
+ requests
7
+ tensorflow
8
+ pyarrow
9
+ beautifulsoup4
10
+ sentencepiece
11
+ ddgs
12
+ faiss-cpu
13
+ tokenizers