StevenChen16 commited on
Commit
17b23e6
1 Parent(s): 0d31eec

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +72 -0
app.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from llamafactory.chat import ChatModel
3
+ from llamafactory.extras.misc import torch_gc
4
+ import re
5
+ import space
6
+
7
+ def split_into_sentences(text):
8
+ sentence_endings = re.compile(r'(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\?|\!)\s')
9
+ sentences = sentence_endings.split(text)
10
+ return [sentence.strip() for sentence in sentences if sentence]
11
+
12
+ @space.GPU
13
+ def process_paragraph(paragraph, progress=gr.Progress()):
14
+ sentences = split_into_sentences(paragraph)
15
+ results = []
16
+ total_sentences = len(sentences)
17
+ for i, sentence in enumerate(sentences):
18
+ progress((i + 1) / total_sentences)
19
+ messages.append({"role": "user", "content": sentence})
20
+ sentence_response = ""
21
+ for new_text in chat_model.stream_chat(messages, temperature=0.7, top_p=0.9, top_k=50, max_new_tokens=300):
22
+ sentence_response += new_text.strip()
23
+ category = sentence_response.strip().lower().replace(' ', '_')
24
+ if category != "fair":
25
+ results.append((sentence, category))
26
+ else:
27
+ results.append((sentence, "fair"))
28
+ messages.append({"role": "assistant", "content": sentence_response})
29
+ torch_gc()
30
+ return results
31
+
32
+ args = dict(
33
+ model_name_or_path="princeton-nlp/Llama-3-Instruct-8B-SimPO", # 使用量化的 Llama-3-8B-Instruct 模型
34
+ adapter_name_or_path="StevenChen16/llama3-8b-compliance-review", # 加载保存的 LoRA 适配器
35
+ template="llama3", # 与训练时使用的模板相同
36
+ finetuning_type="lora", # 与训练时使用的微调类型相同
37
+ quantization_bit=8, # 加载 4-bit 量化模型
38
+ use_unsloth=True, # 使用 UnslothAI 的 LoRA 优化以加速生成
39
+ )
40
+ chat_model = ChatModel(args)
41
+ messages = []
42
+
43
+ # 定义类型到颜色的映射
44
+ label_to_color = {
45
+ "fair": "green",
46
+ "limitation_of_liability": "red",
47
+ "unilateral_termination": "orange",
48
+ "unilateral_change": "yellow",
49
+ "content_removal": "purple",
50
+ "contract_by_using": "blue",
51
+ "choice_of_law": "cyan",
52
+ "jurisdiction": "magenta",
53
+ "arbitration": "brown",
54
+ }
55
+
56
+ with gr.Blocks() as demo:
57
+
58
+ with gr.Row(equal_height=True):
59
+ with gr.Column():
60
+ input_text = gr.Textbox(label="Input Paragraph", lines=10, placeholder="Enter the paragraph here...")
61
+ btn = gr.Button("Process")
62
+ with gr.Column():
63
+ output = gr.HighlightedText(label="Processed Paragraph", color_map=label_to_color)
64
+ progress = gr.Progress()
65
+
66
+ def on_click(paragraph):
67
+ results = process_paragraph(paragraph, progress=progress)
68
+ return results
69
+
70
+ btn.click(on_click, inputs=input_text, outputs=[output])
71
+
72
+ demo.launch()