yangheng commited on
Commit
2af1644
1 Parent(s): d42914b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +148 -53
app.py CHANGED
@@ -1,25 +1,33 @@
1
- import os
 
 
 
 
 
 
 
 
2
  import random
3
  import gradio as gr
4
  import pandas as pd
5
- import requests
6
- import shutil
7
-
8
- from pyabsa import download_all_available_datasets, AspectTermExtraction as ATEPC, TaskCodeOption
 
 
 
9
  from pyabsa.utils.data_utils.dataset_manager import detect_infer_dataset
10
 
11
- if os.path.exists("integrated_datasets"):
12
- shutil.rmtree("integrated_datasets")
13
- if os.path.exists("source_datasets.backup"):
14
- shutil.rmtree("source_datasets.backup")
15
-
16
  download_all_available_datasets()
17
 
18
- dataset_items = {dataset.name: dataset for dataset in ATEPC.ATEPCDatasetList()}
 
 
19
 
20
- def get_example(dataset):
21
  task = TaskCodeOption.Aspect_Polarity_Classification
22
- dataset_file = detect_infer_dataset(dataset_items[dataset], task)
23
 
24
  for fname in dataset_file:
25
  lines = []
@@ -27,65 +35,152 @@ def get_example(dataset):
27
  fname = [fname]
28
 
29
  for f in fname:
30
- print('loading: {}'.format(f))
31
- fin = open(f, 'r', encoding='utf-8')
32
  lines.extend(fin.readlines())
33
  fin.close()
34
  for i in range(len(lines)):
35
- lines[i] = lines[i][:lines[i].find('$LABEL$')].replace('[B-ASP]', '').replace('[E-ASP]', '').strip()
 
 
 
 
 
36
  return sorted(set(lines), key=lines.index)
37
 
38
 
39
- dataset_dict = {dataset.name: get_example(dataset.name) for dataset in ATEPC.ATEPCDatasetList()}
40
- aspect_extractor = ATEPC.AspectExtractor(checkpoint='multilingual')
 
41
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
- def perform_inference(text, dataset):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  if not text:
45
- text = dataset_dict[dataset][random.randint(0, len(dataset_dict[dataset]) - 1)]
 
 
46
 
47
- result = aspect_extractor.predict(text,
48
- pred_sentiment=True)
49
 
50
- result = pd.DataFrame({
51
- 'aspect': result['aspect'],
52
- 'sentiment': result['sentiment'],
53
- # 'probability': result[0]['probs'],
54
- 'confidence': [round(x, 4) for x in result['confidence']],
55
- 'position': result['position']
56
- })
57
- return result, '{}'.format(text)
58
 
59
 
60
  demo = gr.Blocks()
61
 
62
  with demo:
63
- gr.Markdown("# <p align='center'>Multilingual Aspect-based Sentiment Analysis !</p>")
64
- gr.Markdown("""### Repo: [PyABSA V2](https://github.com/yangheng95/PyABSA)
65
- ### Author: [Heng Yang](https://github.com/yangheng95) (杨恒)
66
- [![Downloads](https://pepy.tech/badge/pyabsa)](https://pepy.tech/project/pyabsa)
67
- [![Downloads](https://pepy.tech/badge/pyabsa/month)](https://pepy.tech/project/pyabsa)
68
- """
69
- )
70
- 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 ")
71
- gr.Markdown("**You don't need to split each Chinese (Korean, etc.) token as the provided, just input the natural language text.**")
72
- output_dfs = []
73
  with gr.Row():
74
- with gr.Column():
75
- input_sentence = gr.Textbox(placeholder='Leave this box blank and choose a dataset will give you a random example...', label="Example:")
76
- gr.Markdown("You can find the datasets at [github.com/yangheng95/ABSADatasets](https://github.com/yangheng95/ABSADatasets/tree/v1.2/datasets/text_classification)")
77
- dataset_ids = gr.Radio(choices=[dataset.name for dataset in ATEPC.ATEPCDatasetList()[:-1]], value='Laptop14', label="Datasets")
78
- inference_button = gr.Button("Let's go!")
79
- gr.Markdown("There is a [demo](https://huggingface.co/spaces/yangheng/PyABSA-ATEPC-Chinese) specialized for the Chinese langauge")
80
- gr.Markdown("This demo support many other language as well, you can try and explore the results of other languages by yourself.")
81
 
82
  with gr.Column():
83
- output_text = gr.TextArea(label="Example:")
84
- output_df = gr.DataFrame(label="Prediction Results:")
85
- output_dfs.append(output_df)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
- inference_button.click(fn=perform_inference,
88
- inputs=[input_sentence, dataset_ids],
89
- outputs=[output_df, output_text])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
 
91
  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
  with gr.Row():
 
 
 
 
 
 
 
120
 
121
  with gr.Column():
122
+ gr.Markdown("# <p align='center'>Aspect Sentiment Triplet Extraction !</p>")
123
+
124
+ with gr.Row():
125
+ with gr.Column():
126
+ aste_input_sentence = gr.Textbox(
127
+ placeholder="Leave this box blank and choose a dataset will give you a random example...",
128
+ label="Example:",
129
+ )
130
+ gr.Markdown(
131
+ "You can find code and dataset at [ASTE examples](https://github.com/yangheng95/PyABSA/tree/v2/examples-v2/aspect_sentiment_triplet_extration)"
132
+ )
133
+ aste_dataset_ids = gr.Radio(
134
+ choices=[dataset.name for dataset in ASTE.ASTEDatasetList()[:-1]],
135
+ value="Restaurant14",
136
+ label="Datasets",
137
+ )
138
+ aste_inference_button = gr.Button("Let's go!")
139
+
140
+ aste_output_text = gr.TextArea(label="Example:")
141
+ aste_output_pred_df = gr.DataFrame(label="Predicted Triplets:")
142
+ aste_output_true_df = gr.DataFrame(label="Original Triplets:")
143
+
144
+ aste_inference_button.click(
145
+ fn=perform_aste_inference,
146
+ inputs=[aste_input_sentence, aste_dataset_ids],
147
+ outputs=[aste_output_pred_df, aste_output_true_df, aste_output_text],
148
+ )
149
 
150
+ with gr.Column():
151
+ gr.Markdown(
152
+ "# <p align='center'>Multilingual Aspect-based Sentiment Analysis !</p>"
153
+ )
154
+ with gr.Row():
155
+ with gr.Column():
156
+ atepc_input_sentence = gr.Textbox(
157
+ placeholder="Leave this box blank and choose a dataset will give you a random example...",
158
+ label="Example:",
159
+ )
160
+ gr.Markdown(
161
+ "You can find the datasets at [github.com/yangheng95/ABSADatasets](https://github.com/yangheng95/ABSADatasets/tree/v1.2/datasets/text_classification)"
162
+ )
163
+ atepc_dataset_ids = gr.Radio(
164
+ choices=[dataset.name for dataset in ATEPC.ATEPCDatasetList()[:-1]],
165
+ value="Laptop14",
166
+ label="Datasets",
167
+ )
168
+ atepc_inference_button = gr.Button("Let's go!")
169
+
170
+ atepc_output_text = gr.TextArea(label="Example:")
171
+ atepc_output_df = gr.DataFrame(label="Prediction Results:")
172
+
173
+ atepc_inference_button.click(
174
+ fn=perform_atepc_inference,
175
+ inputs=[atepc_input_sentence, atepc_dataset_ids],
176
+ outputs=[atepc_output_df, atepc_output_text],
177
+ )
178
+ gr.Markdown(
179
+ """### GitHub Repo: [PyABSA V2](https://github.com/yangheng95/PyABSA)
180
+ ### Author: [Heng Yang](https://github.com/yangheng95) (杨恒)
181
+ [![Downloads](https://pepy.tech/badge/pyabsa)](https://pepy.tech/project/pyabsa)
182
+ [![Downloads](https://pepy.tech/badge/pyabsa/month)](https://pepy.tech/project/pyabsa)
183
+ """
184
+ )
185
 
186
  demo.launch()