In traditional harmony phrases end with cadences.
When we have only a melody, like your PDF, the cadences are implied, implied because there isn't full harmony to make them explicit.
There are various cadence types, but for this question we only need to talk about half cadences which pause on the dominant and perfect cadences on the tonic. Normally those would be dominant and tonic chords, but with only the melody we can focus on the dominant and tonic tones, scale degrees.
A common structural plan is to end one or more phrases on half cadences, which have a feeling of only partial ending and the music continues, before playing a phrase with a conclusive perfect cadence.
A half cadence can be made more emphatic by approaching the dominant from a half step below, from the dominant's leading tone. This is what happens in measure 4 when the B natural is used instead of the B flat of the key signature. That is considered just a temporary chromatic change to make the half cadence more emphatic.
...every B in the piece is natural
Toward the end of the melody - should be measure 27 of your PDF - the harmony shifts to the subdominant chord, the B flat or G minor chords in F major, and then the B flat of the key signature is used, because it's an essential tone of the subdominant... actually it is the subdominant.
All that happens in interior of the tune. The starting and ending are clearly on the F major chord.
It starts and ends on F major, a raised fourth scale degree is used for the half cadences, it highlights the subdominant just before the end. This is a very common tonal structure for music in the key of F major.
The chromatic variation of the B isn't abnormal. It can happen with other tones too. Conventionally the start and especially the end harmonies determine the key. Chromatically shifting around on the interior can be called tonicization or modulation depending on the extent of the change, but those shifts don't change the key of the whole piece. Again, this is a convention, a norm. You could have a piece that deliberate works against that convention and then the key might be an ambiguous/debatable point.