Oliver12315 commited on
Commit
d0ebf51
1 Parent(s): 300b042

test persistent mount

Browse files
Files changed (1) hide show
  1. app.py +181 -83
app.py CHANGED
@@ -1,32 +1,27 @@
1
  import gradio as gr
2
  import pandas as pd
3
- import matplotlib.pyplot as plt
4
  from Prediction import *
5
  import os
6
  from datetime import datetime
7
-
8
-
9
- # examples = []
10
- # if os.path.exists("assets/examples.txt"):
11
- # with open("assets/examples.txt", "r", encoding="utf8") as file:
12
- # for sentence in file:
13
- # sentence = sentence.strip()
14
- # examples.append(sentence)
15
- # else:
16
- examples = [
17
- "Ends tonight! Shop select certifiably comfortable shoes!",
18
- "Just Do it!",
19
- "Don't miss our products!",
20
- "What are some of your favorite jokes? Let us know!",
21
- "Is anyone being creative with their snow day?",
22
- "Did you see our latest movie?",
23
- "In fact, we discovered that Woollip works better than what we imagined.",
24
- "It is made of Titanium Grade 5, a material famous for being very strong yet very light.",
25
- "Each game already comes with six characters.",
26
- "We thank you personally for the trust you are putting in us and our company.",
27
- "I wear it everyday and am very happy with it!",
28
- "We are so grateful for our everyday heroes who never cease to amaze us!"
29
- ]
30
 
31
  device = torch.device('cpu')
32
  tokenizer = BertTokenizer.from_pretrained("Oliver12315/Brand_Tone_of_Voice")
@@ -51,6 +46,65 @@ def csv_process(csv_file, attr="content"):
51
  outputs.append(output_path)
52
  return outputs
53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
  my_theme = gr.Theme.from_hub("JohnSmith9982/small_and_pretty")
56
  with gr.Blocks(theme=my_theme, title='Brand_Tone_of_Voice_demo') as demo:
@@ -64,70 +118,114 @@ with gr.Blocks(theme=my_theme, title='Brand_Tone_of_Voice_demo') as demo:
64
  <h5 style="margin: 0;">If you like our project, please give us a star ✨ on Github for the latest update.</h5>
65
  <div style="display: flex; justify-content: center; align-items: center; text-align: center;>
66
  <a href="https://arxiv.org/abs/xx.xx"><img src="https://img.shields.io/badge/Arxiv-xx.xx-red"></a>
67
- <a href='https://huggingface.co/spaces/Oliver12315/Brand_Tone_of_Voice_Online_Demo'><img src='https://img.shields.io/badge/Project_Page-Oliver12315/Brand_Tone_of_Voice_Online_Demo' alt='Project Page'></a>
68
  <a href='https://github.com'><img src='https://img.shields.io/badge/Github-Code-blue'></a>
69
  </div>
70
  </div>
71
  </div>
72
  """)
73
 
74
- with gr.Tab("Single Sentence"):
75
- with gr.Row():
76
- tbox_input = gr.Textbox(label="Input",
77
- info="Please input a sentence here:")
78
- gr.Markdown("""
79
- # Detailed information about our model:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  ...
81
- """)
82
- tab_output = gr.DataFrame(label='Predictions:',
83
- headers=["Label", "Probability"],
84
- datatype=["str", "number"],
85
- interactive=False)
86
- with gr.Row():
87
- button_ss = gr.Button("Submit", variant="primary")
88
- button_ss.click(fn=single_sentence, inputs=[tbox_input], outputs=[tab_output])
89
- gr.ClearButton([tbox_input, tab_output])
90
-
91
- gr.Examples(
92
- examples=examples,
93
- inputs=tbox_input,
94
- examples_per_page=len(examples)
95
- )
96
-
97
- with gr.Tab("CSV File"):
98
- with gr.Row():
99
- csv_input = gr.File(label="CSV File:",
100
- file_types=['.csv'],
101
- file_count="single"
102
- )
103
- csv_output = gr.File(label="Predictions:")
104
-
105
- with gr.Row():
106
- button = gr.Button("Submit", variant="primary")
107
- button.click(fn=csv_process, inputs=[csv_input], outputs=[csv_output])
108
- gr.ClearButton([csv_input, csv_output])
109
-
110
- gr.Markdown("## Examples \n The incoming CSV must include the ``content`` field, which represents the text that needs to be predicted!")
111
- gr.DataFrame(label='Csv input format:',
112
- value=[[i, examples[i]] for i in range(len(examples))],
113
- headers=["index", "content"],
114
- datatype=["number","str"],
115
- interactive=False
116
- )
117
-
118
- with gr.Tab("Readme"):
119
- gr.Markdown(
120
- """
121
- # Paper Name
122
-
123
- # Authors
124
-
125
- + First author
126
- + Corresponding author
127
-
128
- # Detailed Information
129
-
130
- ...
131
- """
132
- )
133
  demo.launch()
 
1
  import gradio as gr
2
  import pandas as pd
 
3
  from Prediction import *
4
  import os
5
  from datetime import datetime
6
+ import re
7
+ import json
8
+
9
+ persistent_path = "/data"
10
+ os.environ['HF_HOME'] = os.path.join(persistent_path, ".huggingface")
11
+ user_input_path = os.path.join(persistent_path, 'user.jsonl')
12
+
13
+ examples = []
14
+ if os.path.exists("assets/examples.txt"):
15
+ with open("assets/examples.txt", "r", encoding="utf8") as file:
16
+ for sentence in file:
17
+ sentence = sentence.strip()
18
+ examples.append(sentence)
19
+ else:
20
+ examples = [
21
+ "Games of the imagination teach us actions have consequences in a realm that can be reset.",
22
+ "But New Jersey farmers are retiring and all over the state, development continues to push out dwindling farmland.",
23
+ "He also is the Head Designer of The Design Trust so-to-speak, besides his regular job ..."
24
+ ]
 
 
 
 
25
 
26
  device = torch.device('cpu')
27
  tokenizer = BertTokenizer.from_pretrained("Oliver12315/Brand_Tone_of_Voice")
 
46
  outputs.append(output_path)
47
  return outputs
48
 
49
+ def check_save(fname, lname, cnum, email, oname, position):
50
+ errors = []
51
+ valid_vars = {}
52
+
53
+ if not fname.strip() or not lname.strip():
54
+ errors.append("Name cannot be empty")
55
+ elif fname.isdigit() or lname.isdigit():
56
+ errors.append("Name cannot be purely numerical")
57
+ else:
58
+ valid_vars["fname"] = fname
59
+ valid_vars["lname"] = lname
60
+
61
+ valid_vars["cnum"] = ''
62
+ if cnum:
63
+ if not cnum.isdigit():
64
+ errors.append("The phone number must be a pure number")
65
+ else:
66
+ valid_vars["cnum"] = cnum
67
+
68
+ if not email.strip():
69
+ errors.append("Email cannot be empty")
70
+ elif not re.match(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$', email):
71
+ errors.append("Incorrect email format")
72
+ else:
73
+ valid_vars["email"] = email
74
+
75
+ if not oname.strip():
76
+ errors.append("Organization name cannot be empty")
77
+ elif oname.isdigit():
78
+ errors.append("Organization cannot be purely numerical")
79
+ else:
80
+ valid_vars["oname"] = oname
81
+
82
+ valid_vars["position"] = ''
83
+ if position:
84
+ if position.isdigit():
85
+ errors.append("Position in your company cannot be purely numerical")
86
+ else:
87
+ valid_vars["position"] = position
88
+
89
+ if errors:
90
+ return errors
91
+
92
+ current_time = datetime.now()
93
+ formatted_time = current_time.strftime("%Y_%m_%d_%H_%M_%S")
94
+ valid_vars['time'] = formatted_time
95
+
96
+ with open(user_input_path, 'a+', encoding="utf8") as file:
97
+ file.write(json.dumps(valid_vars)+"\n")
98
+
99
+ records = {}
100
+ with open(user_input_path, 'r', encoding="utf8") as file:
101
+ for line in file:
102
+ line = line.strip()
103
+ dct = json.loads(line)
104
+ records[dct['time']] = dct
105
+
106
+ return records
107
+
108
 
109
  my_theme = gr.Theme.from_hub("JohnSmith9982/small_and_pretty")
110
  with gr.Blocks(theme=my_theme, title='Brand_Tone_of_Voice_demo') as demo:
 
118
  <h5 style="margin: 0;">If you like our project, please give us a star ✨ on Github for the latest update.</h5>
119
  <div style="display: flex; justify-content: center; align-items: center; text-align: center;>
120
  <a href="https://arxiv.org/abs/xx.xx"><img src="https://img.shields.io/badge/Arxiv-xx.xx-red"></a>
121
+ <a href='https://huggingface.co/spaces/Oliver12315/Brand_Tone_of_Voice_demo'><img src='https://img.shields.io/badge/Project_Page-Oliver12315/Brand_Tone_of_Voice_demo' alt='Project Page'></a>
122
  <a href='https://github.com'><img src='https://img.shields.io/badge/Github-Code-blue'></a>
123
  </div>
124
  </div>
125
  </div>
126
  """)
127
 
128
+
129
+ debug_tb = gr.Textbox(label="Persistent: ", type='text')
130
+ with gr.Column(visible=True) as regis:
131
+ gr.Markdown("# Welcome to BTV! Please fill out the form below to continue.\nI’m assuming that you mention somewhere that this project/research is conducted by the University of Manchester/AMBS. By ticking this box, I consent to be approached by the research team of the University of Manchester.")
132
+ with gr.Column(variant='panel'):
133
+ fname_tb = gr.Textbox(label="First Name: ", type='text')
134
+ lname_tb = gr.Textbox(label="Last Name: ", type='text')
135
+ email_tb = gr.Textbox(label="Email: ", type='email')
136
+ cnum_tb = gr.Textbox(label="Contact: (Optional)", type='text')
137
+ oname_tb = gr.Textbox(label="Organization name: ", type='text')
138
+ position_tb = gr.Textbox(label="Positions in your company: (Optional)", type='text')
139
+ error_box = gr.HTML(value="", visible=False)
140
+ submit_btn = gr.Button("Click here to start if you have fullfill all the item!")
141
+
142
+ with gr.Row(visible=False) as mainrow:
143
+
144
+ with gr.Tab("Single Sentence"):
145
+ with gr.Row():
146
+ tbox_input = gr.Textbox(label="Input",
147
+ info="Please input a sentence here:")
148
+ gr.Markdown("""
149
+ # Detailed information about our model:
150
+ ...
151
+ """)
152
+ tab_output = gr.DataFrame(label='Predictions:',
153
+ headers=["Label", "Probability"],
154
+ datatype=["str", "number"],
155
+ interactive=False)
156
+ with gr.Row():
157
+ button_ss = gr.Button("Submit", variant="primary", visible=False)
158
+ button_ss.click(fn=single_sentence, inputs=[tbox_input], outputs=[tab_output])
159
+ gr.ClearButton([tbox_input, tab_output])
160
+
161
+ gr.Examples(
162
+ examples=examples,
163
+ inputs=tbox_input,
164
+ examples_per_page=len(examples)
165
+ )
166
+
167
+ with gr.Tab("Csv File"):
168
+ with gr.Row():
169
+ csv_input = gr.File(label="CSV File:",
170
+ file_types=['.csv'],
171
+ file_count="single"
172
+ )
173
+ csv_output = gr.File(label="Predictions:")
174
+
175
+ with gr.Row():
176
+ button_cf = gr.Button("Submit", variant="primary", visible=False)
177
+ button_cf.click(fn=csv_process, inputs=[csv_input], outputs=[csv_output])
178
+ gr.ClearButton([csv_input, csv_output])
179
+
180
+ gr.Markdown("## Examples \n The incoming CSV must include the ``content`` field, which represents the text that needs to be predicted!")
181
+ gr.DataFrame(label='Csv input format:',
182
+ value=[[i, examples[i]] for i in range(len(examples))],
183
+ headers=["index", "content"],
184
+ datatype=["number","str"],
185
+ interactive=False
186
+ )
187
+
188
+ with gr.Tab("Readme"):
189
+ gr.Markdown(
190
+ """
191
+ # Paper Name
192
+
193
+ # Authors
194
+
195
+ + First author
196
+ + Corresponding author
197
+
198
+ # Detailed Information
199
+
200
  ...
201
+ """
202
+ )
203
+
204
+ def submit(*user_input):
205
+ res = check_save(*user_input)
206
+ if isinstance(res, list):
207
+ return {
208
+ error_box: gr.HTML(
209
+ value=f"""
210
+ <div style="display: flex; justify-content: center; align-items: center; text-align: center;">
211
+ <div>
212
+ <p style="color:red;">{"; ".join(res)}</p>
213
+ </div>
214
+ </div>
215
+ """,
216
+ visible=True)
217
+ }
218
+ else:
219
+ return {
220
+ mainrow: gr.Row(visible=True),
221
+ regis: gr.Row(visible=False),
222
+ error_box: gr.HTML(visible=False),
223
+ debug_tb: gr.Textbox(value=json.dumps(res), type='text', visible=True)
224
+ }
225
+
226
+ submit_btn.click(
227
+ submit,
228
+ [fname_tb, lname_tb, cnum_tb, email_tb, oname_tb, position_tb],
229
+ [mainrow, regis, error_box, debug_tb],
230
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
231
  demo.launch()