In this code, what should I change to add a title to each segment that belongs to a special project? i.e.: the rows with "special project" don't have a NaN value.
"""
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 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
Got it — you want each segment to include a title if it belongs to a special project (i.e., when the column "special_project" is not NaN).
You can achieve this easily by modifying the section where each segment is created — specifically, prepend a title to the segment text when the row has a value in "special_project".
Here’s the minimal and clean change you should make inside the segmentation loop.
✅ Step-by-step modification
Find this part inside your for idx, row in df.iterrows(): loop:
pythonCopy codesentences = segment_hebrew_spacy(row['text'], nlp=nlp)
segment = ""
segment_word_count = 0
segment_number = 0
Now, after initializing those variables, add this:
pythonCopy code# Add project title if exists
project_title = ""
if pd.notna(row.get("special_project")):
project_title = f"\n\n### {row['special_project']} ###\n\n"
# 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
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.")
# 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
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",
"פרויקטים מיוחדים": "special_project"}, inplace=True)
# basic_stats(data)
segmented_df = preprocess_text_segments(data, max_words=400)
segmented_df.to_csv("../../data/ivritai_transcripts/segmented_sentences_400_word_limit.csv")
"""
Then, when you append each segment to all_segments, prepend this title to the text only for the first segment of that testimony:
Replace both occurrences of
pythonCopy code'text': segment.strip(),
with:
pythonCopy code'text': (project_title + segment.strip()) if (segment_number == 0 and project_title) else segment.strip(),
✅ Resulting behavior
If a row has "special_project" = "Shoah comparison" (for example), the first segment will start like this:
shellCopy code### Shoah comparison ###
אני זוכרת את...
If "special_project" is NaN, no title is added.
✅ Optional: if you prefer a separate column instead of inline title
If you’d rather add a new column segment_title instead of editing the text, you can instead include:
pythonCopy code'title': row['special_project'] if pd.notna(row['special_project']) else None,
in the dictionaries you append to all_segments.
That would keep text clean while allowing flexible display or filtering later.
Would you like me to show the full function (preprocess_text_segments) with this modification applied cleanly?