EnverLee commited on
Commit
07a8064
·
verified ·
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)