andrew3279 commited on
Commit
fd0db56
1 Parent(s): 52751aa

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -0
app.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoTokenizer, AutoModelForCausalLM
2
+ from itertools import chain
3
+ import gradio as gr
4
+ import torch
5
+
6
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
7
+ print(device)
8
+
9
+ tokenizer = AutoTokenizer.from_pretrained("uer/gpt2-chinese-cluecorpussmall")
10
+ model = AutoModelForCausalLM.from_pretrained("uer/gpt2-chinese-cluecorpussmall").to(device)
11
+
12
+ def generate_text(prompt,length=1000):
13
+ inputs = tokenizer(prompt,add_special_tokens=False, return_tensors="pt").to(device)
14
+
15
+ txt = tokenizer.decode(model.generate(inputs["input_ids"],
16
+ max_length=length,
17
+ num_beams=2,
18
+ no_repeat_ngram_size=2,
19
+ early_stopping=True,
20
+ pad_token_id = 0
21
+ )[0])
22
+
23
+ #Replace text
24
+ replacements = {
25
+ '[': "",
26
+ ']': "",
27
+ 'S': "",
28
+ 'E': "",
29
+ 'P': "",
30
+ 'U': "",
31
+ 'N': "",
32
+ 'K': ""
33
+ }
34
+
35
+
36
+ new_text = ''.join(chain.from_iterable(replacements.get(word, [word]) for word in txt))
37
+
38
+
39
+ return new_text
40
+
41
+ with gr.Blocks() as web:
42
+ gr.Markdown("<h1><center>Andrew Lim Chinese stories </center></h1>")
43
+ gr.Markdown("""<h2><center>让人工智能讲故事:<br><br>
44
+ <img src=https://images.unsplash.com/photo-1550450339-e7a4787a2074?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1252&q=80></center></h2>""")
45
+ gr.Markdown("""<center>******</center>""")
46
+
47
+
48
+ input_text = gr.Textbox(label="故事的开始", lines=6)
49
+ buton = gr.Button("Submit ")
50
+ output_text = gr.Textbox(lines=6, label="人工智能讲一个故事 :")
51
+ buton.click(generate_text, inputs=[input_text], outputs=output_text)
52
+
53
+ web.launch()