Building a Sentence Endpoint Detector with Deep Learning
Sharing the story of developing a deep learning model that detects the endpoints of sentences (periods, question marks).
Project Introduction
With WebRTC's Speech Recognition API, you can easily implement STT (Speech To Text). You can try a demo on the WebRTC Lab's speech recognition site, and you'll be surprised at how well it recognizes speech. The example below is me saying "마침표가 찍히지 않는 것을 볼 수 있습니다" ("You can see that no period is added").
While using WebRTC's Speech Recognition API in an internal company project, I found that the STT output has no sentence endpoints such as periods or question marks. That project needed sentence boundaries, so I implemented a deep learning model that detects sentence endpoints such as periods and question marks.
Development Process
The development went in the order Crawling > Preprocessing > Analysis > Labeling > Training.
Crawling
This is the stage of collecting the data needed for training. The data used in this project was the minutes of the 20th National Assembly of Korea, which is most similar to the data that will actually come in. The data was in hwp format, so I converted it to txt files using a GUI macro.
Preprocessing
This is the stage of processing and cleaning the collected data. The meeting data follows a consistent format, so I analyzed it and applied the following preprocessing.
Preprocessing the National Assembly minutes
- Extract the text array (line by line)
- Per-line preprocessing
'^\n' : Remove blank lines
'o' : Remove paragraph descriptions that use a lowercase English o (ex: o Greeting from the Cabinet members)
- Convert the text array to a text string
- Remove data before and after the meeting
The first occurrence of '\(\d+?[월시]\d+?[일분]\s.+?\)' marks the start
The last occurrence of '\(\d+?[월시]\d+?[일분]\s.+?\)' marks the end
- Remove non-conversation content
'(\(.+\))' : Remove parenthesized data
'\d+\.\s[^◯]*' : Remove the list of meeting agenda items
- Split into conversations per speaker over time
'◯.+?\s.+?\s+' : Extract the speaker
Speaker sequence and conversation sequence
- Clean each speaker's conversation paragraph
'\n' Remove line break characters
strip (remove leading and trailing whitespace)
'\s{2,}' Replace two or more spaces with one
'\s$' Remove the space at the end of a paragraph
Replace '․' (not a period) between consecutive nouns with ','
- Extract sentences from the paragraphs
strip (remove leading and trailing whitespace)
'\s?(.+?[\.\!\?…])\D' : Extract sentencesAfter removing data unnecessary for training and splitting by speaker, I collected a total of 2,084,007 sentences.

Analysis
This is the stage of visualizing the data and checking that preprocessing was done correctly. Analyzing the collected sentences, they average about 40 characters, with a maximum length of 1,131 characters.
Max sentence length: 1131
Min sentence length: 2
Mean sentence length: 49.34
Sentence length std: 40.68
Median sentence length: 38.0
Sentence length 1st quartile: 19.0
Sentence length 3rd quartile: 67.0

Analyzing the collected words, sentences average about 12 words, with a maximum of 256 words.
Max word count: 256
Min word count: 1
Mean word count: 11.89
Word count std: 10.00
Median word count: 9.0
Word count 1st quartile: 5.0
Word count 3rd quartile: 16.0
The analysis of special characters and endpoint types is as follows.
Sentences ending with a question mark: 11.44%
Sentences ending with a period: 83.64%
Sentences ending with …: 4.64%
Sentences with commas: 30.27%
Sentences with special characters: 36.72%
Labeling
This is the stage of labeling the data. I defined the problem to solve as a classification problem: choosing which of space( ), period(.), and question mark(?) comes between two words.
So I split the words into Bigrams, and added [PAD] for the case where the last word of a sentence comes alone. For the label, I used the actual value that comes between the Bigram: 0 for space, 1 for period, and 2 for question mark.
Labeling the sentence 의석을 정리해 주시기 바랍니다. 그럼 준비 되셨나요? ("Please take your seats. So, are you ready?") gives the following.
| data | label |
|---|---|
| 의석을 [PAD] | 0 |
| 의석을 정리해 | 0 |
| 정리해 [PAD] | 0 |
| 정리해 주시기 | 0 |
| 주시기 [PAD] | 0 |
| 주시기 바랍니다 | 0 |
| 바랍니다 [PAD] | 1 |
| 바랍니다 그럼 | 1 |
| 그럼 [PAD] | 0 |
| 그럼 준비 | 0 |
| 준비 [PAD] | 0 |
| 준비 되셨나요 | 0 |
| 되셨나요 [PAD] | 2 |
Analyzing the ratio of the labeled data gives the following.
Total data count : 16,519,997
Question mark data count : 158,842 (0.9%)
Period data count : 1,183,299 (7.2%)
Space data count : 15,177,856 (91.9%)Training
I used Keras for training, and built a vocabulary of 692,862 words in the following way to represent words as positive integers.
tokenize
def createVocabulary(bigram_array):
vocab = {}
index = 1
for i, bigram in enumerate(bigram_array):
words = bigram.split(' ')
if len(words) != 2:
continue
for word in words:
if word not in vocab:
vocab[word] = index
index += 1
return vocab, index
def text2seq(vocab, bigram_array):
bigram_seq = []
for i, bigram in enumerate(bigram_array):
words = bigram.split(' ')
seq = []
for word in words:
if word in vocab:
seq.append(vocab[word])
else:
seq.append(0) # 0 for OOV
bigram_seq.append(seq)
return bigram_seqThe data labeled earlier as space(0), period(1), and question mark(2) was one-hot encoded using the keras.util.to_categorical function, and I split the total data into training and test data at 8:2.
Training data : 13,215,997
Test data : 3,304,000First, I used an Embedding layer to convert the words represented as positive integers into dense vectors of a fixed size. Next I added an LSTM layer, and since this is a problem of classifying among three classes (space, period, question mark), I added a softmax Dense layer with an output dimension of 3. I used categorical_crossentropy for the loss, and compiled the model with the adam optimizer.
model
model = Sequential()
model.add(Embedding(vocab_size, 2, input_length=2))
model.add(LSTM(128))
model.add(Dense(3, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
history = model.fit(X_train, y_train, epochs=8, validation_split=0.3, batch_size = 2048)I trained for a total of 8 epochs, which took 30 minutes. The validation accuracy at the end of training was about 98.6%, but since the data is heavily biased toward space(0), an accuracy of over 90% is guaranteed even if everything is predicted as space(0), so this doesn't mean much.

So here it's important to look at precision, recall, and f1-score.
| Class | precision | recall | f1-score | Samples |
|---|---|---|---|---|
| Space(0) | 0.99 | 1.00 | 0.99 | 1,520,203 |
| Period(1) | 0.95 | 0.93 | 0.94 | 232,575 |
| Question mark(2) | 0.90 | 0.66 | 0.76 | 31,706 |
| micro avg | 0.98 | 0.98 | 0.98 | 1,784,484 |
| macro avg | 0.95 | 0.86 | 0.90 | 1,784,484 |
| weighted avg | 0.98 | 0.98 | 0.98 | 1,784,484 |
| samples avg | 0.98 | 0.98 | 0.98 | 1,784,484 |
As you can see, space(0), which has the most data, has high precision, recall, and f1-score. Period(1) also performed better than expected, with almost every metric above 0.9, even though it has about 6.5 times less data than space(0). However, question mark(2) has too little data, so its recall came out a bit low at 0.66, but its precision of 0.90 is a fairly reliable number.
Test
The script used in this test is an excerpt from the broadcast script of Kim Yong-min's briefing on Thursday, August 22, 2018, and I state that it has nothing to do with any personal views or meaning.
I took an excerpt from the broadcast script of Kim Yong-min's briefing on Thursday, August 22, 2018, removed the periods and question marks, and fed it into the model as input data to test it.

Apart from a period inserted in line 3 where a space should be, and a period missing in line 12, you can see that everything was predicted reasonably well.
Demo
The video below is a demo of the endpoint detection model mounted on STT using WebRTC's Speech Recognition API.
The endpoint detection model was deployed on Python Flask and served as an API, and I implemented it so that when the speaker finishes speaking, the API is called to add a period or question mark.
Closing
WebRTC Speech Recognition performs really well, and it's even free. With it, I think you could build a wide variety of services. Also, hwp files seem really hard to extract text from.. 😭
That wraps up the project of building a sentence endpoint detector with deep learning.
Comments