Spaces:
Sleeping
Sleeping
Update utils/model.py
Browse files4 unmodified lines5678910111213141516171819202122232425262728293031323334353637381 unmodified line404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293944 unmodified linesfrom spacy.tokens import DocBinimport randomimport shutil# Load the training data from the .spacy filedef load_data_from_spacy_file(file_path):# Initialize a blank English model to ensure compatibilitynlp = spacy.blank("en")# Load the DocBin object and get documentstry:doc_bin = DocBin().from_disk(file_path)docs = list(doc_bin.get_docs(nlp.vocab))return docsexcept Exception as e:print(f"Error loading data from .spacy file: {e}")return []# Train model functiondef train_model(epochs, model_path):# Initialize a blank English modelnlp = spacy.blank("en")# Create an NER component and add it to the pipelineif "ner" not in nlp.pipe_names:ner = nlp.add_pipe("ner")nlp.add_pipe("sentencizer")# Define all possible entity labelslabels = ["PERSON", "CONTACT", "EMAIL", "ABOUT", "EXPERIENCE", "YEARS_EXPERIENCE","UNIVERSITY", "SOFT_SKILL", "INSTITUTE", "LAST_QUALIFICATION_YEAR", "JOB_TITLE",1 unmodified line"LANGUAGE", "LOCATION", "PROJECTS", "SKILL", "CERTIFICATE"]# Add labels to the NER componentfor label in labels:ner.add_label(label)# Load the training datatrain_data = load_data_from_spacy_file("./data/Spacy_data.spacy")# Start the trainingoptimizer = nlp.begin_training()epoch_losses = []best_loss = float('inf')# Training loopfor epoch in range(epochs):losses = {}random.shuffle(train_data) # Shuffle data for better training# Create minibatchesbatches = minibatch(train_data, size=compounding(4.0, 32.0, 1.001))for batch in batches:texts, annotations = zip(*[(doc.text, {"entities": [(ent.start_char, ent.end_char, ent.label_) for ent in doc.ents]}) for doc in batch])# Convert to Example objectsexamples = [Example.from_dict(nlp.make_doc(text), annotation) for text, annotation in zip(texts, annotations)]# Update the modelnlp.update(examples, sgd=optimizer, drop=0.35, losses=losses)current_loss = losses.get("ner", float('inf'))epoch_losses.append(current_loss)print(f"Losses at epoch {epoch + 1}: {losses}")# Save the best modelif current_loss < best_loss:best_loss = current_loss# Save to a temporary pathtemp_model_path = model_path + "_temp"nlp.to_disk(temp_model_path)# Use shutil to move the model to the final pathif os.path.exists(model_path):shutil.rmtree(model_path) # Remove the old model if it existsshutil.copytree(temp_model_path, model_path) # Copy the temp model to the final pathshutil.rmtree(temp_model_path) # Remove the temporary model directory# Final save after trainingnlp.to_disk(model_path)return epoch_losses4 unmodified lines567891011121314151617181920212223242526272829303132333435361 unmodified line38394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041054 unmodified linesfrom spacy.tokens import DocBinimport randomimport shutilimport osdef load_data_from_spacy_file(file_path):"""Load training data from .spacy file."""nlp = spacy.blank("en")try:doc_bin = DocBin().from_disk(file_path)docs = list(doc_bin.get_docs(nlp.vocab))print(f"Loaded {len(docs)} documents from {file_path}.")return docsexcept Exception as e:print(f"Error loading data from .spacy file: {e}")return []def train_model(epochs, model_path):"""Train NER model."""nlp = spacy.blank("en")# Add the NER pipelineif "ner" not in nlp.pipe_names:ner = nlp.add_pipe("ner")nlp.add_pipe("sentencizer") # Optional component to split sentences# Define entity labelslabels = ["PERSON", "CONTACT", "EMAIL", "ABOUT", "EXPERIENCE", "YEARS_EXPERIENCE","UNIVERSITY", "SOFT_SKILL", "INSTITUTE", "LAST_QUALIFICATION_YEAR", "JOB_TITLE",1 unmodified line"LANGUAGE", "LOCATION", "PROJECTS", "SKILL", "CERTIFICATE"]# Add the labels to the NER pipelinefor label in labels:ner.add_label(label)# Load training datatrain_data = load_data_from_spacy_file("./data/Spacy_data.spacy")# Verify if data was loaded correctlyif not train_data:print("No training data found. Exiting training.")returnoptimizer = nlp.begin_training()epoch_losses = []best_loss = float('inf')# Start training loopfor epoch in range(epochs):losses = {}random.shuffle(train_data) # Shuffle data# Create batchesbatches = minibatch(train_data, size=compounding(4.0, 32.0, 1.001))for batch in batches:# Extract texts and annotationstry:texts, annotations = zip(*[(doc.text, {"entities": [(ent.start_char, ent.end_char, ent.label_) for ent in doc.ents]})for doc in batch])except ValueError as e:print(f"Error processing batch: {e}")continue# Create Example objectsexamples = [Example.from_dict(nlp.make_doc(text), annotation)for text, annotation in zip(texts, annotations)]# Update the modelnlp.update(examples, sgd=optimizer, drop=0.35, losses=losses)# Record loss for this epochcurrent_loss = losses.get("ner", float('inf'))epoch_losses.append(current_loss)print(f"Losses at epoch {epoch + 1}: {losses}")# Save the best modelif current_loss < best_loss:best_loss = current_losstemp_model_path = model_path + "_temp"nlp.to_disk(temp_model_path)# Safely move to the final pathif os.path.exists(model_path):shutil.rmtree(model_path)shutil.copytree(temp_model_path, model_path)shutil.rmtree(temp_model_path)# Save the final modelnlp.to_disk(model_path)print(f"Training completed. Final model saved at: {model_path}")return epoch_losses
utils/model.py+46-35