Andrew Tsai commited on
Commit
78303df
1 Parent(s): a5c949d
Files changed (2) hide show
  1. app.py +78 -0
  2. requirements.txt +11 -0
app.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --coding:utf-8--
2
+ import os
3
+ import shutil
4
+
5
+ import gradio as gr
6
+ from fastapi import Request, FastAPI, Response
7
+
8
+ import torch
9
+ import flash
10
+ from flash.text import TextClassificationData, TextClassifier
11
+ from huggingface_hub import hf_hub_download
12
+
13
+ labels = {'law':[
14
+ '刑法第11條', '毒品危害防制條例第10條', '刑法第47條', '刑事訴訟法第299條', '刑法第41條', '刑事訴訟法第454條',
15
+ '毒品危害防制條例第18條', '刑事訴訟法第273條', '刑事訴訟法第449條', '刑法第38條', '刑法第51條', '刑事訴訟法第450條',
16
+ '刑事訴訟法第455條', '刑法第10條', '毒品危害防制條例第4條', '刑法第62條', '毒品危害防制條例第11條', '刑法第56條',
17
+ '毒品危害防制條例第19條', '刑法第55條', '毒品危害防制條例第17條', '刑事訴訟法第310條', '刑事訴訟法第368條',
18
+ '刑事訴訟法第369條', '刑事訴訟法第364條'],
19
+ 'sentence':[
20
+ '(425.0, 1335.0]', '(4.999, 90.0]', '(150.0, 180.0]','(90.0, 120.0]', '(1335.0, 10950.0]',
21
+ '(300.0, 425.0]', '(180.0, 210.0]', '(240.0, 300.0]','(120.0, 150.0]', '(210.0, 240.0]']
22
+ }
23
+
24
+ def load_classification_model():
25
+ REPO_ID = "AndrewTsai0406/bert-tiny-law-article-classifier"
26
+ MODEL_NAME = 'law_classification_prajjwal1-bert-tiny.pt'
27
+
28
+ if os.path.isfile('./models/'+MODEL_NAME):
29
+ print("File exists in the directory.")
30
+ else:
31
+ print("File does not exist in the directory.")
32
+ hf_hub_download(repo_id=REPO_ID, filename=MODEL_NAME, local_dir_use_symlinks=False, local_dir='./models')
33
+ model = TextClassifier.load_from_checkpoint('./models/'+MODEL_NAME)
34
+ return model
35
+
36
+ def load_regression_model():
37
+ REPO_ID = "AndrewTsai0406/bert-tiny-jail-sentence-classifier"
38
+ MODEL_NAME = 'sentence_classification_prajjwal1-bert-tiny.pt'
39
+ if os.path.isfile('./models/'+MODEL_NAME):
40
+ print("File exists in the directory.")
41
+ else:
42
+ print("File does not exist in the directory.")
43
+ hf_hub_download(repo_id=REPO_ID, filename=MODEL_NAME, local_dir_use_symlinks=False, local_dir='./models')
44
+ model = TextClassifier.load_from_checkpoint('./models/'+MODEL_NAME)
45
+ return model
46
+
47
+ model_classificaiton = load_classification_model()
48
+ model_regression = load_regression_model()
49
+ trainer = flash.Trainer(gpus=torch.cuda.device_count(), enable_checkpointing=False)
50
+ # trainer = flash.Trainer(gpus=torch.cuda.device_count(), accelerator="gpu", enable_checkpointing=False)
51
+
52
+ def gradio_model_inference(text):
53
+ datamodule = TextClassificationData.from_lists(predict_data=[text],batch_size=4)
54
+ predictions_law_articels = trainer.predict(model_classificaiton, datamodule = datamodule, output="labels")
55
+ predictions_sentence = trainer.predict(model_regression, datamodule = datamodule, output="labels")
56
+ pred_from, pred_to = labels['sentence'][int(predictions_sentence[0][0])].split(', ')
57
+ predictions_sentence = 'Jail time: from '+f'{int(float(pred_from[1:]))}'+' days'+' to '+f'{int(float(pred_to[:-1]))}'+' days'
58
+ return '\n'.join(predictions_law_articels[0][0]), predictions_sentence
59
+
60
+ demo = gr.Interface(fn=gradio_model_inference,
61
+ inputs=gr.Textbox(lines=10, label='Judgment', placeholder="Please give an document here for inference."),
62
+ outputs=[gr.Textbox(label='Law article prediction'),
63
+ gr.Textbox(label='Sentence prediction')],
64
+ title="AI Judge (ML Zoomcamp Project)",
65
+ description="""## A Legal Decision Support System
66
+ ### 1. AI-powered Decision Making
67
+ Utilizing state-of-the-art machine learning algorithms, the AI Judgment Predictor processes vast amounts of legal data to generate accurate predictions regarding potential legal outcomes. This includes identifying the specific laws relevant to a case and evaluating their application in light of precedent-setting decisions.
68
+ ### 2. Sentencing Projections
69
+ In addition to identifying applicable laws, the AI Judgment Predictor goes a step further by providing estimations of potential sentences for incarceration. By considering factors such as the severity of the offense, any aggravating or mitigating circumstances, and jurisdiction-specific sentencing guidelines, the system offers a valuable insight into the potential legal ramifications.""",
70
+ # theme=gr.themes.Monochrome(),
71
+ article="![Alt text](https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTpZJRGjMclwPOjGNLaiGsKaloSP2CTz1Z4tg&usqp=CAU)",
72
+ examples=['理由本件原判決認定上訴人甲○○基於意圖營利之概括犯意,自民國八十六年四月上旬某日起至同年六月二十一日下午約四、五時止,先後在其位於雲林縣斗六市鎮○里鎮○路二七八巷十八號住處、雲林縣斗六市○○路某廟旁或同市○○路口戴凱勇所經營之「儂徠檳榔攤」、同市○○路五克拉MTV店內等地,將已裝有少許海洛因粉末之注射針筒,以每支新台幣(下同)一千元之價格販賣予戴凱勇六次(在鎮北路及儂徠檳榔攤各二次,其餘各一次),每次販賣一支予戴凱勇施用(販毒所得財物六千元),嗣於八十六年六月二十一日晚上七時五十分許,戴凱勇為警查獲後供出其毒品來源係向上訴人所購,經警授意再度以呼叫器連絡上訴人購買毒品,嗣於同日晚上十一時許,上訴人與不知情之劉忠興二人前往上開「儂徠檳榔攤」欲販賣予戴凱勇時,經警方逮捕上訴人、劉忠興(已經第一審另案判處施用毒品罪刑確定)二人,並在上訴人身上扣得其供預備販賣所用已裝有海洛因粉末之注射針筒三支及毒品海洛因一小包(警方為檢驗方便,將三支針筒內之海洛因倒出分別裝入三小包夾鏈袋內,總共四小包海洛因送驗之驗餘淨重○‧一○公克)等情,因而撤銷第一審關於上訴人販賣毒品部分之科刑判決,改判仍論處上訴人連續販賣毒品(累犯)罪刑,固非無見'] )
73
+ demo.launch(share=True)
74
+
75
+ try:
76
+ shutil.rmtree('./lightning_logs')
77
+ except FileNotFoundError:
78
+ pass
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cn2an
2
+ flask
3
+ fastapi
4
+ gradio
5
+ gunicorn
6
+ uvicorn
7
+ ipykernel
8
+ lightning-flash[text]
9
+ nbformat
10
+ pandas
11
+ pyarrow