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 = []
code
Assistant
# Get sentences
print("Loading SpaCy model...")
if spacy.prefer_gpu():
print("Using GPU")
else:
print("Using CPU")
# spacy.require_gpu()
start = time.time()
nlp = spacy.load("he_ner_news_trf") # 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)
segment = ""
segment_word_count = 0
segment_number = 0
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(),
'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(),
'word_count': segment_word_count
})
# save progressively
res = pd.DataFrame(all_segments)
res.to_csv("../../data/ivritai_transcripts/segmented_sentences.csv")
print(f"Processed testimony {identifier} into {segment_number + 1} segments.")
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
def basic_stats(df: pd.DataFrame):
"""
Print basic stats about the dataframe.
1. Number of testimonies
2. Average word count per testimony
3. Histogram of word count
:return:
"""
# number of testimonies
print(f"Number of testimonies: {len(df)}")
# average word count per testimony
df["word_count"] = df.text.apply(lambda x: len(str(x).split()))
print(f"Average word count per testimony: {df.word_count.mean()}")
# histogram of word count
plt.hist(df.word_count, bins=50)
plt.xlabel("Word count")
plt.ylabel("Number of testimonies")
plt.title("Histogram of word count per testimony")
plt.show()
if name == 'main':
data = pd.read_csv("../../data/ivritai_transcripts/ivritai_transcripts_with_metadata.csv", index_col=0)
# only keep specific columns
cols = ["text", "Identifier", "Witness Identifier", "עד/ה", "שיוך לקהילה",
"איפה היית ב7/10", "Name", "שפת העדות"]
data = data[cols]
data.rename(columns={"עד/ה": "witness",
"שיוך לקהילה": "community",
"איפה היית ב7/10": "location",
"Name": "name",
"שפת העדות": "testimony_language"}, inplace=True)
# basic_stats(data)
segmented_df = preprocess_text_segments(data, max_words=600)
segmented_df.to_csv("../../data/ivritai_transcripts/segmented_sentences.csv")
"""
Good question — your script is pretty heavy (SpaCy transformer model + building/storing a large dataframe + iterating row by row), so memory will balloon if you don’t clear objects. Here are some things you can do to free memory during the run:
🔹 1. Don’t keep everything in all_segments
Right now, you’re building one big list of all segments (all_segments) before making a DataFrame. For large input this explodes in memory.
Instead, write out progressively and clear:
pythonCopy codeimport gc
for idx, row in df.iterrows():
# ... your segmentation logic ...
if segment:
seg_df = pd.DataFrame([{
**row.to_dict(),
'tid_order': f"{int(testimony_id)}_{segment_number}",
'text': segment.strip(),
'word_count': segment_word_count
}])
seg_df.to_csv("../../data/ivritai_transcripts/segmented_sentences.csv",
mode='a', header=not os.path.exists("../../data/ivritai_transcripts/segmented_sentences.csv"))
code
# Clear variables you don’t need anymore
del sentences, segment
gc.collect()
This way you never keep all all_segments in memory.
🔹 2. Load SpaCy once
Currently you load the transformer model inside preprocess_text_segments each time. Move it outside and reuse:
pythonCopy codenlp = spacy.load("he_ner_news_trf")
🔹 3. Explicit cleanup with gc.collect()
After processing a row / chunk:
pythonCopy codedel res # if you don’t need the intermediate DataFrame
gc.collect()
This forces Python to release memory from deleted objects.
🔹 4. Use .itertuples() instead of .iterrows()
iterrows() builds Series objects → expensive in memory. Use:
pythonCopy codefor row in df.itertuples(index=False):
identifier = row.Identifier
sentences = segment_hebrew_spacy(row.text, nlp)
🔹 5. Chunk the input CSV
If the raw input is huge, don’t read all into RAM at once:
pythonCopy codechunksize = 500
for chunk in pd.read_csv("ivritai_transcripts_with_metadata.csv", chunksize=chunksize):
preprocess_text_segments(chunk, max_words=600, nlp=nlp)
Use .pipe(texts, batch_size=20) instead of processing one row at a time.
👉 If your main issue is RAM blow-up while segmenting all testimonies, the biggest wins are:
progressive saving instead of all_segments in memory,
chunked processing of the CSV,
and reusing a single nlp.
Do you want me to rewrite your preprocess_text_segments function so it saves progressively (without keeping all_segments in memory) and clears garbage each loop?