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.
code
:param df:
:return:
"""
pass
You can use this helper function that calls Hebrew spacy
def segment_hebrew_spacy(text):
doc = nlp(text)
return [sent.text for sent in doc.sents]
Assistant
User
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Got it! You want to split Hebrew text into segments of approximately max_words without breaking sentences, using spaCy for sentence segmentation, and track segments with IDs. Here’s a complete implementation:
pythonCopy codeimport pandas as pd
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
for idx, row in df.iterrows():
testimony_id = row['testimony_id']
text = row['text']
# Get sentences
sentences = segment_hebrew_spacy(text)
segment = ""
segment_word_count = 0
segment_number = 0
for sent in sentences:
sent_word_count = len(sent.split())
# If adding this sentence exceeds max_words, finalize current segment
if segment_word_count + sent_word_count > max_words:
# Append current segment
all_segments.append({
'testimony_id': testimony_id,
'segment_id': f"{testimony_id}_{segment_number}",
'text': segment.strip()
})
# Start new segment
segment_number += 1
segment = sent
segment_word_count = sent_word_count
else:
# Add sentence to current segment
if segment:
segment += " " + sent
else:
segment = sent
segment_word_count += sent_word_count
# Append any remaining segment
if segment:
all_segments.append({
'testimony_id': testimony_id,
'segment_id': f"{testimony_id}_{segment_number}",
'text': segment.strip()
})
return pd.DataFrame(all_segments)
✅ How it works:
Uses segment_hebrew_spacy to split text into sentences.
Iterates through sentences and accumulates them into segments without exceeding max_words.
Tracks the segment number for each testimony.
Returns a DataFrame with testimony_id, segment_id, and text.
If you want, I can also optimize it to handle very large testimonies efficiently and make sure no segment ends up empty or overly small. This is useful for thousands of testimonies.
Do you want me to do that?
I made some changes.
Does it look correct?
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
for idx, row in df.iterrows():
testimony_id = row['testimony_id']
text = row['text']
# Get sentences
print("Loading SpaCy model...")
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()
# time the segmentation
start = time.time()
df['sentences'] = df['text'].apply(segment_hebrew_spacy)
minutes = int((time.time() - start) / 60)
print(f"Segmentation done in {minutes} minutes")
df = df.explode('sentences')
df = add_tid_order(df)
df.index = df['tid_order']
df.drop(columns=['text', 'tid', 'order'], inplace=True)
# save before continuing
df.to_csv("../../data/ivritai_transcripts/segmented_sentences.csv")
segment = ""
segment_word_count = 0
segment_number = 0
for sent in df.sentences:
sent_word_count = len(sent.split())
# If adding this sentence exceeds max_words, finalize current segment
if segment_word_count + sent_word_count > max_words:
# Append current segment
all_segments.append({
'testimony_id': testimony_id,
'segment_id': f"{testimony_id}_{segment_number}",
'text': segment.strip()
})
# Start new segment
segment_number += 1
segment = sent
segment_word_count = sent_word_count
else:
# Add sentence to current segment
if segment:
segment += " " + sent
else:
segment = sent
segment_word_count += sent_word_count
# Append any remaining segment
if segment:
all_segments.append({
'testimony_id': testimony_id,
'segment_id': f"{testimony_id}_{segment_number}",
'text': segment.strip()
})
return pd.DataFrame(all_segments)
Thanks for sharing your updated code. I went through it carefully, and there are a few issues and inefficiencies in your version:
Loading the SpaCy model inside the loop
pythonCopy codenlp = spacy.load("he_ner_news_trf")
Right now, you are loading the model for every single testimony. This is extremely slow.
Fix: Load the model once before the loop.
Applying segment_hebrew_spacy to the entire DataFrame inside the loop
pythonCopy codedf['sentences'] = df['text'].apply(segment_hebrew_spacy)
Here you are re-processing the whole DataFrame (df) for each row. That means if df has 100 testimonies, you are re-running segmentation 100 times for the entire DataFrame.
Fix: Apply segment_hebrew_spacy just to the current text inside the loop.
Exploding the DataFrame and dropping columns
pythonCopy codedf = df.explode('sentences')
df = add_tid_order(df)
df.index = df['tid_order']
df.drop(columns=['text', 'tid', 'order'], inplace=True)
This is unnecessary inside the loop for per-testimony segmentation. You don’t need to explode the full DataFrame for segmenting one testimony.
Doing this here will break the logic that accumulates segments for a single testimony.
Timing and saving CSV inside the loop
Saving segmented_sentences.csv inside the loop will overwrite the file repeatedly for each testimony.
Similarly, timing statements inside the loop are okay for debugging but should be moved outside the loop for efficiency.
✅ Suggested corrected structure
pythonCopy codeimport pandas as pd
import spacy
import time
for idx, row in df.iterrows():
testimony_id = row['testimony_id']
text = row['text']
# Segment sentences for this testimony only
sentences = segment_hebrew_spacy(text)
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:
# Save current segment
all_segments.append({
'testimony_id': testimony_id,
'segment_id': f"{testimony_id}_{segment_number}",
'text': segment.strip()
})
segment_number += 1
segment = sent
segment_word_count = sent_word_count
else:
segment = f"{segment} {sent}" if segment else sent
segment_word_count += sent_word_count
if segment:
all_segments.append({
'testimony_id': testimony_id,
'segment_id': f"{testimony_id}_{segment_number}",
'text': segment.strip()
})
return pd.DataFrame(all_segments)
This version:
Loads the model once.
Segments per testimony, not the entire DataFrame repeatedly.
Avoids unnecessary DataFrame explosions or CSV writes inside the loop.
Keeps your segmenting logic intact.
If you want, I can also add an optional feature to save all sentences for all testimonies once while still keeping efficient per-testimony segmentation. This is handy if you need both sentence-level and segment-level outputs.
Do you want me to do that?