File size: 9,284 Bytes
eae3e45
 
3738fa1
eae3e45
 
3738fa1
 
eae3e45
 
f7aa46d
eae3e45
a712f08
d352fac
4c5887b
3738fa1
 
 
 
 
 
ff0d9cb
 
202bff1
6d75696
202bff1
eae3e45
202bff1
6461706
 
eae3e45
 
 
 
 
 
 
 
 
6461706
eae3e45
 
 
 
 
 
6461706
82ae94e
6461706
ce7ef36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6461706
 
202bff1
eae3e45
 
202bff1
eae3e45
 
6461706
eae3e45
202bff1
eae3e45
202bff1
6461706
 
 
eae3e45
 
 
202bff1
eae3e45
202bff1
 
eae3e45
 
202bff1
 
eae3e45
 
 
 
 
 
 
 
6461706
eae3e45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09943a8
eae3e45
 
 
 
a712f08
 
eae3e45
 
 
 
 
 
 
 
 
ce7ef36
eae3e45
 
 
 
4c5887b
 
1216b61
 
9237dce
4c5887b
 
 
 
 
1216b61
4c5887b
 
23e6e61
 
98f200a
 
e0f694b
23e6e61
f7aa46d
23e6e61
f7aa46d
e0f694b
ff0d9cb
 
 
 
 
 
6fff5d4
dc5a2cc
6a8f59b
 
 
 
 
3e1d8de
 
 
 
 
ff0d9cb
eae3e45
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
import gradio as gr
import pandas as pd
import itertools
import tempfile
import os
import ast 
import requests
import re
from chatgpt_api import get_chatgpt_response
from voice_create import text_to_speech
from select_question import create_choice_question
from manuscript_conversion import manuscript_conversion
from category import check
from kousei import kousei2

import pandas as pd
import tempfile
import os
import re

from convert_chukan_fmt_1 import convert_chukan_fmt_1

def kousei(csv_file, input_text):
    prompt_text = input_text + "指摘は、全ての問題において問題がない場合も含めて、必ず全問題、[id]に続けて結果を書くフォーマットで返してください。[id]の後は改行しないで。[id]はリクエストと完全一致の形式で。(必ず[問題ID]が5つ表示されるはずです)指摘方法は、問題ない場合は「問題なし」、指摘がある場合は「問題あり」\n「問題あり」の場合、問題のある箇所を具体的に指摘してください。\n#リスト"
    
    # CSVファイルを読み込む
    df = pd.read_csv(csv_file)
    # 'id'列のデータ型を文字列に変換
    df['id'] = df['id'].astype(str)
    # DataFrameを5行ごとに処理するためのグループ化
    df['group_id'] = df.index // 5
    grouped = df.groupby('group_id')

    # 各グループに対してフォーマットされたプロンプトを作成
    def create_prompt(group, base_prompt):
        prompt = base_prompt
        for _, row in group.iterrows():
            prompt += f"\n[{row['id']}]\n{row['原稿']}"
            print(prompt)
        return prompt
    
    # 各グループごとのプロンプトを生成
    prompts = grouped.apply(lambda g: create_prompt(g, prompt_text))
    prompts = prompts.reset_index(name='prompt_after')
    
    # 各プロンプトをAPIに送信(この部分は実装に応じて修正が必要です)
    prompts['response'] = prompts['prompt_after'].apply(get_chatgpt_response)
    print(prompts['response'])

    # 各グループに対してフォーマットされたプロンプトを作成
    def create_prompt(group, base_prompt):
        prompt = base_prompt
        for _, row in group.iterrows():
            prompt += f"\n[{row['id']}]\n{row['原稿']}"
            print(prompt)
        return prompt
    
    # 各グループごとのプロンプトを生成
    prompts = grouped.apply(lambda g: create_prompt(g, prompt_text))
    prompts = prompts.reset_index(name='prompt_after')
    
    # 各プロンプトをAPIに送信(この部分は実装に応じて修正が必要です)
    prompts['response'] = prompts['prompt_after'].apply(get_chatgpt_response)
    print(prompts['response'])
    
    

    # 応答を分割して元のDataFrameにマッピングする関数
    def split_responses(grouped_df):
        rows = []
        for _, row in grouped_df.iterrows():
            response = row['response']
            split_response = re.split(r'\[([^\]]+)\]\s*', response)
            ids_texts = list(zip(split_response[1::2], split_response[2::2]))

            for id_text in ids_texts:
                problem_id, correction_result = id_text
                # フィルタリングされたDataFrameを安全に取得
                filtered_df = df[df['id'] == problem_id]
                original_content = filtered_df['原稿'].iloc[0] if not filtered_df.empty else "原稿が見つかりません"
                rows.append({
                    'id': problem_id,
                    'contents': original_content,
                    '校正結果': correction_result.strip()
                })

        return pd.DataFrame(rows)
    
    final_results = split_responses(prompts)
    
    # ファイル出力
    with tempfile.NamedTemporaryFile(delete=False, suffix='.csv') as tmp:
        final_results.to_csv(tmp.name, index=False, encoding='cp932', errors='ignore')
        output_path = tmp.name
    
    # ファイル名を変更
    new_path = os.path.join(os.path.dirname(output_path), "output.csv")
    os.rename(output_path, new_path)
    return new_path
    
title = "英語生成ツール"

with gr.Blocks(theme=gr.themes.Soft()) as demo:
    gr.Markdown(
        f"""
         # {title}
        """
    )
    with gr.Tab("問題生成(選択肢)"):
        with gr.Column():
            gr.Markdown("""
        ## 利用手順
        1. こちらの[マスタ](https://drive.google.com/uc?export=download&id=1VyDBtVrnDUlddmITiXg7ybqyB0CTCPeu)を手元に置く
        2. シート「input」に、生成したい問題パターンを書いてください(赤字の要素は固定。選択肢は可変。適宜行追加OK)
        3. 完成したら、「ファイル>名前を付けて保存」から「CSV UTF-8(コンマ区切り)(*.csv)」形式で保存
        4. 3のCSVを本サイトにアップロード
        """)

            with gr.Row():
                inputs=gr.File(label="CSVファイルをアップロード")
                outputs=gr.File(label="ダウンロード", file_count="singular")
            gr.Button("問題生成").click(
                create_choice_question,
                inputs=[inputs],
                outputs=[outputs]
            )
    with gr.Tab("原稿変換"):
        with gr.Column():
            with gr.Row():
                inputs=gr.File(label="CSVファイルをアップロード")
                outputs=gr.File(label="ダウンロード", file_count="singular")
            gr.Button("変換").click(
                manuscript_conversion,
                inputs=[inputs],
                outputs=[outputs]
            )
    with gr.Tab("校正"):
        with gr.Column():
            input_text_kousei = gr.Textbox(label="校正観点を入力してください。",value="英単語習得を目的として、以下2種類の問題を用意しています。\n1.英語の正しい日本語訳を選択する4択問題\n2.日本語の正しい英語訳を選択する4択問題\n「#リスト」の誤答選択肢の中に、正解選択肢の別解になってしまっているもの、または別解とは言えないが紛らわしすぎるものがないか、探して指摘してください。")
            with gr.Row():
                inputs=gr.File(label="CSVファイルをアップロード")
                outputs=gr.File(label="ダウンロード", file_count="singular")
            gr.Button("校正スタート").click(
                kousei,
                inputs=[inputs,input_text_kousei],
                outputs=[outputs]
            )
    with gr.Tab("校正2"):
        with gr.Column():
            radio_options = ["英語", "日本語"]
            radio_button = gr.Radio(choices=radio_options, label="選択してください",value="英語")
            input_text_kousei = gr.Textbox(label="校正観点を入力してください。",value="If there are any typographical errors, omissions, missing or extra spaces and periods, or grammatical mistakes in the English text, please point them out.")
            with gr.Row():
                inputs=gr.File(label="CSVファイルをアップロード")
                outputs=gr.File(label="ダウンロード", file_count="singular")
            gr.Button("校正スタート").click(
                kousei2,
                inputs=[inputs,input_text_kousei,radio_button],
                outputs=[outputs]
            )
    with gr.Tab("音声生成"):
         with gr.Column():
             # GradioのUIコンポーネントを定義
             radio_options = ["ブレイクタイム有", "ブレイクタイム無"]
             radio_button = gr.Radio(choices=radio_options, label="選択してください",value="ブレイクタイム有")
             with gr.Row():
                 file_input = gr.File(label="CSVファイルをアップロード")
                 submit_button = gr.Button("音声ファイルを生成")
             file_output = gr.File(label="ダウンロード")
             submit_button.click(fn=text_to_speech, inputs=[file_input,radio_button], outputs=[file_output])
    with gr.Tab("中間マスタ生成(意味理解)"):
        with gr.Column():
            with gr.Row():
                file_input = gr.File(label="CSVアップロード")
                submit_button = gr.Button("ファイルコンバート")
            file_output = gr.File(label="ファイルをダウンロード")
            submit_button.click(fn=convert_chukan_fmt_1, inputs=[file_input], outputs=[file_output])
    with gr.Tab("カテゴリ分類"):
        with gr.Column():
            input_text_kousei = gr.Textbox(label="分類観点を入力してください。",value="xxxxxxxに関する内容の場合は「該当あり」と書いてください。")
            with gr.Row():
                inputs=gr.File(label="CSVファイルをアップロード")
                outputs=gr.File(label="ダウンロード", file_count="singular")
            gr.Button("分類スタート").click(
                check,
                inputs=[inputs,input_text_kousei],
                outputs=[outputs]
            )
        
demo.launch(share=True)