This script wont run on my laptop since it need lots of RAM. Can you please help me make…
- User
This script wont run on my laptop since it need lots of RAM. Can you please help me make it more effiecnt? There are 750 rows of data. It ran for 5 minutes on the first 5 rows. Then, running on the full dataframe crached.
""" import random import time import pandas as pd import matplotlib.pyplot as plt import spacy import gc
def segment_hebrew_spacy(text, nlp): doc = nlp(text) return [sent.text for sent in doc.sents]
def segment_hebrew_spacy_texts(texts, nlp, batch_size=8):
"""
texts: list of testimony texts
Returns list of list of sentences
"""
all_sentences = []
for doc in nlp.pipe(texts, batch_size=batch_size):
all_sentences.append([sent.text for sent in doc.sents])
return all_sentences
def add_tid_order(df): df['order'] = df.groupby(['Identifier']).cumcount() df['tid'] = df['Identifier'].str.split(".").str[-1].astype(str) df['tid_order'] = df['tid'] + '_' + df['order'].astype(str) return df
def preprocess_text_segments(df: pd.DataFrame, max_words: int) -> pd.DataFrame: """ Divide the text into segments of approx max_words words each. Make sure to not split sentences. Add a column "segment_id" to the dataframe to identify each segment. The ids should be in the format <testimony_id>_<segment_number>. 1. If a testimony has less than max_words, it should have a single segment with segment_number 0. 2. If a testimony has more than max_words, it should be split into multiple segments, each with segment_number starting from 0. """ all_segments = []
# Get sentences print("Loading SpaCy model...") # if torch.cuda.is_available(): # spacy.require_gpu() # this forces SpaCy to use GPU # print("SpaCy is now using the GPU") # else: # print("GPU not available, using CPU") start = time.time() nlp = spacy.load("he_ner_news_trf", disable=["tagger", "parser", "ner"]) # Requires GPU for best performance print(f"Model loaded in {(time.time() - start):.2f} seconds\n") print("Segmenting sentences...") print() for idx, row in df.iterrows(): identifier = row['Identifier'] testimony_id = identifier.split(".")[-1] if pd.notna(identifier) else str(random.randint(100000, 999999)) # process only this testimony sentences = segment_hebrew_spacy(row['text'], nlp=nlp) # sentences_list = segment_hebrew_spacy_texts([row['text']], nlp=nlp) # sentences = sentences_list[0] if sentences_list else [] # <-- take first (and only) item segment = "" segment_word_count = 0 segment_number = 0 # Add project title if exists project_title = "" if pd.notna(row.get("special_project")): project_title = f"Special tag: {row['special_project']}\n\n" for sent in sentences: sent_word_count = len(sent.split()) if segment_word_count + sent_word_count > max_words: all_segments.append({ **row.to_dict(), # keep metadata # 'testimony_id': testimony_id, 'tid_order': f"{int(testimony_id)}_{segment_number}", # 'text': segment.strip(), 'text': (project_title + segment.strip()) if project_title else segment.strip(), 'word_count': segment_word_count }) segment_number += 1 segment = sent segment_word_count = sent_word_count else: segment = f"{segment} {sent}".strip() segment_word_count += sent_word_count if segment: all_segments.append({ **row.to_dict(), # keep metadata # 'testimony_id': testimony_id, 'tid_order': f"{int(testimony_id)}_{segment_number}", # 'text': segment.strip(), 'text': (project_title + segment.strip()) if project_title else segment.strip(), 'word_count': segment_word_count }) # save progressively res = pd.DataFrame(all_segments) res.to_csv("../../data/ivritai_transcripts/segmented_sentences_special_titles.csv") print(f"Processed testimony {identifier} into {segment_number + 1} segments.") # clear memory del res gc.collect() minutes = int((time.time() - start) / 60) print(f"Segmentation done in {minutes} minutes") res = pd.DataFrame(all_segments) # set index to tid_order res.set_index('tid_order', inplace=True) return res - Assistant
- User
There is no he_core_news_sm
- Assistant
- User
if "sentencizer" not in nThere is no such thing spacy.blank("he")
- Assistant