yangheng commited on
Commit
88f8e2a
β€’
1 Parent(s): 8cf98ad

update_app

Browse files
Files changed (1) hide show
  1. app.py +159 -45
app.py CHANGED
@@ -1,19 +1,33 @@
1
- import os
 
 
 
 
 
 
 
 
2
  import random
3
  import gradio as gr
4
  import pandas as pd
5
- import requests
6
-
7
- from pyabsa import download_all_available_datasets, AspectTermExtraction as ATEPC, TaskCodeOption
 
 
 
 
8
  from pyabsa.utils.data_utils.dataset_manager import detect_infer_dataset
9
 
10
  download_all_available_datasets()
11
 
12
- dataset_items = {dataset.name: dataset for dataset in ATEPC.ATEPCDatasetList()}
 
 
13
 
14
- def get_example(dataset):
15
  task = TaskCodeOption.Aspect_Polarity_Classification
16
- dataset_file = detect_infer_dataset(dataset_items[dataset], task)
17
 
18
  for fname in dataset_file:
19
  lines = []
@@ -21,65 +35,165 @@ def get_example(dataset):
21
  fname = [fname]
22
 
23
  for f in fname:
24
- print('loading: {}'.format(f))
25
- fin = open(f, 'r', encoding='utf-8')
26
  lines.extend(fin.readlines())
27
  fin.close()
28
  for i in range(len(lines)):
29
- lines[i] = lines[i][:lines[i].find('$LABEL$')].replace('[B-ASP]', '').replace('[E-ASP]', '').strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  return sorted(set(lines), key=lines.index)
31
 
32
 
33
- dataset_dict = {dataset.name: get_example(dataset.name) for dataset in ATEPC.ATEPCDatasetList()}
34
- aspect_extractor = ATEPC.AspectExtractor(checkpoint='multilingual')
35
 
 
 
 
 
 
36
 
37
- def perform_inference(text, dataset):
 
 
 
 
 
 
38
  if not text:
39
- text = dataset_dict[dataset][random.randint(0, len(dataset_dict[dataset]) - 1)]
 
 
 
 
40
 
41
- result = aspect_extractor.predict(text,
42
- pred_sentiment=True)
 
 
 
 
 
 
 
 
43
 
44
- result = pd.DataFrame({
45
- 'aspect': result['aspect'],
46
- 'sentiment': result['sentiment'],
47
- # 'probability': result[0]['probs'],
48
- 'confidence': [round(x, 4) for x in result['confidence']],
49
- 'position': result['position']
50
- })
51
- return result, '{}'.format(text)
 
 
 
 
52
 
53
 
54
  demo = gr.Blocks()
55
 
56
  with demo:
57
- gr.Markdown("# <p align='center'>Multilingual Aspect-based Sentiment Analysis !</p>")
58
- gr.Markdown("""### Repo: [PyABSA V2](https://github.com/yangheng95/PyABSA)
59
- ### Author: [Heng Yang](https://github.com/yangheng95) (杨恒)
60
- [![Downloads](https://pepy.tech/badge/pyabsa)](https://pepy.tech/project/pyabsa)
61
- [![Downloads](https://pepy.tech/badge/pyabsa/month)](https://pepy.tech/project/pyabsa)
62
- """
63
- )
64
- gr.Markdown("Your input text should be no more than 80 words, that's the longest text we used in trainer. However, you can try longer text in self-trainer ")
65
- gr.Markdown("**You don't need to split each Chinese (Korean, etc.) token as the provided, just input the natural language text.**")
 
 
66
  output_dfs = []
 
 
67
  with gr.Row():
68
  with gr.Column():
69
- input_sentence = gr.Textbox(placeholder='Leave this box blank and choose a dataset will give you a random example...', label="Example:")
70
- gr.Markdown("You can find the datasets at [github.com/yangheng95/ABSADatasets](https://github.com/yangheng95/ABSADatasets/tree/v1.2/datasets/text_classification)")
71
- dataset_ids = gr.Radio(choices=[dataset.name for dataset in ATEPC.ATEPCDatasetList()[:-1]], value='Laptop14', label="Datasets")
72
- inference_button = gr.Button("Let's go!")
73
- gr.Markdown("There is a [demo](https://huggingface.co/spaces/yangheng/PyABSA-ATEPC-Chinese) specialized for the Chinese langauge")
74
- gr.Markdown("This demo support many other language as well, you can try and explore the results of other languages by yourself.")
 
 
 
 
 
 
 
75
 
76
  with gr.Column():
77
- output_text = gr.TextArea(label="Example:")
78
- output_df = gr.DataFrame(label="Prediction Results:")
79
- output_dfs.append(output_df)
80
 
81
- inference_button.click(fn=perform_inference,
82
- inputs=[input_sentence, dataset_ids],
83
- outputs=[output_df, output_text])
 
 
84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  demo.launch()
 
1
+ # -*- coding: utf-8 -*-
2
+ # file: app.py
3
+ # time: 17:08 2023/3/6
4
+ # author: YANG, HENG <hy345@exeter.ac.uk> (杨恒)
5
+ # github: https://github.com/yangheng95
6
+ # huggingface: https://huggingface.co/yangheng
7
+ # google scholar: https://scholar.google.com/citations?user=NPq5a_0AAAAJ&hl=en
8
+ # Copyright (C) 2023. All Rights Reserved.
9
+
10
  import random
11
  import gradio as gr
12
  import pandas as pd
13
+ from pyabsa import (
14
+ download_all_available_datasets,
15
+ AspectTermExtraction as ATEPC,
16
+ TaskCodeOption,
17
+ available_checkpoints,
18
+ )
19
+ from pyabsa import AspectSentimentTripletExtraction as ASTE
20
  from pyabsa.utils.data_utils.dataset_manager import detect_infer_dataset
21
 
22
  download_all_available_datasets()
23
 
24
+ atepc_dataset_items = {dataset.name: dataset for dataset in ATEPC.ATEPCDatasetList()}
25
+ aste_dataset_items = {dataset.name: dataset for dataset in ASTE.ASTEDatasetList()}
26
+
27
 
28
+ def get_atepc_example(dataset):
29
  task = TaskCodeOption.Aspect_Polarity_Classification
30
+ dataset_file = detect_infer_dataset(atepc_dataset_items[dataset], task)
31
 
32
  for fname in dataset_file:
33
  lines = []
 
35
  fname = [fname]
36
 
37
  for f in fname:
38
+ print("loading: {}".format(f))
39
+ fin = open(f, "r", encoding="utf-8")
40
  lines.extend(fin.readlines())
41
  fin.close()
42
  for i in range(len(lines)):
43
+ lines[i] = (
44
+ lines[i][: lines[i].find("$LABEL$")]
45
+ .replace("[B-ASP]", "")
46
+ .replace("[E-ASP]", "")
47
+ .strip()
48
+ )
49
+ return sorted(set(lines), key=lines.index)
50
+
51
+
52
+ def get_aste_example(dataset):
53
+ task = TaskCodeOption.Aspect_Sentiment_Triplet_Extraction
54
+ dataset_file = detect_infer_dataset(aste_dataset_items[dataset], task)
55
+
56
+ for fname in dataset_file:
57
+ lines = []
58
+ if isinstance(fname, str):
59
+ fname = [fname]
60
+
61
+ for f in fname:
62
+ print("loading: {}".format(f))
63
+ fin = open(f, "r", encoding="utf-8")
64
+ lines.extend(fin.readlines())
65
+ fin.close()
66
  return sorted(set(lines), key=lines.index)
67
 
68
 
69
+ available_checkpoints("ASTE", True)
 
70
 
71
+ atepc_dataset_dict = {
72
+ dataset.name: get_atepc_example(dataset.name)
73
+ for dataset in ATEPC.ATEPCDatasetList()
74
+ }
75
+ aspect_extractor = ATEPC.AspectExtractor(checkpoint="multilingual")
76
 
77
+ aste_dataset_dict = {
78
+ dataset.name: get_aste_example(dataset.name) for dataset in ASTE.ASTEDatasetList()
79
+ }
80
+ triplet_extractor = ASTE.AspectSentimentTripletExtractor(checkpoint="english")
81
+
82
+
83
+ def perform_atepc_inference(text, dataset):
84
  if not text:
85
+ text = atepc_dataset_dict[dataset][
86
+ random.randint(0, len(atepc_dataset_dict[dataset]) - 1)
87
+ ]
88
+
89
+ result = aspect_extractor.predict(text, pred_sentiment=True)
90
 
91
+ result = pd.DataFrame(
92
+ {
93
+ "aspect": result["aspect"],
94
+ "sentiment": result["sentiment"],
95
+ # 'probability': result[0]['probs'],
96
+ "confidence": [round(x, 4) for x in result["confidence"]],
97
+ "position": result["position"],
98
+ }
99
+ )
100
+ return result, "{}".format(text)
101
 
102
+
103
+ def perform_aste_inference(text, dataset):
104
+ if not text:
105
+ text = aste_dataset_dict[dataset][
106
+ random.randint(0, len(aste_dataset_dict[dataset]) - 1)
107
+ ]
108
+
109
+ result = triplet_extractor.predict(text)
110
+
111
+ pred_triplets = pd.DataFrame(result["Triplets"])
112
+ true_triplets = pd.DataFrame(result["True Triplets"])
113
+ return pred_triplets, true_triplets, "{}".format(text)
114
 
115
 
116
  demo = gr.Blocks()
117
 
118
  with demo:
119
+
120
+ gr.Markdown("# <p align='center'>Aspect Sentiment Triplet Extraction !</p>")
121
+
122
+ gr.Markdown(
123
+ "Your input text should be no more than 80 words, that's the longest text we used in trainer. "
124
+ "However, you can try longer text in self-trainer "
125
+ )
126
+ gr.Markdown(
127
+ "**You don't need to split each Chinese (Korean, etc.) token as the provided,"
128
+ " just input the natural language text.**"
129
+ )
130
  output_dfs = []
131
+
132
+
133
  with gr.Row():
134
  with gr.Column():
135
+ aste_input_sentence = gr.Textbox(
136
+ placeholder="Leave this box blank and choose a dataset will give you a random example...",
137
+ label="Example:",
138
+ )
139
+ gr.Markdown(
140
+ "You can find code and dataset at [ASTE examples](https://github.com/yangheng95/PyABSA/examples-v2/aspect_sentiment_triplet_extration)"
141
+ )
142
+ aste_dataset_ids = gr.Radio(
143
+ choices=[dataset.name for dataset in ASTE.ASTEDatasetList()[:-1]],
144
+ value="Restaurant14",
145
+ label="Datasets",
146
+ )
147
+ aste_inference_button = gr.Button("Let's go!")
148
 
149
  with gr.Column():
150
+ aste_output_text = gr.TextArea(label="Example:")
151
+ aste_output_pred_df = gr.DataFrame(label="Predicted Triplets:")
152
+ aste_output_true_df = gr.DataFrame(label="Original Triplets:")
153
 
154
+ aste_inference_button.click(
155
+ fn=perform_aste_inference,
156
+ inputs=[aste_input_sentence, aste_dataset_ids],
157
+ outputs=[aste_output_pred_df, aste_output_true_df, aste_output_text],
158
+ )
159
 
160
+
161
+ gr.Markdown(
162
+ "# <p align='center'>Multilingual Aspect-based Sentiment Analysis !</p>"
163
+ )
164
+ with gr.Row():
165
+ with gr.Column():
166
+ atepc_input_sentence = gr.Textbox(
167
+ placeholder="Leave this box blank and choose a dataset will give you a random example...",
168
+ label="Example:",
169
+ )
170
+ gr.Markdown(
171
+ "You can find the datasets at [github.com/yangheng95/ABSADatasets](https://github.com/yangheng95/ABSADatasets/tree/v1.2/datasets/text_classification)"
172
+ )
173
+ atepc_dataset_ids = gr.Radio(
174
+ choices=[dataset.name for dataset in ATEPC.ATEPCDatasetList()[:-1]],
175
+ value="Laptop14",
176
+ label="Datasets",
177
+ )
178
+ atepc_inference_button = gr.Button("Let's go!")
179
+
180
+ with gr.Column():
181
+ atepc_output_text = gr.TextArea(label="Example:")
182
+ atepc_output_df = gr.DataFrame(label="Prediction Results:")
183
+
184
+ atepc_inference_button.click(
185
+ fn=perform_atepc_inference,
186
+ inputs=[atepc_input_sentence, atepc_dataset_ids],
187
+ outputs=[atepc_output_df, atepc_output_text],
188
+ )
189
+ gr.Markdown(
190
+ """### Repo: [PyABSA V2](https://github.com/yangheng95/PyABSA)
191
+ ### Author: [Heng Yang](https://github.com/yangheng95) (杨恒)
192
+ [![Downloads](https://pepy.tech/badge/pyabsa)](https://pepy.tech/project/pyabsa)
193
+ [![Downloads](https://pepy.tech/badge/pyabsa/month)](https://pepy.tech/project/pyabsa)
194
+ """
195
+ )
196
+ gr.Markdown(
197
+ "This demo support many other language as well, you can try and explore the results of other languages by yourself."
198
+ )
199
  demo.launch()