import os import gradio as gr from openai import OpenAI import json import tempfile is_env_local = os.getenv("IS_ENV_LOCAL", "false") == "true" print(f"is_env_local: {is_env_local}") # KEY CONFIG if is_env_local: with open("local_config.json") as f: config = json.load(f) IS_ENV_PROD = "False" OPEN_AI_KEY = config["OPEN_AI_KEY"] else: OPEN_AI_KEY = os.getenv("OPEN_AI_KEY") OPEN_AI_CLIENT = OpenAI(api_key=OPEN_AI_KEY) def generate_topics(model, max_tokens, sys_content, scenario, eng_level, user_generate_topics_prompt): """ 根据系统提示和用户输入的情境及主题,调用OpenAI API生成相关的主题句。 """ user_content = f""" scenario is {scenario} english level is {eng_level} {user_generate_topics_prompt} """ messages = [ {"role": "system", "content": sys_content}, {"role": "user", "content": user_content} ] request_payload = { "model": model, "messages": messages, "max_tokens": max_tokens, "response_format": { "type": "json_object" } } response = OPEN_AI_CLIENT.chat.completions.create(**request_payload) content = response.choices[0].message.content topics = json.loads(content)["topics"] topics_text = json.dumps(topics) gr_update = gr.update(visible=False, value=topics_text) return gr_update def update_topic_input(topic): return topic def generate_points(model, max_tokens, sys_content, scenario, eng_level, topic, user_generate_points_prompt): """ 根据系统提示和用户输入的情境、主题,调用OpenAI API生成相关的主题句。 """ user_content = f""" scenario is {scenario} english level is {eng_level} topic is {topic} {user_generate_points_prompt} """ messages = [ {"role": "system", "content": sys_content}, {"role": "user", "content": user_content} ] request_payload = { "model": model, "messages": messages, "max_tokens": max_tokens, } response = OPEN_AI_CLIENT.chat.completions.create(**request_payload) content = response.choices[0].message.content points = json.loads(content)["points"] points_text = json.dumps(points) gr_update = gr.update(visible=False, value=points_text) return gr_update def update_points_input(points): return points def generate_topic_sentences(model, max_tokens, sys_content, scenario, eng_level, topic, points, user_generate_topic_sentences_prompt): """ 根据系统提示和用户输入的情境及要点,调用OpenAI API生成相关的主题句及其合理性解释。 """ user_content = f""" scenario is {scenario} english level is {eng_level} topic is {topic} points is {points} {user_generate_topic_sentences_prompt} """ messages = [ {"role": "system", "content": sys_content}, {"role": "user", "content": user_content} ] response_format = { "type": "json_object" } request_payload = { "model": model, "messages": messages, "max_tokens": max_tokens, "response_format": response_format } response = OPEN_AI_CLIENT.chat.completions.create(**request_payload) response_content = json.loads(response.choices[0].message.content) json_content = response_content["results"] topic_sentences_text = json.dumps(json_content, ensure_ascii=False) gr_update = gr.update(visible=False, value=topic_sentences_text) return gr_update def update_topic_sentence_input(topic_sentences_radio, topic_sentence_output): selected_topic_sentence = topic_sentences_radio topic_sentence_output = json.loads(topic_sentence_output) topic_sentence_input = "" for ts in topic_sentence_output: if ts["topic-sentence"] == selected_topic_sentence: appropriate = "O 適合" if ts["appropriate"] == "Y" else "X 不適合" border_color = "green" if ts["appropriate"] == "Y" else "red" background_color = "#e0ffe0" if ts["appropriate"] == "Y" else "#ffe0e0" suggestion_html = f"""

你選了主題句:{selected_topic_sentence}

是否適當:{appropriate}

原因:{ts['reason']}

""" topic_sentence_input = ts["topic-sentence"] if ts["appropriate"] == "Y" else "" break return topic_sentence_input, suggestion_html def generate_supporting_sentences(model, max_tokens, sys_content, scenario, eng_level, topic, points, topic_sentence, user_generate_supporting_sentences_prompt): """ 根据系统提示和用户输入的情境、主题、要点、主题句,调用OpenAI API生成相关的支持句。 """ user_content = f""" scenario is {scenario} english level is {eng_level} topic is {topic} points is {points} topic sentence is {topic_sentence} {user_generate_supporting_sentences_prompt} """ messages = [ {"role": "system", "content": sys_content}, {"role": "user", "content": user_content} ] request_payload = { "model": model, "messages": messages, "max_tokens": max_tokens, } response = OPEN_AI_CLIENT.chat.completions.create(**request_payload) content = response.choices[0].message.content.strip() return content def generate_conclusion_sentences(model, max_tokens, sys_content, scenario, eng_level, topic, points, topic_sentence, user_generate_conclusion_sentence_prompt): """ 根据系统提示和用户输入的情境、主题、要点、主题句,调用OpenAI API生成相关的结论句。 """ user_content = f""" scenario is {scenario} english level is {eng_level} topic is {topic} points is {points} topic sentence is {topic_sentence} {user_generate_conclusion_sentence_prompt} """ messages = [ {"role": "system", "content": sys_content}, {"role": "user", "content": user_content} ] request_payload = { "model": model, "messages": messages, "max_tokens": max_tokens, } response = OPEN_AI_CLIENT.chat.completions.create(**request_payload) content = response.choices[0].message.content.strip() return content def generate_paragraph(topic_sentence, supporting_sentences, conclusion_sentence): """ 根据用户输入的主题句、支持句、结论句,生成完整的段落。 """ paragraph = f"{topic_sentence}\n{supporting_sentences}\n{conclusion_sentence}" return paragraph def generate_paragraph_evaluate(paragraph, user_generate_paragraph_evaluate_prompt): """ 根据用户输入的段落,调用OpenAI API生成相关的段落分析。 """ user_content = f""" paragraph is {paragraph} {user_generate_paragraph_evaluate_prompt} """ messages = [ {"role": "system", "content": paragraph}, {"role": "user", "content": user_content} ] response_format = { "type": "json_object" } request_payload = { "model": "gpt-3.5-turbo", "messages": messages, "max_tokens": 500, "response_format": response_format } response = OPEN_AI_CLIENT.chat.completions.create(**request_payload) content = response.choices[0].message.content return content def generate_correct_grammatical_spelling_errors(eng_level, paragraph, user_correct_grammatical_spelling_errors_prompt): """ 根据用户输入的段落,调用OpenAI API生成相关的文法和拼字错误修正。 """ user_content = f""" level is {eng_level} paragraph is {paragraph} {user_correct_grammatical_spelling_errors_prompt} """ messages = [ {"role": "system", "content": paragraph}, {"role": "user", "content": user_content} ] response_format = { "type": "json_object" } request_payload = { "model": "gpt-3.5-turbo", "messages": messages, "max_tokens": 500, "response_format": response_format } response = OPEN_AI_CLIENT.chat.completions.create(**request_payload) content = response.choices[0].message.content return content def generate_refine_paragraph(eng_level, paragraph, user_refine_paragraph_prompt): """ 根据用户输入的段落,调用OpenAI API生成相关的段落改善建议。 """ user_content = f""" eng_level is {eng_level} paragraph is {paragraph} {user_refine_paragraph_prompt} """ messages = [ {"role": "system", "content": paragraph}, {"role": "user", "content": user_content} ] response_format = { "type": "json_object" } request_payload = { "model": "gpt-3.5-turbo", "messages": messages, "max_tokens": 500, "response_format": response_format } response = OPEN_AI_CLIENT.chat.completions.create(**request_payload) content = response.choices[0].message.content return content def paragraph_save_and_tts(paragraph_text): """ Saves the paragraph text and generates an audio file using OpenAI's TTS. """ try: # Call OpenAI's TTS API to generate speech from text response = OPEN_AI_CLIENT.audio.speech.create( model="tts-1", voice="alloy", input=paragraph_text, ) with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as temp_file: temp_file.write(response.content) # Get the file path of the temp file audio_path = temp_file.name # Return the path to the audio file along with the text return paragraph_text, audio_path except Exception as e: print(f"An error occurred while generating TTS: {e}") # Handle the error appropriately (e.g., return an error message or a default audio path) return paragraph_text, None with gr.Blocks(theme=gr.themes.Soft(primary_hue=gr.themes.colors.blue, secondary_hue=gr.themes.colors.orange)) as demo: # basic inputs 主題與情境 with gr.Row(): with gr.Column(): model = gr.Radio(["gpt-4o", "gpt-3.5-turbo"], label="Model", value="gpt-4o", visible=False) max_tokens = gr.Slider(minimum=50, maximum=4000, value=4000, label="Max Tokens", visible=False) sys_content_input = gr.Textbox(label="System Prompt", value="You are an English teacher who is practicing with me to improve my English writing skill.", visible=False) with gr.Row(): eng_level_input = gr.Radio(["beginner", "intermediate", "advanced"], label="English Level", value="beginner") with gr.Row(): gr.Markdown("# Step 1. 你今天想練習寫什麼呢?") with gr.Row(): gr.Markdown("""## 寫作的主題與讀者、寫作的目的、文章的風格、長度、範圍、以及作者的專業知識等都有關係。因為不容易找主題,所以利用兩階段方式來找主題。特為較無英文寫作經驗的 基礎級使用者 提供多種大範圍情境,待篩選情境後,下一步再來決定明確的主題。""") with gr.Row(): scenario_values = [ "Health", "Thanksgiving", "Halloween", "moon festival in Taiwan", "School and Learning", "Travel and Places", "Family and Friends", "Hobbies and Leisure Activities", "Health and Exercise", "Personal Experiences", "My Future Goals", "School Life", "Pets", "A Problem and Solution", "Holidays and Celebrations", "My Favorite Cartoon/Anime" ] scenario_input = gr.Dropdown(label="先選擇一個大範圍的情境:", choices=scenario_values, value="Health") # Step 2. 確定段落主題 with gr.Row(): with gr.Column(): with gr.Row(): gr.Markdown("# Step 2. 確定段落主題") with gr.Row(): with gr.Column(): gr.Markdown("""## 主題是整個段落要探討、闡述的主要議題。確定主題對於段落的架構、內容非常重要,幫助讀者預期段落的內容,增加閱讀的速度及理解度。寫作過程中,掌握主題可以幫助作者有效傳達自己的想法和觀點,幫助讀者更容易理解。""") with gr.Column(): with gr.Accordion("參考指引:情境與主題如何搭配呢?", open=False): gr.Markdown(""" 例如,情境是 `School & Learning` ,你可以依照自己的興趣、背景及經驗,決定合適的主題,像是:`My First Day at School` 或 `The Role of Internet in Learning` 例如,情境是 `Climate Change`,相關主題可能是 `Global Warming` 或 `Extreme Weather Events` """) with gr.Row(visible=False) as topic_params: default_generate_topics_prompt = """ Give me 10 topics relevant to Scenario, for a paragraph. Just the topics, no explanation, use simple English language. Make sure the vocabulary you use is at english level. output use JSON EXAMPLE: "topics":["topic1", "topic2", "topic3", "topic4", "topic5", "topic6", "topic7", "topic8", "topic9", "topic10"] """ user_generate_topics_prompt = gr.Textbox(label="Topics Prompt", value=default_generate_topics_prompt, visible=False) with gr.Row(): with gr.Column(): topic_input = gr.Textbox(label="選擇合適的主題:", interactive=False) with gr.Column(): generate_topics_button = gr.Button("使用 🪄 JUTOR 產生 10 個段落主題,再挑選一個來練習吧!", variant="primary") topic_output = gr.Textbox(label="AI Generated Topic 主題", visible=True, value=[]) @gr.render(inputs=topic_output) def render_topics(topics): topics_list = json.loads(topics) topic_radio = gr.Radio(topics_list, label="Topics", elem_id="topic_button") topic_radio.select( fn=update_topic_input, inputs=[topic_radio], outputs=[topic_input] ) return topic_radio # Step 3. 寫出段落要點 with gr.Row(): with gr.Column(): with gr.Row() as points_params: default_generate_points_prompt = """ Please provide main points to develop in a paragraph about topic in the context of scenario, use simple English language and make sure the vocabulary you use is at eng_level. No more explanation either no developing these points into a simple paragraph. Output use JSON format EXAMPLE: "points":["point1", "point2", "point3"] """ user_generate_points_prompt = gr.Textbox(label="Points Prompt", value=default_generate_points_prompt, visible=False) with gr.Row() as points_html: gr.Markdown("# Step 3. 寫出段落要點") with gr.Row(): gr.Markdown("## 根據情境、主題,可以視主題不同,試著寫出 1-3 個要點。段落要點務必選擇比較相關的,才好寫入一個段落。不相關的要點會讓段落缺乏連貫一致性。") with gr.Row(): gr.Markdown("### `基礎級使用者` 先從 1 個要點開始練習,比較好掌握;等熟悉之後在 `實力級`,就可選擇 2-3 個要點來發揮。") with gr.Row(): with gr.Column(): points_input = gr.Textbox(label="#1 要點/關鍵字") with gr.Column(): generate_points_button = gr.Button("找尋靈感?使用 🪄 JUTOR 產生要點/關鍵字", variant="primary") points_output = gr.Textbox(label="AI Generated Points 要點", visible=True, value=[]) @gr.render(inputs=points_output) def render_points(points): points_list = json.loads(points) points_radio = gr.Radio(points_list, label="Points", elem_id="point_button") points_radio.select( fn=update_points_input, inputs=[points_radio], outputs=[points_input] ) return points_radio # Step 4. 選定主題句 with gr.Row(): with gr.Column(): with gr.Row() as topic_sentences_params: default_generate_topic_sentences_prompt = """ Please provide one appropriate topic sentence that aptly introduces the subject for the given scenario and topic. Additionally, provide two topic sentences that, while related to the topic, would be considered inappropriate or less effective for the specified context. Those sentences must include the three main points:". Use English language and each sentence should not be too long. For each sentence, explain the reason in Traditional Chinese, Taiwan, 繁體中文 zh-TW. Make sure the vocabulary you use is at level. Output use JSON format EXAMPLE: "results": [ {{ "topic-sentence": "#","appropriate": "Y/N", "reason": "#中文解釋" }} , {{ "topic-sentence": "#","appropriate": "Y/N", "reason": "#中文解釋" }}, {{ "topic-sentence": "#","appropriate": "Y/N", "reason": "#中文解釋" }} ] """ user_generate_topic_sentences_prompt = gr.Textbox(label="Topic Sentences Prompt", value=default_generate_topic_sentences_prompt, visible=False) with gr.Row() as topic_sentences_html: gr.Markdown("# Step 4. 選定主題句") with gr.Row(): with gr.Column(): gr.Markdown("## 主題句(Topic Sentence)是一個段落中最重要的句子,它介紹主題並含括該段落的所有要點,引起讀者的興趣。就像藍圖一樣,指出客廳、廚房、臥室等位置。") gr.Markdown("## 主題句通常位於段落的開頭,幫助讀者迅速理解段落的內容。如果沒有主題句,段落的架構及內容的一致性及連貫性就會受影響。") gr.Markdown("## 主題句的範圍,應能適當含括你剛才決定的各個要點,範圍不要太大,以致無法在一個段落清楚説明,也不能太小,無法含括段落的所有要點。") with gr.Column(): with gr.Accordion("參考指引:合適的主題句?", open=False): gr.Markdown("""舉例,情境是 `School & Learning`,段落主題是 `Time Management`,那麼 `Balancing school work and leisure time is a crucial aspect of effective time management` 就是合適的主題句,因為它清楚點出該段落將説明有效運用時間來讓課業及娛樂取得平衡。""") with gr.Row(): with gr.Column(): topic_sentence_input = gr.Textbox(label="Topic Sentences") with gr.Column(): generate_topic_sentences_button = gr.Button("生成並在下面 3 個 JUTOR 產生的主題句中,選出一個最合適的", variant="primary") topic_sentence_output = gr.Textbox(label="AI Generated Topic Sentences 主題句") @gr.render(inputs=topic_sentence_output) def render_topic_sentences(topic_sentences): # Parsing the JSON string to a list topic_sentences_list = json.loads(topic_sentences) # Extracting only the topic sentences for the radio button options radio_options = [ts["topic-sentence"] for ts in topic_sentences_list] # Creating the radio button element topic_sentences_radio = gr.Radio(radio_options, label="Topic Sentences", elem_id="topic_sentence_button") topic_sentences_suggestions = gr.HTML() # Setting up the action when a radio button is selected topic_sentences_radio.select( fn=update_topic_sentence_input, inputs=[topic_sentences_radio, topic_sentence_output], outputs= [topic_sentence_input, topic_sentences_suggestions] ) return topic_sentences_radio with gr.Row(): with gr.Column(): with gr.Row() as supporting_sentences_params: default_generate_supporting_sentences_prompt = """ I'm aiming to improve my writing. I have a topic sentence as topic_sentence_input. Please assist me by "Developing supporting detials" based on the keyword: points to write three sentences as an example. - Make sure any revised vocabulary aligns with the eng_level. - Guidelines for Length and Complexity: Please keep the example concise and straightforward, avoiding overly technical language. Total word-count is around 50. no more explanation either no more extra non-relation sentences. """ user_generate_supporting_sentences_prompt = gr.Textbox(label="Supporting Sentences Prompt", value=default_generate_supporting_sentences_prompt, visible=False) with gr.Row() as supporting_sentences_html: gr.Markdown("# Step 5.寫出完整段落") with gr.Row(): gr.Markdown("## 請根據主題句,練習寫出 「支持句」及「結論句」來完成一個完整的段落。") with gr.Row(): with gr.Column(): gr.Markdown("### 支持句:以支持句來解釋要點,必要時舉例説明,來支持主題句。這些句子應該按照邏輯順序來組織,例如時間順序、空間順序、重要性順序、因果關係等。並使用轉折詞來引導讀者從一個 idea 到下一個 idea,讓讀者讀起來很順暢,不需反覆閱讀。") with gr.Column(): with gr.Accordion("參考指引:撰寫支持句的方法?", open=False): gr.Markdown(""" - Explanation 解釋説明:說明居住城市的優點,例如住在城市可享受便利的交通。 - Fact 陳述事實:説明運動可以增強心肺功能和肌肉力量,對於身體健康有正面影響。 - Cause and Effect 原因結果:解釋為何必須家事分工,例如家事分工更容易維護家庭環境的整齊清潔。 - Compare and Contrast 比較與對比:將主題與其他相關事物進行比較。例如比較傳統教學與線上學習。 - Incident 事件:利用事件來做説明。例如誤用表情符號造成困擾的事件,或葡式蛋塔風行的跟瘋事件。 - Evidence 提供證據:引用相關數據、研究或事實來佐證。例如全球互聯網用戶數已經突破了 50 億人,佔全球總人口近 65%。 - Example 舉例:舉自家為例,説明如何將家事的責任分配給每個家庭成員。 """) with gr.Accordion("參考指引:針對要點的支持句,要寫幾句呢?", open=False): gr.Markdown(""" - 一個要點,寫 3-6 句 - 兩個要點,每個要點寫 2-3 句 - 三個要點,每個要點寫 1-2 句 """) with gr.Row(): with gr.Column(): gr.Markdown("### 寫出關於 focus 的支持句") supporting_sentences_input = gr.Textbox(label="Supporting Sentences") with gr.Column(): generate_supporting_sentences_button = gr.Button("AI Generate Supporting Sentences") supporting_sentences_output = gr.Textbox(label="AI Generated Supporting Sentences 支持句", show_copy_button=True) gr.Markdown("## 6. Conclusion sentence 結論句") default_generate_conclusion_sentence_prompt = """ I'm aiming to improve my writing. By the topic sentence, please assist me by "Developing conclusion sentences" based on keywords of points to finish a paragrpah as an example. - Make sure any revised vocabulary aligns with the correctly eng_level. - Guidelines for Length and Complexity: Please keep the example concise and straightforward, avoiding overly technical language. Total word-count is around 20. """ user_generate_conclusion_sentence_prompt = gr.Textbox(label="Conclusion Sentence Prompt", value=default_generate_conclusion_sentence_prompt, visible=False) generate_conclusion_sentence_button = gr.Button("AI Generate Conclusion Sentence") conclusion_sentence_output = gr.Textbox(label="AI Generated Conclusion Sentence 結論句", show_copy_button=True) conclusion_sentence_input = gr.Textbox(label="Conclusion Sentence") gr.Markdown("## 7. Paragraph Integration and Revision 段落確認與修訂") generate_paragraph_button = gr.Button("Generate Paragraph") paragraph_output = gr.Textbox(label="Generated Paragraph 完整段落", show_copy_button=True) paragraph_input = gr.Textbox(label="Paragraph") gr.Markdown("## 8. Evaluate 分析") default_user_generate_paragraph_evaluate_prompt = """ Based on the final paragraph provided, evaluate the writing in terms of content, organization, grammar, and vocabulary. Provide feedback in simple and supportive language. -- 根據上述的文章,以「內容(content)」層面評分。 - 評分等級有三級:beginner, intermediate, advanced. - 以繁體中文解釋 評分結果以 JSON 格式輸出: content: { "content_level": "#beginner/intermediate/advanced", "content_explanation": "#中文解釋" } -- 根據上述的文章,以「組織(organization)」層面評分。 - 評分等級有三級:beginner, intermediate, advanced. - 以繁體中文解釋 評分結果以 JSON 格式輸出: organization: { "organization_level": "#beginner/intermediate/advanced", "organization_explanation": "#中文解釋" } -- 根據上述的文章,以「文法和用法(Grammar and usage)」層面評分。 - 評分等級有三級:beginner, intermediate, advanced. - 以繁體中文解釋 評分結果以 JSON 格式輸出: grammar_and_usage: { "GrammarAndUsage_level": "#beginner/intermediate/advanced", "GrammarAndUsage_explanation": "#中文解釋" } -- 根據上述的文章,以「詞彙(Vocabulary )」層面評分。 - 評分等級有三級:beginner, intermediate, advanced. - 以繁體中文解釋 評分結果以 JSON 格式輸出: vocabulary: { "Vocabulary_level": "#beginner/intermediate/advanced", "Vocabulary_explanation": "#中文解釋" } -- 根據上述的文章,以「連貫性和連接詞(Coherence and Cohesion)」層面評分。 - 評分等級有三級:beginner, intermediate, advanced. - 以繁體中文解釋 評分結果以 JSON 格式輸出: coherence_and_cohesion: { "CoherenceAndCohesion_level": "#beginner/intermediate/advanced", "CoherenceAndCohesion_explanation": "#中文解釋" } 將上述的輸出為 JSON: {{ “content“: {content’s dict}, “organization“: {organization dict}, “grammar_and_usage“: {grammar_and_usage dict}, “vocabulary“: {vocabulary dict}, “coherence_and_cohesion“: {coherence_and_cohesion dict} }} """ user_generate_paragraph_evaluate_prompt = gr.Textbox(label="Paragraph evaluate Prompt", value=default_user_generate_paragraph_evaluate_prompt, visible=False) generate_paragraph_evaluate_button = gr.Button("Save and Evaluate") paragraph_evaluate_output = gr.Textbox(label="Generated Paragraph evaluate 完整段落分析", show_copy_button=True) gr.Markdown("## 9. Correct Grammatical and Spelling Errors 修訂文法與拼字錯誤") default_user_correct_grammatical_spelling_errors_prompt = """ I'm aiming to improve my writing. Please assist me by "Correcting Grammatical and Spelling Errors" in the provided paragraph. For every correction you make, I'd like an "Explanation" to understand the reasoning behind it. - Paragraph for Correction: [paragraph split by punctuation mark] - The sentence to remain unchanged: [sentence_to_remain_unchanged] - When explaining, use Traditional Chinese (Taiwan, 繁體中文) for clarity. - But others(original, Correction, revised_paragraph) in English. - Make sure any revised vocabulary aligns with the eng_level. - Guidelines for Length and Complexity: Please keep explanations concise and straightforward, - Avoiding overly technical language. The response should strictly be in the below JSON format and nothing else: { "Corrections and Explanations": [ { "original": "# original_sentence1", "Correction": "#correction_1", "Explanation": "#explanation_1(in_traditional_chinese)" }, { "original": "# original_sentence2", "Correction": "#correction_2", "Explanation": "#explanation_2(in_traditional_chinese)" }, ... ], "Revised Paragraph": "#revised_paragraph" } """ user_correct_grammatical_spelling_errors_prompt = gr.Textbox(label="Correct Grammatical and Spelling Errors Prompt", value=default_user_correct_grammatical_spelling_errors_prompt, visible=False) generate_correct_grammatical_spelling_errors_button = gr.Button("Correct Grammatical and Spelling Errors") correct_grammatical_spelling_errors_output = gr.Textbox(label="Correct Grammatical and Spelling Errors 修訂文法與拼字錯誤") paragraph_correct_grammatical_spelling_errors_input = gr.Textbox(label="Paragraph") gr.Markdown("## 10. Refine Paragraph 段落改善建議") default_user_refine_paragraph_prompt = """ I need assistance with revising a paragraph. Please "Refine" the "Revised Version 1" and immediately "Provide Explanations" for each suggestion you made. - Revised Version 1 (for correction): paragraph_ai_modification(split by punctuation mark) - Do not modify the sentence: topicSentence" - Make sure any revised vocabulary aligns with the eng_level. - When explaining, use Traditional Chinese (Taiwan, 繁體中文) for clarity. - But others(Origin, Suggestion, revised_paragraph_v2) use English, that's very important. - Guidelines for Length and Complexity: Please keep explanations concise and straightforward, avoiding overly technical language. The response should strictly be in the below JSON format and nothing else: { "Suggestions and Explanations": [ { "Origin": "#original_text_1", "Suggestion": "#suggestion_1", "Explanation": "#explanation_1(in_traditional_chinese)" }, { "Origin": "#original_text_2", "Suggestion": "#suggestion_2", "Explanation": "#explanation_2(in_traditional_chinese)" }, ... ], "Revised Paragraph": "#revised_paragraph_v2" } """ user_refine_paragraph_prompt = gr.Textbox(label="Refine Paragraph Prompt", value=default_user_refine_paragraph_prompt, visible=False) generate_refine_paragraph_button = gr.Button("Refine Paragraph") refine_output = gr.Textbox(label="Refine Paragraph 段落改善建議", show_copy_button=True) paragraph_refine_input = gr.Textbox(label="Paragraph 段落改善", show_copy_button=True) gr.Markdown("## 11. Save and Share") paragraph_save_button = gr.Button("Save and Share") paragraph_save_output = gr.Textbox(label="Save and Share") audio_output = gr.Audio(label="Generated Speech", type="filepath") generate_topics_button.click( fn=generate_topics, inputs=[ model, max_tokens, sys_content_input, scenario_input, eng_level_input, user_generate_topics_prompt ], outputs=[topic_output] ) generate_points_button.click( fn=generate_points, inputs=[ model, max_tokens, sys_content_input, scenario_input, eng_level_input, topic_input, user_generate_points_prompt ], outputs=points_output ) generate_topic_sentences_button.click( fn=generate_topic_sentences, inputs=[ model, max_tokens, sys_content_input, scenario_input, eng_level_input, topic_input, points_input, user_generate_topic_sentences_prompt ], outputs=topic_sentence_output ) generate_supporting_sentences_button.click( fn=generate_supporting_sentences, inputs=[ model, max_tokens, sys_content_input, scenario_input, eng_level_input, topic_input, points_input, topic_sentence_input, user_generate_supporting_sentences_prompt ], outputs=supporting_sentences_output ) generate_conclusion_sentence_button.click( fn=generate_conclusion_sentences, inputs=[ model, max_tokens, sys_content_input, scenario_input, eng_level_input, topic_input, points_input, topic_sentence_input, user_generate_conclusion_sentence_prompt ], outputs=conclusion_sentence_output ) generate_paragraph_button.click( fn=generate_paragraph, inputs=[ topic_sentence_input, supporting_sentences_input, conclusion_sentence_input ], outputs=paragraph_output ) generate_paragraph_evaluate_button.click( fn=generate_paragraph_evaluate, inputs=[ paragraph_input, user_generate_paragraph_evaluate_prompt ], outputs=paragraph_evaluate_output ) generate_correct_grammatical_spelling_errors_button.click( fn=generate_correct_grammatical_spelling_errors, inputs=[ eng_level_input, paragraph_input, user_correct_grammatical_spelling_errors_prompt ], outputs=correct_grammatical_spelling_errors_output ) generate_refine_paragraph_button.click( fn=generate_refine_paragraph, inputs=[ eng_level_input, paragraph_correct_grammatical_spelling_errors_input, user_refine_paragraph_prompt ], outputs=refine_output ) paragraph_save_button.click( fn=paragraph_save_and_tts, inputs=[ paragraph_refine_input ], outputs=[ paragraph_save_output, audio_output ] ) demo.launch()