Yuchan5386 commited on
Commit
b2c8ad4
ยท
verified ยท
1 Parent(s): 109056f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -54
app.py CHANGED
@@ -1,64 +1,66 @@
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
 
 
 
 
 
 
25
 
26
- messages.append({"role": "user", "content": message})
 
 
 
27
 
28
- response = ""
 
 
 
 
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
 
38
 
39
- response += token
40
- yield response
41
 
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
-
62
-
63
- if __name__ == "__main__":
64
- demo.launch()
 
1
+ import json
2
  import gradio as gr
3
+ from sklearn.feature_extraction.text import TfidfVectorizer
4
+ from sklearn.metrics.pairwise import cosine_similarity
5
 
6
+ file_path = "InstructData.jsonl"
 
 
 
7
 
8
+ # 1. ๋Œ€ํ™” ๋ฐ์ดํ„ฐ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ (๋ชจ๋“  human-gpt ์Œ ์ถ”์ถœ)
9
+ def load_conversations(file_path):
10
+ conversations = []
11
+ with open(file_path, 'r', encoding='utf-8') as f:
12
+ for line in f:
13
+ data = json.loads(line)
14
+ conv = data.get('conversations', [])
15
+ prev = None
16
+ for c in conv:
17
+ if c.get('from') == 'human':
18
+ prev = c['value']
19
+ elif c.get('from') == 'gpt' and prev:
20
+ conversations.append((prev, c['value']))
21
+ prev = None
22
+ return conversations
23
 
24
+ # 2. ํ•œ๊ตญ์–ด ๋ถˆ์šฉ์–ด ์„ค์ • + TF-IDF ๋ฒกํ„ฐ๋ผ์ด์ € ์ค€๋น„
25
+ def build_vectorizer(questions):
26
+ korean_stopwords = ['๊ทธ๋ฆฌ๊ณ ', '๊ทธ๋Ÿฌ๋‚˜', 'ํ•˜์ง€๋งŒ', '๋˜ํ•œ', '์ด๋Ÿฐ', '์ €๋Ÿฐ', '๊ทธ๋Ÿฐ', '์žˆ๋Š”', '์—†๋Š”', '๊ฒƒ', '์ˆ˜', '๋•Œ๋ฌธ์—', 'ํ•ด์„œ']
27
+ vectorizer = TfidfVectorizer(stop_words=korean_stopwords)
28
+ tfidf_matrix = vectorizer.fit_transform(questions)
29
+ return vectorizer, tfidf_matrix
 
 
 
30
 
31
+ # 3. ์œ ์‚ฌ๋„ ๊ธฐ๋ฐ˜ Top-k ์‘๋‹ต ์ฐพ๊ธฐ
32
+ def find_top_responses(user_input, conversations, vectorizer, tfidf_matrix, top_k=3):
33
+ user_vec = vectorizer.transform([user_input])
34
+ sims = cosine_similarity(user_vec, tfidf_matrix)[0]
35
+ top_indices = sims.argsort()[-top_k:][::-1]
36
+ results = ""
37
+ for i, idx in enumerate(top_indices, 1):
38
+ answer = conversations[idx][1]
39
+ score = sims[idx]
40
+ results += f"{i}. {answer} (์œ ์‚ฌ๋„: {score:.2f})\n\n"
41
+ return results.strip()
42
 
43
+ # ์ดˆ๊ธฐํ™”
44
+ convs = load_conversations(file_path)
45
+ questions = [q for q, _ in convs]
46
+ vectorizer, tfidf_matrix = build_vectorizer(questions)
47
 
48
+ # Gradio ์ธํ„ฐํŽ˜์ด์Šค ํ•จ์ˆ˜
49
+ def chatbot_interface(user_input):
50
+ if user_input.strip().lower() == "์ข…๋ฃŒ":
51
+ return "ChatBot: ์•ˆ๋…•~ ๋˜ ๋†€๋Ÿฌ์™€!"
52
+ return find_top_responses(user_input, convs, vectorizer, tfidf_matrix)
53
 
54
+ # Gradio UI ๊ตฌ์„ฑ
55
+ with gr.Blocks() as demo:
56
+ gr.Markdown("## ChatBot (TF-IDF ๊ธฐ๋ฐ˜ Top-3 ๋‹ต๋ณ€ ์ถ”์ฒœ)")
57
+ with gr.Row():
58
+ with gr.Column():
59
+ input_box = gr.Textbox(label="์งˆ๋ฌธ์„ ์ž…๋ ฅํ•ด์ค˜!", placeholder="์˜ˆ: ์ฑ—๋ด‡ ์–ด๋–ป๊ฒŒ ๋งŒ๋“ค์–ด์š”?")
60
+ submit_btn = gr.Button("Toki์—๊ฒŒ ๋ฌผ์–ด๋ณด๊ธฐ ๐Ÿง ")
61
+ with gr.Column():
62
+ output_box = gr.Textbox(label="Toki์˜ ์ถ”์ฒœ ๋‹ต๋ณ€ Top-3", lines=10)
63
 
64
+ submit_btn.click(fn=chatbot_interface, inputs=input_box, outputs=output_box)
 
65
 
66
+ demo.launch()