Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,25 +1,23 @@
|
|
1 |
import gradio as gr
|
2 |
import pandas as pd
|
3 |
-
from datasets import
|
4 |
-
from transformers import GPT2Tokenizer, GPT2LMHeadModel, Trainer, TrainingArguments
|
5 |
import torch
|
6 |
import os
|
7 |
import matplotlib.pyplot as plt
|
|
|
8 |
import json
|
9 |
import io
|
10 |
from datetime import datetime
|
11 |
|
12 |
-
#
|
13 |
columns = []
|
14 |
|
15 |
-
#
|
16 |
-
hf_token = "YOUR_HUGGINGFACE_ACCESS_TOKEN"
|
17 |
-
|
18 |
-
# ファイル読み込み機能
|
19 |
def read_file(data_file):
|
20 |
global columns
|
21 |
try:
|
22 |
-
#
|
23 |
file_extension = os.path.splitext(data_file.name)[1]
|
24 |
if file_extension == '.csv':
|
25 |
df = pd.read_csv(data_file.name)
|
@@ -28,7 +26,7 @@ def read_file(data_file):
|
|
28 |
elif file_extension == '.xlsx':
|
29 |
df = pd.read_excel(data_file.name)
|
30 |
else:
|
31 |
-
return "無効なファイル形式です。CSV
|
32 |
|
33 |
# 列を検出
|
34 |
columns = df.columns.tolist()
|
@@ -36,22 +34,20 @@ def read_file(data_file):
|
|
36 |
except Exception as e:
|
37 |
return f"エラーが発生しました: {str(e)}"
|
38 |
|
39 |
-
|
40 |
-
# 列のバリデーション
|
41 |
def validate_columns(prompt_col, description_col):
|
42 |
if prompt_col not in columns or description_col not in columns:
|
43 |
return False
|
44 |
return True
|
45 |
|
46 |
-
|
47 |
-
# モデルの訓練
|
48 |
def train_model(data_file, model_name, epochs, batch_size, learning_rate, output_dir, prompt_col, description_col, hf_token):
|
49 |
try:
|
50 |
-
#
|
51 |
if not validate_columns(prompt_col, description_col):
|
52 |
-
return "
|
53 |
|
54 |
-
#
|
55 |
file_extension = os.path.splitext(data_file.name)[1]
|
56 |
if file_extension == '.csv':
|
57 |
df = pd.read_csv(data_file.name)
|
@@ -63,20 +59,20 @@ def train_model(data_file, model_name, epochs, batch_size, learning_rate, output
|
|
63 |
# データのプレビュー
|
64 |
preview = df.head().to_string(index=False)
|
65 |
|
66 |
-
#
|
67 |
df['text'] = df[prompt_col] + ': ' + df[description_col]
|
68 |
dataset = Dataset.from_pandas(df[['text']])
|
69 |
|
70 |
-
# GPT-2
|
71 |
tokenizer = GPT2Tokenizer.from_pretrained(model_name)
|
72 |
model = GPT2LMHeadModel.from_pretrained(model_name)
|
73 |
|
74 |
-
#
|
75 |
if tokenizer.pad_token is None:
|
76 |
tokenizer.add_special_tokens({'pad_token': '[PAD]'})
|
77 |
model.resize_token_embeddings(len(tokenizer))
|
78 |
|
79 |
-
#
|
80 |
def tokenize_function(examples):
|
81 |
tokens = tokenizer(examples['text'], padding="max_length", truncation=True, max_length=128)
|
82 |
tokens['labels'] = tokens['input_ids'].copy()
|
@@ -84,7 +80,7 @@ def train_model(data_file, model_name, epochs, batch_size, learning_rate, output
|
|
84 |
|
85 |
tokenized_datasets = dataset.map(tokenize_function, batched=True)
|
86 |
|
87 |
-
#
|
88 |
training_args = TrainingArguments(
|
89 |
output_dir=output_dir,
|
90 |
overwrite_output_dir=True,
|
@@ -104,7 +100,7 @@ def train_model(data_file, model_name, epochs, batch_size, learning_rate, output
|
|
104 |
metric_for_best_model="eval_loss"
|
105 |
)
|
106 |
|
107 |
-
# Trainer
|
108 |
trainer = Trainer(
|
109 |
model=model,
|
110 |
args=training_args,
|
@@ -112,53 +108,65 @@ def train_model(data_file, model_name, epochs, batch_size, learning_rate, output
|
|
112 |
eval_dataset=tokenized_datasets,
|
113 |
)
|
114 |
|
115 |
-
#
|
116 |
trainer.train()
|
117 |
eval_results = trainer.evaluate()
|
118 |
|
119 |
-
# Fine-tuned
|
120 |
model.save_pretrained(output_dir)
|
121 |
tokenizer.save_pretrained(output_dir)
|
122 |
|
123 |
-
#
|
124 |
train_loss = [x['loss'] for x in trainer.state.log_history if 'loss' in x]
|
125 |
eval_loss = [x['eval_loss'] for x in trainer.state.log_history if 'eval_loss' in x]
|
126 |
-
plt.plot(train_loss, label='
|
127 |
-
plt.plot(eval_loss, label='
|
128 |
-
plt.xlabel('
|
129 |
-
plt.ylabel('
|
130 |
-
plt.title('
|
131 |
plt.legend()
|
132 |
plt.savefig(os.path.join(output_dir, 'training_eval_loss.png'))
|
133 |
|
134 |
-
#
|
135 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
136 |
|
137 |
-
return f"
|
138 |
except Exception as e:
|
139 |
return f"エラーが発生しました: {str(e)}"
|
140 |
|
141 |
-
|
142 |
-
|
143 |
-
def upload_model_to_huggingface(output_dir, model_name, hf_token):
|
144 |
try:
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
folder_path=output_dir,
|
149 |
-
repo_id=model_name,
|
150 |
-
path_in_repo=".",
|
151 |
-
use_auth_token=hf_token
|
152 |
-
)
|
153 |
-
return f"モデルがHugging Faceに正常にアップロードされました。\nリポジトリURL: https://huggingface.co/{model_name}"
|
154 |
-
except Exception as e:
|
155 |
-
return f"モデルのアップロード中にエラーが発生しました: {str(e)}"
|
156 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
157 |
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
return "生成されたテキスト"
|
162 |
|
163 |
# UI設定
|
164 |
with gr.Blocks() as ui:
|
|
|
1 |
import gradio as gr
|
2 |
import pandas as pd
|
3 |
+
from datasets import load_dataset, Dataset
|
4 |
+
from transformers import GPT2Tokenizer, GPT2LMHeadModel, Trainer, TrainingArguments
|
5 |
import torch
|
6 |
import os
|
7 |
import matplotlib.pyplot as plt
|
8 |
+
from huggingface_hub import HfApi # ここを修正しました
|
9 |
import json
|
10 |
import io
|
11 |
from datetime import datetime
|
12 |
|
13 |
+
# グローバル変数で検出された列を保存
|
14 |
columns = []
|
15 |
|
16 |
+
# ファイル読み込み関数
|
|
|
|
|
|
|
17 |
def read_file(data_file):
|
18 |
global columns
|
19 |
try:
|
20 |
+
# ファイルをロード
|
21 |
file_extension = os.path.splitext(data_file.name)[1]
|
22 |
if file_extension == '.csv':
|
23 |
df = pd.read_csv(data_file.name)
|
|
|
26 |
elif file_extension == '.xlsx':
|
27 |
df = pd.read_excel(data_file.name)
|
28 |
else:
|
29 |
+
return "無効なファイル形式です。CSV, JSON, Excelファイルをアップロードしてください。"
|
30 |
|
31 |
# 列を検出
|
32 |
columns = df.columns.tolist()
|
|
|
34 |
except Exception as e:
|
35 |
return f"エラーが発生しました: {str(e)}"
|
36 |
|
37 |
+
# 列の選択が正しいかを検証
|
|
|
38 |
def validate_columns(prompt_col, description_col):
|
39 |
if prompt_col not in columns or description_col not in columns:
|
40 |
return False
|
41 |
return True
|
42 |
|
43 |
+
# モデル訓練関数
|
|
|
44 |
def train_model(data_file, model_name, epochs, batch_size, learning_rate, output_dir, prompt_col, description_col, hf_token):
|
45 |
try:
|
46 |
+
# 列の検証
|
47 |
if not validate_columns(prompt_col, description_col):
|
48 |
+
return "無効な列選択です。データセット内の列を確認してください。"
|
49 |
|
50 |
+
# ファイルのロード
|
51 |
file_extension = os.path.splitext(data_file.name)[1]
|
52 |
if file_extension == '.csv':
|
53 |
df = pd.read_csv(data_file.name)
|
|
|
59 |
# データのプレビュー
|
60 |
preview = df.head().to_string(index=False)
|
61 |
|
62 |
+
# 訓練用テキストの準備
|
63 |
df['text'] = df[prompt_col] + ': ' + df[description_col]
|
64 |
dataset = Dataset.from_pandas(df[['text']])
|
65 |
|
66 |
+
# GPT-2のトークナイザーとモデルを初期化
|
67 |
tokenizer = GPT2Tokenizer.from_pretrained(model_name)
|
68 |
model = GPT2LMHeadModel.from_pretrained(model_name)
|
69 |
|
70 |
+
# 必要であればパディングトークンを追加
|
71 |
if tokenizer.pad_token is None:
|
72 |
tokenizer.add_special_tokens({'pad_token': '[PAD]'})
|
73 |
model.resize_token_embeddings(len(tokenizer))
|
74 |
|
75 |
+
# データのトークナイズ関数
|
76 |
def tokenize_function(examples):
|
77 |
tokens = tokenizer(examples['text'], padding="max_length", truncation=True, max_length=128)
|
78 |
tokens['labels'] = tokens['input_ids'].copy()
|
|
|
80 |
|
81 |
tokenized_datasets = dataset.map(tokenize_function, batched=True)
|
82 |
|
83 |
+
# 訓練のための設定
|
84 |
training_args = TrainingArguments(
|
85 |
output_dir=output_dir,
|
86 |
overwrite_output_dir=True,
|
|
|
100 |
metric_for_best_model="eval_loss"
|
101 |
)
|
102 |
|
103 |
+
# Trainer設定
|
104 |
trainer = Trainer(
|
105 |
model=model,
|
106 |
args=training_args,
|
|
|
108 |
eval_dataset=tokenized_datasets,
|
109 |
)
|
110 |
|
111 |
+
# 訓練開始
|
112 |
trainer.train()
|
113 |
eval_results = trainer.evaluate()
|
114 |
|
115 |
+
# Fine-tunedモデルを保存
|
116 |
model.save_pretrained(output_dir)
|
117 |
tokenizer.save_pretrained(output_dir)
|
118 |
|
119 |
+
# 訓練損失と評価損失のグラフ生成
|
120 |
train_loss = [x['loss'] for x in trainer.state.log_history if 'loss' in x]
|
121 |
eval_loss = [x['eval_loss'] for x in trainer.state.log_history if 'eval_loss' in x]
|
122 |
+
plt.plot(train_loss, label='訓練損失')
|
123 |
+
plt.plot(eval_loss, label='評価損失')
|
124 |
+
plt.xlabel('ステップ数')
|
125 |
+
plt.ylabel('損失')
|
126 |
+
plt.title('訓練と評価の損失')
|
127 |
plt.legend()
|
128 |
plt.savefig(os.path.join(output_dir, 'training_eval_loss.png'))
|
129 |
|
130 |
+
# モデルのHuggingFaceにアップロード
|
131 |
+
hf_api = HfApi()
|
132 |
+
hf_api.upload_folder(
|
133 |
+
folder_path=output_dir,
|
134 |
+
path_in_repo=".",
|
135 |
+
repo_id=model_name,
|
136 |
+
token=hf_token
|
137 |
+
)
|
138 |
|
139 |
+
return f"訓練が完了しました。\nデータのプレビュー:\n{preview}", eval_results
|
140 |
except Exception as e:
|
141 |
return f"エラーが発生しました: {str(e)}"
|
142 |
|
143 |
+
# テキスト生成関数
|
144 |
+
def generate_text(prompt, temperature, top_k, top_p, max_length, repetition_penalty, use_comma, batch_size):
|
|
|
145 |
try:
|
146 |
+
model_name = "./fine-tuned-gpt2"
|
147 |
+
tokenizer = GPT2Tokenizer.from_pretrained(model_name)
|
148 |
+
model = GPT2LMHeadModel.from_pretrained(model_name)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
149 |
|
150 |
+
if use_comma:
|
151 |
+
prompt = prompt.replace('.', ',')
|
152 |
+
|
153 |
+
inputs = tokenizer(prompt, return_tensors="pt", padding=True)
|
154 |
+
attention_mask = inputs.attention_mask
|
155 |
+
outputs = model.generate(
|
156 |
+
inputs.input_ids,
|
157 |
+
attention_mask=attention_mask,
|
158 |
+
max_length=int(max_length),
|
159 |
+
temperature=float(temperature),
|
160 |
+
top_k=int(top_k),
|
161 |
+
top_p=float(top_p),
|
162 |
+
repetition_penalty=float(repetition_penalty),
|
163 |
+
num_return_sequences=int(batch_size),
|
164 |
+
pad_token_id=tokenizer.eos_token_id
|
165 |
+
)
|
166 |
|
167 |
+
return [tokenizer.decode(output, skip_special_tokens=True) for output in outputs]
|
168 |
+
except Exception as e:
|
169 |
+
return f"エラーが発生しました: {str(e)}"
|
|
|
170 |
|
171 |
# UI設定
|
172 |
with gr.Blocks() as ui:
|