|
import streamlit as st |
|
import pandas as pd |
|
import torch |
|
from torch.utils.data import Dataset, DataLoader |
|
from transformers import AutoTokenizer, AutoModelForSequenceClassification, Trainer, TrainingArguments |
|
from sklearn.model_selection import train_test_split |
|
import os |
|
import json |
|
|
|
|
|
class TextDataset(Dataset): |
|
def __init__(self, encodings, labels): |
|
self.encodings = encodings |
|
self.labels = labels |
|
|
|
def __getitem__(self, idx): |
|
|
|
item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()} |
|
item['labels'] = torch.tensor(self.labels[idx]) |
|
return item |
|
|
|
def __len__(self): |
|
return len(self.labels) |
|
|
|
|
|
def load_config(config_path='config.json'): |
|
with open(config_path, 'r') as f: |
|
config = json.load(f) |
|
return config |
|
|
|
|
|
def main(): |
|
st.title("CSV Data Processing and Model Training π§ ") |
|
|
|
|
|
config = load_config() |
|
|
|
|
|
uploaded_files = st.file_uploader("Upload CSV files", accept_multiple_files=True, type="csv") |
|
|
|
if uploaded_files: |
|
combined_texts = [] |
|
|
|
|
|
for uploaded_file in uploaded_files: |
|
df = pd.read_csv(uploaded_file) |
|
|
|
|
|
combined_texts.extend(df.astype(str).agg(' '.join, axis=1)) |
|
|
|
|
|
st.write("Combined text for training:", combined_texts[:5]) |
|
|
|
|
|
use_existing_model = st.checkbox("Load an existing local model?", value=False) |
|
|
|
if use_existing_model: |
|
|
|
model_path = st.text_input("Enter the path to the local model directory:", value="") |
|
if model_path and os.path.exists(model_path): |
|
model = AutoModelForSequenceClassification.from_pretrained(model_path) |
|
st.write(f"Loaded model from {model_path} successfully! π") |
|
else: |
|
st.warning("Please provide a valid model directory path.") |
|
return |
|
else: |
|
|
|
model = AutoModelForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=2) |
|
|
|
|
|
tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased') |
|
|
|
|
|
inputs = tokenizer(combined_texts, padding=True, truncation=True, return_tensors="pt", max_length=512) |
|
|
|
|
|
labels = [0] * len(combined_texts) |
|
|
|
|
|
train_inputs, val_inputs, train_labels, val_labels = train_test_split( |
|
inputs['input_ids'], labels, test_size=0.2, random_state=42 |
|
) |
|
|
|
|
|
train_dataset = TextDataset(encodings={'input_ids': train_inputs}, labels=train_labels) |
|
val_dataset = TextDataset(encodings={'input_ids': val_inputs}, labels=val_labels) |
|
|
|
|
|
num_workers = config.get('num_workers', 4) |
|
|
|
|
|
train_dataloader = DataLoader(train_dataset, batch_size=8, num_workers=num_workers) |
|
val_dataloader = DataLoader(val_dataset, batch_size=8, num_workers=num_workers) |
|
|
|
|
|
training_args = TrainingArguments( |
|
output_dir='./results', |
|
num_train_epochs=1, |
|
per_device_train_batch_size=8, |
|
per_device_eval_batch_size=8, |
|
warmup_steps=500, |
|
weight_decay=0.01, |
|
logging_dir='./logs', |
|
logging_steps=10, |
|
evaluation_strategy="epoch" |
|
) |
|
|
|
|
|
trainer = Trainer( |
|
model=model, |
|
args=training_args, |
|
train_dataset=train_dataset, |
|
eval_dataset=val_dataset |
|
) |
|
|
|
|
|
trainer.train() |
|
|
|
|
|
save_path = st.text_input("Enter the directory path to save the trained model:", value="./trained_model") |
|
|
|
if save_path: |
|
os.makedirs(save_path, exist_ok=True) |
|
model.save_pretrained(save_path) |
|
tokenizer.save_pretrained(save_path) |
|
st.write(f"Model saved successfully to {save_path}! π") |
|
else: |
|
st.warning("Please provide a valid directory path to save the model.") |
|
|
|
|
|
st.success("Training completed successfully! π") |
|
|
|
if __name__ == "__main__": |
|
main() |
|
|