wseo commited on
Commit
6b1f6b2
1 Parent(s): 60a2f06

feat: automatic document completion

Browse files
Files changed (1) hide show
  1. app.py +169 -60
app.py CHANGED
@@ -1,76 +1,185 @@
1
- import gradio as gr
2
  import subprocess
3
- import openai
 
4
  import time
5
  import re
6
 
7
- def translate(text_input, openapi_key):
8
- openai.api_key = openapi_key
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
- # 라이선스 문장 제거
11
- rm_line = text_input.find('-->')
12
- text_list = text_input[rm_line+4:].split('\n')
13
- print(text_list)
 
14
 
 
15
  reply = []
16
 
17
- for i in range(0,len(text_list),10):
18
- content = """What do these sentences about Hugging Face Transformers (a machine learning library) mean in Korean? Please do not translate the word after a 🤗 emoji as it is a product name. Please ignore the video and image and translate only the sentences I provided. Ignore the contents of the iframe tag.
19
- ```md
20
- %s"""%'\n'.join(text_list[i:i+10])
21
-
22
  chat = openai.ChatCompletion.create(
23
- model = "gpt-3.5-turbo-0301", messages=[
24
- {"role": "system",
25
- "content": content},])
26
-
27
- print("질문")
28
- print(content)
29
- print("응답")
30
- print(chat.choices[0].message.content)
31
-
32
  reply.append(chat.choices[0].message.content)
33
 
34
- time.sleep(30)
35
-
36
- return ''.join(reply)
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
- inputs = [
39
- gr.inputs.Textbox(lines=2, label="Input Open API Key"),
40
- gr.inputs.File(label="Upload MDX File")
41
- ]
42
 
43
  outputs = gr.outputs.Textbox(label="Translation")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
- def translate_with_upload(text, file):
46
-
47
- openapi_key = text
48
-
49
- if file is not None:
50
- text_input = ""
51
- with open(file.name, 'r') as f:
52
- text_input += f.read()
53
- text_input += '\n'
54
- print(text_input)
55
- # 텍스트에서 코드 블록을 제거합니다.
56
- text_input = re.sub(r'```.*?```', '', text_input, flags=re.DOTALL)
57
-
58
- text_input = re.sub(r'^\|.*\|$\n?', '', text_input, flags=re.MULTILINE)
59
-
60
- # 텍스트에서 빈 줄을 제거합니다.
61
- text_input = re.sub(r'^\n', '', text_input, flags=re.MULTILINE)
62
- text_input = re.sub(r'\n\n+', '\n\n', text_input)
63
- else:
64
- text_input = ""
65
-
66
- return translate(text_input, openapi_key)
67
-
68
- prompt_translate = gr.Interface(
69
- fn=translate_with_upload,
70
- inputs=inputs,
71
- outputs=outputs,
72
- title="ChatGPT Korean Prompt Translation",
73
- description="Translate your text into Korean using the GPT-3 model.", verbose=True
74
- )
75
 
76
- prompt_translate.launch()
 
 
1
  import subprocess
2
+ import requests
3
+ import string
4
  import time
5
  import re
6
 
7
+ import openai
8
+ import gradio as gr
9
+
10
+ def get_content(filepath: str) -> str:
11
+ url = string.Template(
12
+ "https://raw.githubusercontent.com/huggingface/"
13
+ "transformers/main/docs/source/en/$filepath"
14
+ ).safe_substitute(filepath=filepath)
15
+ response = requests.get(url)
16
+ if response.status_code == 200:
17
+ content = response.text
18
+ return content
19
+ else:
20
+ raise ValueError("Failed to retrieve content from the URL.", url)
21
+
22
+ def preprocess_content(content: str) -> str:
23
+ # Extract text to translate from document
24
+
25
+ ## ignore top license comment
26
+ to_translate = content[content.find('#'):]
27
+ ## remove code blocks from text
28
+ to_translate = re.sub(r'```.*?```', '', to_translate, flags=re.DOTALL)
29
+ ## remove markdown tables from text
30
+ to_translate = re.sub(r'^\|.*\|$\n?', '', to_translate, flags=re.MULTILINE)
31
+ ## remove empty lines from text
32
+ to_translate = re.sub(r'\n\n+', '\n\n', to_translate)
33
+
34
+ return to_translate
35
+
36
+ def get_full_prompt(language: str, filepath: str) -> str:
37
+ content = get_content(filepath)
38
+ to_translate = preprocess_content(content)
39
+
40
+ prompt = string.Template(
41
+ "What do these sentences about Hugging Face Transformers "
42
+ "(a machine learning library) mean in $language? "
43
+ "Please do not translate the word after a 🤗 emoji "
44
+ "as it is a product name.\n```md"
45
+ ).safe_substitute(language=language)
46
+ return '\n'.join([prompt, to_translate.strip(), "```"])
47
+
48
+ def split_markdown_sections(markdown: str) -> list:
49
+ # Find all titles using regular expressions
50
+ return re.split(r'^(#+\s+)(.*)$', markdown, flags=re.MULTILINE)[1:]
51
+ # format is like [level, title, content, level, title, content, ...]
52
+
53
+ def get_anchors(divided: list) -> list:
54
+ anchors = []
55
+ # from https://github.com/huggingface/doc-builder/blob/01b262bae90d66e1150cdbf58c83c02733ed4366/src/doc_builder/build_doc.py#L300-L302
56
+ for title in divided[1::3]:
57
+ anchor = re.sub(r"[^a-z0-9\s]+", "", title.lower())
58
+ anchor = re.sub(r"\s{2,}", " ", anchor.strip()).replace(" ", "-")
59
+ anchors.append(f"[[{anchor}]]")
60
+ return anchors
61
+
62
+ def make_scaffold(content: str, to_translate: str) -> string.Template:
63
+ scaffold = content
64
+ for i, text in enumerate(to_translate.split('\n\n')):
65
+ scaffold = scaffold.replace(text, f'$hf_i18n_placeholder{i}', 1)
66
+ return string.Template(scaffold)
67
+
68
+ def fill_scaffold(filepath: str, translated: str) -> list[str]:
69
+ content = get_content(filepath)
70
+ to_translate = preprocess_content(content)
71
+
72
+ scaffold = make_scaffold(content, to_translate)
73
+ divided = split_markdown_sections(to_translate)
74
+ anchors = get_anchors(divided)
75
+
76
+ translated = split_markdown_sections(translated)
77
+ translated[1::3] = [
78
+ f"{korean_title} {anchors[i]}"
79
+ for i, korean_title in enumerate(translated[1::3])
80
+ ]
81
+ translated = ''.join([
82
+ ''.join(translated[i*3:i*3+3])
83
+ for i in range(len(translated) // 3)
84
+ ]).split('\n\n')
85
+ translated_doc = scaffold.safe_substitute({
86
+ f"hf_i18n_placeholder{i}": text
87
+ for i, text in enumerate(translated)
88
+ })
89
+
90
+ return [content, translated_doc]
91
+
92
+ def translate_openai(language: str, filepath: str, api_key: str) -> list[str]:
93
+ content = get_content(filepath)
94
+ return [content, "Please use the web UI for now."]
95
+ raise NotImplementedError("Currently debugging output.")
96
+
97
+ openai.api_key = api_key
98
+ prompt = string.Template(
99
+ "What do these sentences about Hugging Face Transformers "
100
+ "(a machine learning library) mean in $language? "
101
+ "Please do not translate the word after a 🤗 emoji "
102
+ "as it is a product name.\n```md"
103
+ ).safe_substitute(language=language)
104
 
105
+ to_translate = preprocess_content(content)
106
+
107
+ scaffold = make_scaffold(content, to_translate)
108
+ divided = split_markdown_sections(to_translate)
109
+ anchors = get_anchors(divided)
110
 
111
+ sections = [''.join(divided[i*3:i*3+3]) for i in range(len(divided) // 3)]
112
  reply = []
113
 
114
+ for i, section in enumerate(sections):
 
 
 
 
115
  chat = openai.ChatCompletion.create(
116
+ model = "gpt-3.5-turbo",
117
+ messages=[{
118
+ "role": "user",
119
+ "content": "\n".join([prompt, section, '```'])
120
+ },]
121
+ )
122
+ print(f"{i} out of {len(sections)} complete. Estimated time remaining ~{len(sections) - i} mins")
123
+
 
124
  reply.append(chat.choices[0].message.content)
125
 
126
+ translated = split_markdown_sections('\n\n'.join(reply))
127
+ print(translated[1::3], anchors)
128
+ translated[1::3] = [
129
+ f"{korean_title} {anchors[i]}"
130
+ for i, korean_title in enumerate(translated[1::3])
131
+ ]
132
+ translated = ''.join([
133
+ ''.join(translated[i*3:i*3+3])
134
+ for i in range(len(translated) // 3)
135
+ ]).split('\n\n')
136
+ translated_doc = scaffold.safe_substitute({
137
+ f"hf_i18n_placeholder{i}": text
138
+ for i, text in enumerate(translated)
139
+ })
140
+ return translated_doc
141
 
142
+ demo = gr.Blocks()
 
 
 
143
 
144
  outputs = gr.outputs.Textbox(label="Translation")
145
+ with demo:
146
+ gr.Markdown(
147
+ "# HuggingFace i18n \n"
148
+ "## made easy with this demo."
149
+ )
150
+ with gr.Row():
151
+ language_input = gr.inputs.Textbox(
152
+ default="Korean",
153
+ label=" / ".join([
154
+ "Target language", "langue cible",
155
+ "目标语", "Idioma Objetivo",
156
+ "도착어", "língua alvo"
157
+ ])
158
+ )
159
+ filepath_input = gr.inputs.Textbox(
160
+ default="tasks/masked_language_modeling.md",
161
+ label="File path of transformers document"
162
+ )
163
+ with gr.Tabs():
164
+ with gr.TabItem("Web UI"):
165
+ prompt_button = gr.Button("Show Full Prompt", variant="primary")
166
+ # TODO: add with_prompt_checkbox so people can freely use other services such as DeepL or Papago.
167
+ gr.Markdown("1. Copy with the button right-hand side and paste into [chat.openai.com](https://chat.openai.com).")
168
+ prompt_output = gr.Textbox(label="Full Prompt", lines=3, show_copy_button=True)
169
+ # TODO: add check for segments, indicating whether user should add or remove new lines from their input. (gr.Row)
170
+ gr.Markdown("2. After getting the complete translation, remove randomly inserted newlines on your favorite text editor and paste the result below.")
171
+ ui_translated_input = gr.inputs.Textbox(label="Cleaned ChatGPT initial translation")
172
+ fill_button = gr.Button("Fill in scaffold", variant="primary")
173
+ with gr.TabItem("API (Not Implemented)"):
174
+ with gr.Row():
175
+ api_key_input = gr.inputs.Textbox(label="Your OpenAI API Key")
176
+ api_call_button = gr.Button("Translate (Call API)", variant="primary")
177
+ with gr.Row():
178
+ content_output = gr.Textbox(label="Original content", show_copy_button=True)
179
+ final_output = gr.Textbox(label="Draft for review", show_copy_button=True)
180
 
181
+ prompt_button.click(get_full_prompt, inputs=[language_input, filepath_input], outputs=prompt_output)
182
+ fill_button.click(fill_scaffold, inputs=[filepath_input, ui_translated_input], outputs=[content_output, final_output])
183
+ api_call_button.click(translate_openai, inputs=[language_input, filepath_input, api_key_input], outputs=[content_output, final_output])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
 
185
+ demo.launch()