myasumoto commited on
Commit
941b664
1 Parent(s): 304d0e6

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +204 -0
app.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from openai import OpenAI
2
+ import os
3
+ import math
4
+ import gradio as gr
5
+ import csv
6
+ import glob
7
+ import re
8
+ from bs4 import BeautifulSoup
9
+
10
+ def calculate(skkey, folder_path, output_path, c0, threshold, t1, s1, s1m, t2, s2, reason1, s3, reason2, s4, c1, c2):
11
+ def CalculateCountScore(text):
12
+ cs = ()
13
+ text_length = len(text)
14
+ deviation = abs(text_length - threshold) / float(threshold) * 100
15
+
16
+ if c0 == True:
17
+ if threshold >= text_length:
18
+ sScore = s1 * (1 - (threshold - text_length) / float(threshold))
19
+ else:
20
+ sScore = min(s1 * (1 + (text_length - threshold) / float(threshold)), s1m)
21
+ return(text_length, round(sScore))
22
+ pass
23
+ else:
24
+ if deviation <= t1:
25
+ return (text_length, s1)
26
+ elif deviation <= t2:
27
+ return (text_length, s2)
28
+ else:
29
+ return (text_length,1)
30
+
31
+ def extract_text_from_html(html):
32
+ soup = BeautifulSoup(html, 'html.parser')
33
+ text = soup.get_text(separator=' ')
34
+ return text.strip()
35
+
36
+ #ChatGPTでの採点命令
37
+ def CheckReport(text):
38
+ inputTxt = '"""'+text+'"""'
39
+
40
+ res = client.chat.completions.create(model="gpt-3.5-turbo",
41
+ messages=[
42
+ {
43
+ "role":"system",
44
+ "content":criterion
45
+ },
46
+ {
47
+ "role":"user",
48
+ "content":inputTxt
49
+ },
50
+ ],
51
+ )
52
+ return res.choices[0].message.content
53
+
54
+ # 改行コードを取り除く
55
+ def removeTrashes(string_list):
56
+ # 各要素から改行コードを取り除いた新しいリストを作成
57
+ new_string_list = [string.replace('\n', '').replace('\r', '').replace('点、', ',').replace('点。', ',').replace('False、','False,').replace('True、','True,').replace('TRUE、','True,').replace('FALSE、','False,').replace("TRUE","True").replace("FALSE","False") for string in string_list]
58
+ return new_string_list
59
+
60
+ #箇条書きから必要なものをリストにする
61
+ def extract_elements_from_report(report):
62
+ lines = report.split("\n")
63
+ elements = []
64
+
65
+ for line in lines:
66
+ if line.startswith("点数1:"):
67
+ elements.append(float(line.split(":")[1].strip()))
68
+ elif line.startswith("理由1:"):
69
+ elements.append(line.split(":")[1].strip())
70
+ elif line.startswith("点数2:"):
71
+ elements.append(float(line.split(":")[1].strip()))
72
+ elif line.startswith("理由2:"):
73
+ elements.append(line.split(":")[1].strip())
74
+
75
+ return elements
76
+
77
+
78
+
79
+ # 文字数の点数と中身の点数を足す
80
+ def CalculateScore(output_data):
81
+ new_output_data = []
82
+ for data in output_data:
83
+ # 各行を`,`で分割してリストにする
84
+ items = data.split(',')
85
+ if len(items) >= 5:
86
+ # 3番目と4番目と6番目の数字を取得し、足して新しいデータを作成
87
+ term3 = int(items[2])
88
+ term4_str = ''.join(filter(str.isdigit, items[3])) # 数字以外のごみを取り除く
89
+ term4 = int(term4_str) if term4_str else 0
90
+ term6_str = ''.join(filter(str.isdigit, items[5]))
91
+ term6 = int(term6_str) if term6_str else 0
92
+
93
+ termSum = term3 + term4 + term6
94
+ new_data = ','.join(items[:1] + [str(termSum)] + items[1:])
95
+ new_output_data.append(new_data)
96
+ else:
97
+ new_output_data.append(data)
98
+ return new_output_data
99
+
100
+ #deploy時にはコメントアウト箇所を変更すること
101
+ #openai.api_key = skkey
102
+ client = OpenAI(
103
+ # This is the default and can be omitted
104
+ api_key=sk,
105
+ )
106
+
107
+ # ChatGPTの採点定義
108
+ #criterion = f"レポートの採点を({s3}+{s4})点満点で行う。厳密なCSVでint型の点数,bool型の判定,string型の点数の理由の順で3項のみ1行で出力。カンマとダブルクォーテーション以外の記号を使ってはいけない。点数に関しては{reason1}\+{s3}点そうでなければ加点なし、{reason2}\+{s4}点で、そうでなければ加点なし半角の数字のみで出力。'2点'のように'点'という全角文字を表示してはならない、必ず0,1,2といった半角数字のint型で出力する。判定はChatGPTで生成されたことが確実もしくは高確率の場合はTrue、そうでなけ��ばFalseをBoolean型として出力。理由はレポートが何故この点数となるのかを採点基準に基づいて100文字以内で簡潔にstring型で出力、'理由は・・・'とか'理由:'などの前置きは不要。すべての項目に関して指示された出力以外のものを絶対に出力してはならない。指定されたCSV形式にする。例として1,False,'ルールを変えるためには、問題に気づくことが大切だと自分の意見が述べられている。ChatGPTを使用した痕跡もない'"
109
+
110
+ criterion = f"あなたは寛大な採点者です。三重引用符で囲ったレポートを提示するので、以下の採点基準に則ってあなた自身の答えを何回も反芻し、じっくりと考えてから、甘めに評価してください。ゆえに点数は可能な限り0をつけるべきではない、少しでも評価できる点があれば部分点を与えてください。もしこれを守らず安易に0点にした場合あなたは罰せられます。以下に示すフォーマットで4行の箇条書きで出力し、それ以外のものを出力してはならない。もしそれ以外のものを出力したら罰せられます。点数1:採点基準1で採点した点数を数値でここに入力。理由1:採点基準1での採点結果の理由をここに入力。点数2:採点基準2で採点した数値をここに入力。理由2:採点基準2での採点結果の理由をここに入力。採点基準1は{reason1}。 採点基準2は{reason2}。点数1は0から{s3}の間で半角数字で入力。点数2は0から{s4}の間で半角数字で入力。"
111
+ if c1 and not c2:
112
+ criterion = f"あなたは寛大な採点者です。三重引用符で囲ったレポートを提示するので、以下の採点基準に則ってあなた自身の答えを何回も反芻し、じっくりと考えてから、甘めに評価してください。ゆえに点数は可能な限り0をつけるべきではない、少しでも評価できる点があれば部分点を与えてください。もしこれを守らず安易に0点にした場合あなたは罰せられます。以下に示すフォーマットで4行の箇条書きで出力し、それ以外のものを出力してはならない。もしそれ以外のものを出力したら罰せられます。点数1:採点基準1で採点した点数を数値でここに入力。理由1:採点基準1での採点結果の理由をここに入力。点数2:0と入力。理由2:”なし”と入力。採点基準1は{reason1}。点数1は0から{s3}の間で半角数字で入力。点数2は0と半角数字で入力。"
113
+ elif not c1 and c2:
114
+ criterion = f"あなたは寛大な採点者です。三重引用符で囲ったレポートを提示するので、以下の採点基準に則ってあなた自身の答えを何回も反芻し、じっくりと考えてから、甘めに評価してください。ゆえに点数は可能な限り0をつけるべきではない、少しでも評価できる点があれば部分点を与えてください。もしこれを守らず安易に0点にした場合あなたは罰せられます。以下に示すフォーマットで4行の箇条書きで出力し、それ以外のものを出力してはならない。もしそれ以外のものを出力したら罰せられます。点数1:0と入力。理由1:”なし”と入力。点数2:採点基準2で採点した点数を数値でここに入力。理由2:採点基準2での採点結果の理由をここに入力。採点基準2は{reason2}。点数2は0から{s4}の間で半角数字で入力。点数1は0と半角数字で入力。"
115
+
116
+
117
+ # 名前と学生証番号を抽出する正規表現パターン
118
+ pattern = r'([^_]+)_([^_]+)_.*\.html'
119
+
120
+ # 出力するためのリスト
121
+ output_data = []
122
+
123
+ # フォルダ内のHTMLファイルを取得
124
+ html_files = glob.glob(str(folder_path) + '/*.html')
125
+ print(len(html_files))
126
+
127
+ # 各HTMLファイルに対して処理を行い、CSVファイルに出力
128
+ for file_path in html_files:
129
+ with open(file_path, 'r', encoding='utf-8') as file:
130
+ html_content = file.read()
131
+ plain_text = extract_text_from_html(html_content)
132
+
133
+ #文字数をスコア付け
134
+ try:
135
+ CountLength, CountScore = CalculateCountScore(plain_text)
136
+ except:
137
+ print("Error:", CalculateCountScore(plain_text))
138
+
139
+ #レポート採点,Score,理由、ChatGPT有無のはず
140
+ while any([c1, c2]):
141
+ try:
142
+ outReport = ','.join(map(str, extract_elements_from_report(CheckReport(plain_text)))).replace("点","")
143
+ print(outReport)
144
+ break
145
+ except Exception as e: # エラーが発生した場合は以下の処理を実行する
146
+ print(f"エラーが発生しました?: {e}")
147
+ if not c1 and not c2:
148
+ outReport = "0,なし,0,なし"
149
+
150
+ #ReportScore, Reason, ChatGPT = outReport
151
+ # ファイル名から名前と学生証番号を抽出
152
+ file_name = os.path.basename(file_path)
153
+ match = re.search(pattern, file_name)
154
+ if match:
155
+ name = match.group(1)
156
+ student_id = match.group(2)
157
+ # CSVデータとして出力用リストに追加
158
+ output_data.append(f"{name}, {student_id},{CountLength}, {CountScore}, {outReport}, {plain_text}")
159
+ print("SID:",student_id)
160
+ print(f"{CountLength},{CountScore},{outReport}")
161
+
162
+ output_data = CalculateScore(removeTrashes(output_data))
163
+
164
+ # 結果をCSVファイルに出力
165
+ output_file = str(folder_path) + "\output.csv"
166
+ with open(output_file, 'w', newline='', encoding='utf-8-sig') as file:
167
+ for item in output_data:
168
+ file.write(item + "\n")
169
+
170
+ print('Output saved to', output_file)
171
+ return "Done"
172
+
173
+ with gr.Blocks() as demo:
174
+ with gr.Row():
175
+ skkey = gr.Textbox(label="ChatGPTのAPIキー")
176
+ folder_path = gr.Textbox(label="Input Folder Path", value=r"C:\Users\maya\Dropbox\東海大学\講義\シティズンシップ\test")
177
+ output_path = gr.Textbox(label="Output File Path", value = r"C:\Users\maya\Dropbox\東海大学\講義\シティズンシップ\test\output.csv")
178
+ with gr.Row():
179
+ with gr.Column(scale=1, min_width = 400):
180
+ c0 = gr.Checkbox(label="片方向割合加算");
181
+ threshold = gr.Slider(minimum = 0, maximum = 1000, value=400, label="推奨文字数")
182
+ with gr.Column(scale=1, min_width = 200):
183
+ t1 = gr.Slider(minimum=0, maximum = 100, value=10, label="満点の文字範囲(%)")
184
+ s1 = gr.Slider(minimum=1, maximum = 10, value = 2, label="満点の点数")
185
+ s1m = gr.Slider(minimum=1, maximum = 10, value = 5, label="点数上限")
186
+ with gr.Column(scale=1, min_width = 200):
187
+ t2 = gr.Slider(minimum=0, maximum = 100, value=50, label="許容の文字範囲(%)")
188
+ s2 = gr.Slider(minimum=1, maximum = 20, value = 1, label="許容文字数の際の点数")
189
+ with gr.Row():
190
+ with gr.Column(scale=1, min_width = 400):
191
+ c1 = gr.Checkbox(label="有効");
192
+ reason1 = gr.Textbox(label="採点基準1", value="社会運動について考察しているかどうか")
193
+ s3 = gr.Slider(minimum=0, maximum = 10, value = 1, label="採点基準1の点数")
194
+ with gr.Column(scale=1, min_width = 400):
195
+ c2 = gr.Checkbox(label="有効")
196
+ reason2 = gr.Textbox(label="採点基準2", value = "社会運動の日本での動向が複数の情報源を元に述べられているかどうか")
197
+ s4 = gr.Slider(minimum = 0, maximum = 10, value = 1, label="採点基準2の点数")
198
+
199
+ submit_btn = gr.Button("採点")
200
+ submit_btn.click(
201
+ calculate,
202
+ [skkey, folder_path, output_path, c0, threshold,t1, s1, s1m, t2, s2, reason1, s3, reason2, s4, c1, c2]
203
+ )
204
+ demo.launch()