File size: 15,920 Bytes
77d5918
 
 
 
 
 
 
 
 
 
 
 
 
 
e89787a
 
77d5918
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
959a616
 
 
 
 
 
 
 
77d5918
959a616
 
 
 
77d5918
959a616
 
 
 
 
77d5918
959a616
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77d5918
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85e1019
77d5918
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
919644d
 
 
 
 
 
 
 
 
5226c06
919644d
5226c06
919644d
 
 
 
 
 
 
 
5226c06
919644d
 
 
5226c06
919644d
 
5226c06
919644d
 
5226c06
 
 
919644d
 
5226c06
919644d
 
 
5226c06
004f427
5226c06
 
919644d
 
 
 
 
 
5226c06
 
 
 
 
919644d
5226c06
 
 
004f427
919644d
77d5918
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55632cc
 
 
77d5918
 
 
55632cc
 
 
77d5918
 
55632cc
 
 
77d5918
 
 
 
55632cc
 
 
77d5918
55632cc
 
 
77d5918
55632cc
919644d
 
 
55632cc
919644d
55632cc
 
77d5918
919644d
55632cc
 
 
 
77d5918
 
55632cc
77d5918
 
 
 
 
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
import requests
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers  
import asyncio
from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse, PlainTextResponse
import sentencepiece as spm
import re
import math
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

origins = [
    "https://insect5386.github.io",
    "https://insect5386.github.io/insect5386"
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
      
sp = spm.SentencePieceProcessor()      
sp.load("kolig_unigram.model")      
      
pad_id = sp.piece_to_id("<pad>")      
if pad_id == -1: pad_id = 0      
start_id = sp.piece_to_id("<start>")      
if start_id == -1: start_id = 1      
end_id = sp.piece_to_id("<end>")      
if end_id == -1: end_id = 2      
unk_id = sp.piece_to_id("<unk>")      
if unk_id == -1: unk_id = 3      
      
vocab_size = sp.get_piece_size()      
max_len = 100      
      
def text_to_ids(text):      
    return sp.encode(text, out_type=int)      
      
def ids_to_text(ids):      
    return sp.decode(ids)      
    
class RotaryPositionalEmbedding(layers.Layer):      
    def __init__(self, dim):      
        super().__init__()      
        inv_freq = 1.0 / (10000 ** (np.arange(0, dim, 2) / dim))      
        self.inv_freq = tf.constant(inv_freq, dtype=tf.float32)      
      
    def call(self, x):      
        batch, heads, seq_len, depth = tf.unstack(tf.shape(x))      
        t = tf.range(seq_len, dtype=tf.float32)      
        freqs = tf.einsum('i,j->ij', t, self.inv_freq)      
        emb_sin = tf.sin(freqs)      
        emb_cos = tf.cos(freqs)      
        emb_cos = tf.reshape(emb_cos, [1, 1, seq_len, -1])      
        emb_sin = tf.reshape(emb_sin, [1, 1, seq_len, -1])      
        x1 = x[..., ::2]      
        x2 = x[..., 1::2]      
        x_rotated = tf.stack([      
            x1 * emb_cos - x2 * emb_sin,      
            x1 * emb_sin + x2 * emb_cos      
        ], axis=-1)      
        x_rotated = tf.reshape(x_rotated, tf.shape(x))      
        return x_rotated    
    
class SwiGLU(tf.keras.layers.Layer):    
    def __init__(self, d_model, d_ff):    
        super().__init__()    
        self.proj = tf.keras.layers.Dense(d_ff * 2)    
        self.out = tf.keras.layers.Dense(d_model)    
    
    def call(self, x):    
        x_proj = self.proj(x)    
        x_val, x_gate = tf.split(x_proj, 2, axis=-1)    
        return self.out(x_val * tf.nn.silu(x_gate))    
            
class Block(tf.keras.layers.Layer):  
    def __init__(self, d_model, d_ff, num_heads=8, dropout_rate=0.05, adapter_dim=64):    
        super().__init__()    
        self.ln1 = tf.keras.layers.LayerNormalization(epsilon=1e-5)    
        self.mha = tf.keras.layers.MultiHeadAttention(num_heads=num_heads, key_dim=d_model // num_heads)    
        self.dropout1 = tf.keras.layers.Dropout(dropout_rate)   
        self.adapter_down = tf.keras.layers.Dense(adapter_dim, activation='gelu')   
        self.adapter_up = tf.keras.layers.Dense(d_model)    
    
        self.ln2 = tf.keras.layers.LayerNormalization(epsilon=1e-5)    
        self.ffn = SwiGLU(d_model, d_ff)    
        self.dropout2 = tf.keras.layers.Dropout(dropout_rate)   
        self.rope = RotaryPositionalEmbedding(d_model // num_heads)    
    
    def call(self, x, training=False):    
        x_norm = self.ln1(x)    
        b, s, _ = tf.shape(x_norm)[0], tf.shape(x_norm)[1], tf.shape(x_norm)[2]    
        h = self.mha.num_heads    
        d = x_norm.shape[-1] // h    
    
        qkv = tf.reshape(x_norm, [b, s, h, d])    
        qkv = tf.transpose(qkv, [0, 2, 1, 3])    
        q = self.rope(qkv)    
        k = self.rope(qkv)    
        q = tf.reshape(tf.transpose(q, [0, 2, 1, 3]), [b, s, h * d])    
        k = tf.reshape(tf.transpose(k, [0, 2, 1, 3]), [b, s, h * d])    
    
        attn_out = self.mha(query=q, value=x_norm, key=k, use_causal_mask=True, training=training)    
        attn_out = self.dropout1(attn_out, training=training)    
  
        adapter_out = self.adapter_up(self.adapter_down(attn_out))  
        attn_out = attn_out + adapter_out    
    
        x = x + attn_out    
        ffn_out = self.ffn(self.ln2(x))    
        x = x + self.dropout2(ffn_out, training=training)    
        return x
    
class Flexi(tf.keras.Model):  
    def __init__(self, vocab_size, seq_len, d_model, d_ff, n_layers, num_heads=8, dropout_rate=0.05):  
        super().__init__()  
        self.token_embedding = tf.keras.layers.Embedding(vocab_size, d_model)  
        self.blocks = [Block(d_model, d_ff, num_heads, dropout_rate) for _ in range(n_layers)]  
        self.ln_f = tf.keras.layers.LayerNormalization(epsilon=1e-5)  
  
    def call(self, x, training=False):  
        x = self.token_embedding(x)  
        for block in self.blocks:  
            x = block(x, training=training)  
        x = self.ln_f(x)  
        logits = tf.matmul(x, self.token_embedding.embeddings, transpose_b=True)  
        return logits     
    
model = Flexi(
    vocab_size=vocab_size,
    seq_len=max_len,
    d_model=256,
    d_ff=1024,       
    n_layers=16
)

dummy_input = tf.zeros((1, max_len), dtype=tf.int32)  # 배치1, μ‹œν€€μŠ€κΈΈμ΄ max_len      
_ = model(dummy_input)  # λͺ¨λΈμ΄ λΉŒλ“œλ¨      
model.load_weights("Flexi.weights.h5")      
print("λͺ¨λΈ κ°€μ€‘μΉ˜ λ‘œλ“œ μ™„λ£Œ!")      

  
def is_greedy_response_acceptable(text):  
    text = text.strip()  
  
    # λ„ˆλ¬΄ 짧은 λ¬Έμž₯ κ±°λ₯΄κΈ°  
    if len(text) < 5:  
        return False  
  
    # 단어 수 λ„ˆλ¬΄ 적은 것도 거름  
    if len(text.split()) < 3:  
        return False  
  
    # γ…‹γ…‹γ…‹ 같은 자λͺ¨ μ—°μ†λ§Œ 있으면 거름 (단, 'γ…‹γ…‹' ν¬ν•¨λ˜λ©΄ ν—ˆμš©)  
    if re.search(r'[γ„±-γ…Žγ…-γ…£]{3,}', text) and 'γ…‹γ…‹' not in text:  
        return False  
  
    # λ¬Έμž₯ 끝이 μ–΄μƒ‰ν•œ 경우 (λ‹€/μš”/μ£  λ“± 일반적 ν˜•νƒœλ‘œ λλ‚˜μ§€ μ•ŠμœΌλ©΄ 거름)  
    if not re.search(r'(λ‹€|μš”|μ£ |λ‹€\.|μš”\.|μ£ \.|λ‹€!|μš”!|μ£ !|\!|\?|\.)$', text):  
        return False  
  
    return True

def generate_text_sample(model, prompt, max_len=100, max_gen=98,
                         temperature=0.8, top_k=55, top_p=0.95, min_len=12):
    model_input = text_to_ids(f"<start> {prompt} <sep>")
    model_input = model_input[:max_len]
    generated = list(model_input)

    for _ in range(max_gen):
        pad_len = max(0, max_len - len(generated))
        input_padded = np.pad(generated, (0, pad_len), constant_values=pad_id)
        input_tensor = tf.convert_to_tensor([input_padded])
        logits = model(input_tensor, training=False)
        next_logits = logits[0, len(generated) - 1].numpy()

        # Temperature 적용
        next_logits = next_logits / temperature
        probs = np.exp(next_logits - np.max(next_logits))
        probs = probs / probs.sum()

        # Top-K 필터링
        if top_k is not None and top_k > 0:
            indices_to_remove = probs < np.sort(probs)[-top_k]
            probs[indices_to_remove] = 0
            probs /= probs.sum()

        # Top-P (λˆ„μ  ν™•λ₯ ) 필터링
        if top_p is not None and 0 < top_p < 1:
            sorted_indices = np.argsort(probs)[::-1]
            sorted_probs = probs[sorted_indices]
            cumulative_probs = np.cumsum(sorted_probs)
            # λˆ„μ  ν™•λ₯ μ΄ top_p μ΄ˆκ³Όν•˜λŠ” 토큰듀은 제거
            cutoff_index = np.searchsorted(cumulative_probs, top_p, side='right')
            probs_to_keep = sorted_indices[:cutoff_index+1]
            
            mask = np.ones_like(probs, dtype=bool)
            mask[probs_to_keep] = False
            probs[mask] = 0
            probs /= probs.sum()

        # μƒ˜ν”Œλ§
        next_token = np.random.choice(len(probs), p=probs)
        generated.append(int(next_token))

        # λ””μ½”λ”© 및 ν›„μ²˜λ¦¬
        decoded = sp.decode(generated)
        for t in ["<start>", "<sep>", "<end>"]:
            decoded = decoded.replace(t, "")
        decoded = decoded.strip()

        if len(generated) >= min_len and (next_token == end_id or decoded.endswith(('μš”', 'λ‹€', '.', '!', '?'))):
            if is_greedy_response_acceptable(decoded):
                return decoded
            else:
                continue

    decoded = sp.decode(generated)
    for t in ["<start>", "<sep>", "<end>"]:
        decoded = decoded.replace(t, "")
    return decoded.strip()

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import TruncatedSVD
from sklearn.metrics.pairwise import cosine_similarity

class SimilarityMemory:
    def __init__(self, n_components=100):
        self.memory_texts = []
        self.vectorizer = TfidfVectorizer()
        self.svd = TruncatedSVD(n_components=n_components)
        self.embeddings = None
        self.fitted = False

    def add(self, text: str):
        self.memory_texts.append(text)
        self._update_embeddings()

    def _update_embeddings(self):
        if len(self.memory_texts) == 0:
            self.embeddings = None
            self.fitted = False
            return

        X = self.vectorizer.fit_transform(self.memory_texts)
        n_comp = min(self.svd.n_components, X.shape[1], len(self.memory_texts)-1)
        if n_comp <= 0:
            self.embeddings = X.toarray()
            self.fitted = True
            return

        self.svd = TruncatedSVD(n_components=n_comp)
        self.embeddings = self.svd.fit_transform(X)
        self.fitted = True

    def retrieve(self, query: str, top_k=3):
        if not self.fitted or self.embeddings is None or len(self.memory_texts) == 0:
            return []

        Xq = self.vectorizer.transform([query])
        if self.svd.n_components > Xq.shape[1] or self.svd.n_components > len(self.memory_texts) - 1:
            q_emb = Xq.toarray()
        else:
            q_emb = self.svd.transform(Xq)

        sims = cosine_similarity(q_emb, self.embeddings)[0]
        top_indices = sims.argsort()[::-1][:top_k]

        return [self.memory_texts[i] for i in top_indices]

    def process_input(self, new_text: str, top_k=3):
        """μžλ™μœΌλ‘œ κΈ°μ–΅ μ €μž₯ν•˜κ³ , μœ μ‚¬ν•œ κΈ°μ–΅ μ°Ύμ•„μ„œ ν•©μΉœ ν”„λ‘¬ν”„νŠΈ 생성"""
        related_memories = self.retrieve(new_text, top_k=top_k)
        self.add(new_text)
        return self.merge_prompt(new_text, related_memories)

    def merge_prompt(self, prompt: str, memories: list):
        context = "\n".join(memories)
        return f"{context}\n\n{prompt}" if context else prompt


def mismatch_tone(input_text, output_text):  
    if "γ…‹γ…‹" in input_text and not re.search(r'γ…‹γ…‹|γ…Ž|재밌|놀|λ§Œλ‚˜|λ§›μ§‘|μ—¬ν–‰', output_text):  
        return True  
    return False

# μœ νš¨ν•œ 응닡인지 검사
def is_valid_response(response):
    if len(response.strip()) < 2:
        return False
    if re.search(r'[γ„±-γ…Žγ…-γ…£]{3,}', response):
        return False
    if len(response.split()) < 2:
        return False
    if response.count(' ') < 2:
        return False
    if any(tok in response.lower() for tok in ['hello', 'this', 'γ…‹γ…‹']):
        return False
    return True

# μœ„ν‚€ μš”μ•½ κ΄€λ ¨
def extract_main_query(text):
    sentences = re.split(r'[.?!]\s*', text)
    sentences = [s.strip() for s in sentences if s.strip()]
    if not sentences:
        return text
    last = sentences[-1]
    last = re.sub(r'[^κ°€-힣a-zA-Z0-9 ]', '', last)
    particles = ['이', 'κ°€', '은', 'λŠ”', '을', 'λ₯Ό', '의', 'μ—μ„œ', 'μ—κ²Œ', 'ν•œν…Œ', '보닀']
    for p in particles:
        last = re.sub(rf'\b(\w+){p}\b', r'\1', last)
    return last.strip()

def get_wikipedia_summary(query):
    cleaned_query = extract_main_query(query)
    url = f"https://ko.wikipedia.org/api/rest_v1/page/summary/{cleaned_query}"
    res = requests.get(url)
    if res.status_code == 200:
        return res.json().get("extract", "μš”μ•½ 정보λ₯Ό 찾을 수 μ—†μŠ΅λ‹ˆλ‹€.")
    else:
        return "μœ„ν‚€λ°±κ³Όμ—μ„œ 정보λ₯Ό κ°€μ Έμ˜¬ 수 μ—†μŠ΅λ‹ˆλ‹€."

def textrank_summarize(text, top_n=3):
    sentences = re.split(r'(?<=[.!?])\s+', text.strip())
    sentences = [s.strip() for s in sentences if len(s.strip()) > 10]
    if len(sentences) <= top_n:
        return text
    vectorizer = TfidfVectorizer()
    tfidf_matrix = vectorizer.fit_transform(sentences)
    sim_matrix = cosine_similarity(tfidf_matrix)
    np.fill_diagonal(sim_matrix, 0)
    def pagerank(matrix, damping=0.85, max_iter=100, tol=1e-4):
        N = matrix.shape[0]
        ranks = np.ones(N) / N
        row_sums = np.sum(matrix, axis=1)
        row_sums[row_sums == 0] = 1
        for _ in range(max_iter):
            prev_ranks = ranks.copy()
            for i in range(N):
                incoming = matrix[:, i]
                ranks[i] = (1 - damping) / N + damping * np.sum(incoming * prev_ranks / row_sums)
            if np.linalg.norm(ranks - prev_ranks) < tol:
                break
        return ranks
    scores = pagerank(sim_matrix)
    ranked_idx = np.argsort(scores)[::-1]
    selected_idx = sorted(ranked_idx[:top_n])
    summary = ' '.join([sentences[i] for i in selected_idx])
    return summary

def summarize_from_wikipedia(query, top_n=3):  
    raw_summary = get_wikipedia_summary(query)  
    first_summary = textrank_summarize(raw_summary, top_n=top_n)  
    second_summary = textrank_summarize(first_summary, top_n=top_n)  
    return second_summary


def simple_intent_classifier(text):
    text = text.lower()
    greet_keywords = ["μ•ˆλ…•", "λ°˜κ°€μ›Œ", "이름", "λˆ„κ΅¬", "μ†Œκ°œ", "μ–΄λ””μ„œ μ™”", "정체", "λͺ‡ μ‚΄", "λ„ˆ 뭐야"]
    info_keywords = ["μ„€λͺ…", "정보", "무엇", "뭐야", "μ–΄λ””", "λˆ„κ΅¬", "μ™œ", "μ–΄λ–»κ²Œ", "μ’…λ₯˜", "κ°œλ…"]
    if any(kw in text for kw in greet_keywords):
        return "인사"
    elif any(kw in text for kw in info_keywords):
        return "μ •λ³΄μ§ˆλ¬Έ"
    else:
        return "μΌμƒλŒ€ν™”"

def respond(input_text):
    # 1) μ‚¬μš©μž μž…λ ₯ 기얡에 μ €μž₯ (μ›ν•˜λ©΄)
    memory.add(input_text)

    intent = simple_intent_classifier(input_text)

    if "이름" in input_text:
        response = "제 이름은 Flexiμž…λ‹ˆλ‹€."
        memory.add(response)  # 닡변도 기얡에 μΆ”κ°€ κ°€λŠ₯
        return response

    if "λˆ„κ΅¬" in input_text:
        response = "μ €λŠ” Flexi라고 ν•΄μš”."
        memory.add(response)
        return response

    if intent == "μ •λ³΄μ§ˆλ¬Έ":
        keyword = re.sub(r"(에 λŒ€ν•΄|에 λŒ€ν•œ|에 λŒ€ν•΄μ„œ)?\s*(μ„€λͺ…ν•΄μ€˜|μ•Œλ €μ€˜|뭐야|κ°œλ…|μ •μ˜|정보)?", "", input_text).strip()
        if not keyword:
            response = "μ–΄λ–€ μ£Όμ œμ— λŒ€ν•΄ κΆκΈˆν•œκ°€μš”?"
            memory.add(response)
            return response
        summary = summarize_from_wikipedia(keyword)
        response = f"{summary}\nλ‹€λ₯Έ κΆκΈˆν•œ 점 μžˆμœΌμ‹ κ°€μš”?"
        memory.add(response)
        return response

    # κΈ°μ–΅μ—μ„œ μœ μ‚¬ λ¬Έμž₯ κΊΌλ‚΄μ„œ ν”„λ‘¬ν”„νŠΈ λ§Œλ“€κΈ°
    related_memories = memory.retrieve(input_text, top_k=3)
    merged_prompt = merge_prompt_with_memory(input_text, related_memories)

    # λͺ¨λΈλ‘œ 응닡 생성
    response = generate_text_sample(model, merged_prompt)

    # 응닡 검증, μ•ˆ 맞으면 μž¬μƒμ„±
    if not is_valid_response(response) or mismatch_tone(input_text, response):
        response = generate_text_sample(model, merged_prompt)

    # μ΅œμ’… 응닡도 기얡에 μΆ”κ°€
    memory.add(response)

    return response


@app.get("/generate", response_class=PlainTextResponse)
async def generate(request: Request):
    prompt = request.query_params.get("prompt", "μ•ˆλ…•ν•˜μ„Έμš”")
    response_text = respond(prompt)
    return response_text