EnverLee commited on
Commit
07a8064
โ€ข
1 Parent(s): 400682e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -35
app.py CHANGED
@@ -1,16 +1,12 @@
1
  import gradio as gr
2
  from datasets import load_dataset
3
- import os
4
- from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer, BitsAndBytesConfig
5
  import torch
6
  from threading import Thread
7
  from sentence_transformers import SentenceTransformer
8
  import faiss
9
  import fitz # PyMuPDF
10
-
11
- # ํ™˜๊ฒฝ ๋ณ€์ˆ˜์—์„œ Hugging Face ํ† ํฐ ๊ฐ€์ ธ์˜ค๊ธฐ
12
- token = os.environ.get("HF_TOKEN")
13
-
14
 
15
  # ์ž„๋ฒ ๋”ฉ ๋ชจ๋ธ ๋กœ๋“œ
16
  ST = SentenceTransformer("mixedbread-ai/mxbai-embed-large-v1")
@@ -23,17 +19,36 @@ def extract_text_from_pdf(pdf_path):
23
  text += page.get_text()
24
  return text
25
 
26
- # ๋ฒ•๋ฅ  ๋ฌธ์„œ PDF ๊ฒฝ๋กœ ์ง€์ • ๋ฐ ํ…์ŠคํŠธ ์ถ”์ถœ
27
- pdf_path = "laws.pdf" # ์—ฌ๊ธฐ์— ์‹ค์ œ PDF ๊ฒฝ๋กœ๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”.
28
- law_text = extract_text_from_pdf(pdf_path)
 
 
 
 
 
 
 
29
 
30
- # ๋ฒ•๋ฅ  ๋ฌธ์„œ ํ…์ŠคํŠธ๋ฅผ ๋ฌธ์žฅ ๋‹จ์œ„๋กœ ๋‚˜๋ˆ„๊ณ  ์ž„๋ฒ ๋”ฉ
31
- law_sentences = law_text.split('\n') # Adjust splitting based on your PDF structure
32
- law_embeddings = ST.encode(law_sentences)
33
 
34
- # FAISS ์ธ๋ฑ์Šค ์ƒ์„ฑ ๋ฐ ์ž„๋ฒ ๋”ฉ ์ถ”๊ฐ€
35
- index = faiss.IndexFlatL2(law_embeddings.shape[1])
36
- index.add(law_embeddings)
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
  # Hugging Face์—์„œ ๋ฒ•๋ฅ  ์ƒ๋‹ด ๋ฐ์ดํ„ฐ์…‹ ๋กœ๋“œ
39
  dataset = load_dataset("jihye-moon/LawQA-Ko")
@@ -44,29 +59,21 @@ data = data.map(lambda x: {"question_embedding": ST.encode(x["question"])}, batc
44
  data.add_faiss_index(column="question_embedding")
45
 
46
  # LLaMA ๋ชจ๋ธ ์„ค์ •
47
- model_id = "meta-llama/Meta-Llama-3-8B-Instruct"
48
- bnb_config = BitsAndBytesConfig(
49
- load_in_4bit=True, bnb_4bit_use_double_quant=True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=torch.bfloat16
50
- )
51
- tokenizer = AutoTokenizer.from_pretrained(model_id, token=token)
52
  model = AutoModelForCausalLM.from_pretrained(
53
  model_id,
54
  torch_dtype=torch.bfloat16,
55
  device_map="auto",
56
- quantization_config=bnb_config,
57
- token=token
58
  )
59
 
60
  SYS_PROMPT = """You are an assistant for answering legal questions.
61
  You are given the extracted parts of legal documents and a question. Provide a conversational answer.
62
  If you don't know the answer, just say "I do not know." Don't make up an answer.
63
- you must answer korean."""
64
-
65
- # ๋ฒ•๋ฅ  ๋ฌธ์„œ ๊ฒ€์ƒ‰ ํ•จ์ˆ˜
66
- def search_law(query, k=5):
67
- query_embedding = ST.encode([query])
68
- D, I = index.search(query_embedding, k)
69
- return [(law_sentences[i], D[0][idx]) for idx, i in enumerate(I[0])]
70
 
71
  # ๋ฒ•๋ฅ  ์ƒ๋‹ด ๋ฐ์ดํ„ฐ ๊ฒ€์ƒ‰ ํ•จ์ˆ˜
72
  def search_qa(query, k=3):
@@ -97,11 +104,7 @@ def talk(prompt, history):
97
  messages = [{"role": "system", "content": SYS_PROMPT}, {"role": "user", "content": formatted_prompt}]
98
 
99
  # ๋ชจ๋ธ์—๊ฒŒ ์ƒ์„ฑ ์ง€์‹œ
100
- input_ids = tokenizer.apply_chat_template(
101
- messages,
102
- add_generation_prompt=True,
103
- return_tensors="pt"
104
- ).to(model.device)
105
 
106
  streamer = TextIteratorStreamer(
107
  tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True
@@ -147,4 +150,4 @@ demo = gr.ChatInterface(
147
  )
148
 
149
  # Gradio ๋ฐ๋ชจ ์‹คํ–‰
150
- demo.launch(debug=True)
 
1
  import gradio as gr
2
  from datasets import load_dataset
3
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
 
4
  import torch
5
  from threading import Thread
6
  from sentence_transformers import SentenceTransformer
7
  import faiss
8
  import fitz # PyMuPDF
9
+ import os
 
 
 
10
 
11
  # ์ž„๋ฒ ๋”ฉ ๋ชจ๋ธ ๋กœ๋“œ
12
  ST = SentenceTransformer("mixedbread-ai/mxbai-embed-large-v1")
 
19
  text += page.get_text()
20
  return text
21
 
22
+ # ๊ธฐ๋ณธ ์ œ๊ณต PDF ํŒŒ์ผ ๊ฒฝ๋กœ
23
+ default_pdf_path = "laws.pdf"
24
+
25
+ # FAISS ์ธ๋ฑ์Šค ์ดˆ๊ธฐํ™”
26
+ index = None
27
+ law_sentences = []
28
+
29
+ # ๊ธฐ๋ณธ ์ œ๊ณต PDF ํŒŒ์ผ ์ฒ˜๋ฆฌ ํ•จ์ˆ˜
30
+ def process_default_pdf():
31
+ global index, law_sentences
32
 
33
+ # PDF์—์„œ ํ…์ŠคํŠธ ์ถ”์ถœ
34
+ law_text = extract_text_from_pdf(default_pdf_path)
 
35
 
36
+ # ๋ฌธ์žฅ์„ ๋‚˜๋ˆ„๊ณ  ์ž„๋ฒ ๋”ฉ ์ƒ์„ฑ
37
+ law_sentences = law_text.split('\n')
38
+ law_embeddings = ST.encode(law_sentences)
39
+
40
+ # FAISS ์ธ๋ฑ์Šค ์ƒ์„ฑ ๋ฐ ์ž„๋ฒ ๋”ฉ ์ถ”๊ฐ€
41
+ index = faiss.IndexFlatL2(law_embeddings.shape[1])
42
+ index.add(law_embeddings)
43
+
44
+ # ์ฒ˜์Œ์— ๊ธฐ๋ณธ PDF ํŒŒ์ผ ์ฒ˜๋ฆฌ
45
+ process_default_pdf()
46
+
47
+ # ๋ฒ•๋ฅ  ๋ฌธ์„œ ๊ฒ€์ƒ‰ ํ•จ์ˆ˜
48
+ def search_law(query, k=5):
49
+ query_embedding = ST.encode([query])
50
+ D, I = index.search(query_embedding, k)
51
+ return [(law_sentences[i], D[0][idx]) for idx, i in enumerate(I[0])]
52
 
53
  # Hugging Face์—์„œ ๋ฒ•๋ฅ  ์ƒ๋‹ด ๋ฐ์ดํ„ฐ์…‹ ๋กœ๋“œ
54
  dataset = load_dataset("jihye-moon/LawQA-Ko")
 
59
  data.add_faiss_index(column="question_embedding")
60
 
61
  # LLaMA ๋ชจ๋ธ ์„ค์ •
62
+ model_id = "google/gemma-2-2b-it"
63
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
 
 
 
64
  model = AutoModelForCausalLM.from_pretrained(
65
  model_id,
66
  torch_dtype=torch.bfloat16,
67
  device_map="auto",
 
 
68
  )
69
 
70
  SYS_PROMPT = """You are an assistant for answering legal questions.
71
  You are given the extracted parts of legal documents and a question. Provide a conversational answer.
72
  If you don't know the answer, just say "I do not know." Don't make up an answer.
73
+ you must answer korean.
74
+ You're a LAWEYE legal advisor bot. Your job is to provide korean legal assistance by asking questions to korean speaker, then offering advice or guidance based on the information and law provisions provided. Make sure you only respond with one question at a time.
75
+ ...
76
+ """
 
 
 
77
 
78
  # ๋ฒ•๋ฅ  ์ƒ๋‹ด ๋ฐ์ดํ„ฐ ๊ฒ€์ƒ‰ ํ•จ์ˆ˜
79
  def search_qa(query, k=3):
 
104
  messages = [{"role": "system", "content": SYS_PROMPT}, {"role": "user", "content": formatted_prompt}]
105
 
106
  # ๋ชจ๋ธ์—๊ฒŒ ์ƒ์„ฑ ์ง€์‹œ
107
+ input_ids = tokenizer(messages, return_tensors="pt").to(model.device).input_ids
 
 
 
 
108
 
109
  streamer = TextIteratorStreamer(
110
  tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True
 
150
  )
151
 
152
  # Gradio ๋ฐ๋ชจ ์‹คํ–‰
153
+ demo.launch(debug=True)