timit.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. # Natural Language Toolkit: TIMIT Corpus Reader
  2. #
  3. # Copyright (C) 2001-2007 NLTK Project
  4. # Author: Haejoong Lee <haejoong@ldc.upenn.edu>
  5. # Steven Bird <stevenbird1@gmail.com>
  6. # Jacob Perkins <japerk@gmail.com>
  7. # URL: <http://nltk.org/>
  8. # For license information, see LICENSE.TXT
  9. # [xx] this docstring is out-of-date:
  10. """
  11. Read tokens, phonemes and audio data from the NLTK TIMIT Corpus.
  12. This corpus contains selected portion of the TIMIT corpus.
  13. - 16 speakers from 8 dialect regions
  14. - 1 male and 1 female from each dialect region
  15. - total 130 sentences (10 sentences per speaker. Note that some
  16. sentences are shared among other speakers, especially sa1 and sa2
  17. are spoken by all speakers.)
  18. - total 160 recording of sentences (10 recordings per speaker)
  19. - audio format: NIST Sphere, single channel, 16kHz sampling,
  20. 16 bit sample, PCM encoding
  21. Module contents
  22. ===============
  23. The timit corpus reader provides 4 functions and 4 data items.
  24. - utterances
  25. List of utterances in the corpus. There are total 160 utterances,
  26. each of which corresponds to a unique utterance of a speaker.
  27. Here's an example of an utterance identifier in the list::
  28. dr1-fvmh0/sx206
  29. - _---- _---
  30. | | | | |
  31. | | | | |
  32. | | | | `--- sentence number
  33. | | | `----- sentence type (a:all, i:shared, x:exclusive)
  34. | | `--------- speaker ID
  35. | `------------ sex (m:male, f:female)
  36. `-------------- dialect region (1..8)
  37. - speakers
  38. List of speaker IDs. An example of speaker ID::
  39. dr1-fvmh0
  40. Note that if you split an item ID with colon and take the first element of
  41. the result, you will get a speaker ID.
  42. >>> itemid = 'dr1-fvmh0/sx206'
  43. >>> spkrid , sentid = itemid.split('/')
  44. >>> spkrid
  45. 'dr1-fvmh0'
  46. The second element of the result is a sentence ID.
  47. - dictionary()
  48. Phonetic dictionary of words contained in this corpus. This is a Python
  49. dictionary from words to phoneme lists.
  50. - spkrinfo()
  51. Speaker information table. It's a Python dictionary from speaker IDs to
  52. records of 10 fields. Speaker IDs the same as the ones in timie.speakers.
  53. Each record is a dictionary from field names to values, and the fields are
  54. as follows::
  55. id speaker ID as defined in the original TIMIT speaker info table
  56. sex speaker gender (M:male, F:female)
  57. dr speaker dialect region (1:new england, 2:northern,
  58. 3:north midland, 4:south midland, 5:southern, 6:new york city,
  59. 7:western, 8:army brat (moved around))
  60. use corpus type (TRN:training, TST:test)
  61. in this sample corpus only TRN is available
  62. recdate recording date
  63. birthdate speaker birth date
  64. ht speaker height
  65. race speaker race (WHT:white, BLK:black, AMR:american indian,
  66. SPN:spanish-american, ORN:oriental,???:unknown)
  67. edu speaker education level (HS:high school, AS:associate degree,
  68. BS:bachelor's degree (BS or BA), MS:master's degree (MS or MA),
  69. PHD:doctorate degree (PhD,JD,MD), ??:unknown)
  70. comments comments by the recorder
  71. The 4 functions are as follows.
  72. - tokenized(sentences=items, offset=False)
  73. Given a list of items, returns an iterator of a list of word lists,
  74. each of which corresponds to an item (sentence). If offset is set to True,
  75. each element of the word list is a tuple of word(string), start offset and
  76. end offset, where offset is represented as a number of 16kHz samples.
  77. - phonetic(sentences=items, offset=False)
  78. Given a list of items, returns an iterator of a list of phoneme lists,
  79. each of which corresponds to an item (sentence). If offset is set to True,
  80. each element of the phoneme list is a tuple of word(string), start offset
  81. and end offset, where offset is represented as a number of 16kHz samples.
  82. - audiodata(item, start=0, end=None)
  83. Given an item, returns a chunk of audio samples formatted into a string.
  84. When the fuction is called, if start and end are omitted, the entire
  85. samples of the recording will be returned. If only end is omitted,
  86. samples from the start offset to the end of the recording will be returned.
  87. - play(data)
  88. Play the given audio samples. The audio samples can be obtained from the
  89. timit.audiodata function.
  90. """
  91. import sys
  92. import os
  93. import re
  94. import tempfile
  95. import time
  96. from nltk.tree import Tree
  97. from nltk.internals import import_from_stdlib
  98. from nltk.corpus.reader.util import *
  99. from nltk.corpus.reader.api import *
  100. class TimitCorpusReader(CorpusReader):
  101. """
  102. Reader for the TIMIT corpus (or any other corpus with the same
  103. file layout and use of file formats). The corpus root directory
  104. should contain the following files:
  105. - timitdic.txt: dictionary of standard transcriptions
  106. - spkrinfo.txt: table of speaker information
  107. In addition, the root directory should contain one subdirectory
  108. for each speaker, containing three files for each utterance:
  109. - <utterance-id>.txt: text content of utterances
  110. - <utterance-id>.wrd: tokenized text content of utterances
  111. - <utterance-id>.phn: phonetic transcription of utterances
  112. - <utterance-id>.wav: utterance sound file
  113. """
  114. _FILE_RE = r"(\w+-\w+/\w+\.(phn|txt|wav|wrd))|" + r"timitdic\.txt|spkrinfo\.txt"
  115. """A regexp matching fileids that are used by this corpus reader."""
  116. _UTTERANCE_RE = r"\w+-\w+/\w+\.txt"
  117. def __init__(self, root, encoding="utf8"):
  118. """
  119. Construct a new TIMIT corpus reader in the given directory.
  120. :param root: The root directory for this corpus.
  121. """
  122. # Ensure that wave files don't get treated as unicode data:
  123. if isinstance(encoding, str):
  124. encoding = [(".*\.wav", None), (".*", encoding)]
  125. CorpusReader.__init__(
  126. self, root, find_corpus_fileids(root, self._FILE_RE), encoding=encoding
  127. )
  128. self._utterances = [
  129. name[:-4] for name in find_corpus_fileids(root, self._UTTERANCE_RE)
  130. ]
  131. """A list of the utterance identifiers for all utterances in
  132. this corpus."""
  133. self._speakerinfo = None
  134. self._root = root
  135. self.speakers = sorted(set(u.split("/")[0] for u in self._utterances))
  136. def fileids(self, filetype=None):
  137. """
  138. Return a list of file identifiers for the files that make up
  139. this corpus.
  140. :param filetype: If specified, then ``filetype`` indicates that
  141. only the files that have the given type should be
  142. returned. Accepted values are: ``txt``, ``wrd``, ``phn``,
  143. ``wav``, or ``metadata``,
  144. """
  145. if filetype is None:
  146. return CorpusReader.fileids(self)
  147. elif filetype in ("txt", "wrd", "phn", "wav"):
  148. return ["%s.%s" % (u, filetype) for u in self._utterances]
  149. elif filetype == "metadata":
  150. return ["timitdic.txt", "spkrinfo.txt"]
  151. else:
  152. raise ValueError("Bad value for filetype: %r" % filetype)
  153. def utteranceids(
  154. self, dialect=None, sex=None, spkrid=None, sent_type=None, sentid=None
  155. ):
  156. """
  157. :return: A list of the utterance identifiers for all
  158. utterances in this corpus, or for the given speaker, dialect
  159. region, gender, sentence type, or sentence number, if
  160. specified.
  161. """
  162. if isinstance(dialect, str):
  163. dialect = [dialect]
  164. if isinstance(sex, str):
  165. sex = [sex]
  166. if isinstance(spkrid, str):
  167. spkrid = [spkrid]
  168. if isinstance(sent_type, str):
  169. sent_type = [sent_type]
  170. if isinstance(sentid, str):
  171. sentid = [sentid]
  172. utterances = self._utterances[:]
  173. if dialect is not None:
  174. utterances = [u for u in utterances if u[2] in dialect]
  175. if sex is not None:
  176. utterances = [u for u in utterances if u[4] in sex]
  177. if spkrid is not None:
  178. utterances = [u for u in utterances if u[:9] in spkrid]
  179. if sent_type is not None:
  180. utterances = [u for u in utterances if u[11] in sent_type]
  181. if sentid is not None:
  182. utterances = [u for u in utterances if u[10:] in spkrid]
  183. return utterances
  184. def transcription_dict(self):
  185. """
  186. :return: A dictionary giving the 'standard' transcription for
  187. each word.
  188. """
  189. _transcriptions = {}
  190. for line in self.open("timitdic.txt"):
  191. if not line.strip() or line[0] == ";":
  192. continue
  193. m = re.match(r"\s*(\S+)\s+/(.*)/\s*$", line)
  194. if not m:
  195. raise ValueError("Bad line: %r" % line)
  196. _transcriptions[m.group(1)] = m.group(2).split()
  197. return _transcriptions
  198. def spkrid(self, utterance):
  199. return utterance.split("/")[0]
  200. def sentid(self, utterance):
  201. return utterance.split("/")[1]
  202. def utterance(self, spkrid, sentid):
  203. return "%s/%s" % (spkrid, sentid)
  204. def spkrutteranceids(self, speaker):
  205. """
  206. :return: A list of all utterances associated with a given
  207. speaker.
  208. """
  209. return [
  210. utterance
  211. for utterance in self._utterances
  212. if utterance.startswith(speaker + "/")
  213. ]
  214. def spkrinfo(self, speaker):
  215. """
  216. :return: A dictionary mapping .. something.
  217. """
  218. if speaker in self._utterances:
  219. speaker = self.spkrid(speaker)
  220. if self._speakerinfo is None:
  221. self._speakerinfo = {}
  222. for line in self.open("spkrinfo.txt"):
  223. if not line.strip() or line[0] == ";":
  224. continue
  225. rec = line.strip().split(None, 9)
  226. key = "dr%s-%s%s" % (rec[2], rec[1].lower(), rec[0].lower())
  227. self._speakerinfo[key] = SpeakerInfo(*rec)
  228. return self._speakerinfo[speaker]
  229. def phones(self, utterances=None):
  230. return [
  231. line.split()[-1]
  232. for fileid in self._utterance_fileids(utterances, ".phn")
  233. for line in self.open(fileid)
  234. if line.strip()
  235. ]
  236. def phone_times(self, utterances=None):
  237. """
  238. offset is represented as a number of 16kHz samples!
  239. """
  240. return [
  241. (line.split()[2], int(line.split()[0]), int(line.split()[1]))
  242. for fileid in self._utterance_fileids(utterances, ".phn")
  243. for line in self.open(fileid)
  244. if line.strip()
  245. ]
  246. def words(self, utterances=None):
  247. return [
  248. line.split()[-1]
  249. for fileid in self._utterance_fileids(utterances, ".wrd")
  250. for line in self.open(fileid)
  251. if line.strip()
  252. ]
  253. def word_times(self, utterances=None):
  254. return [
  255. (line.split()[2], int(line.split()[0]), int(line.split()[1]))
  256. for fileid in self._utterance_fileids(utterances, ".wrd")
  257. for line in self.open(fileid)
  258. if line.strip()
  259. ]
  260. def sents(self, utterances=None):
  261. return [
  262. [line.split()[-1] for line in self.open(fileid) if line.strip()]
  263. for fileid in self._utterance_fileids(utterances, ".wrd")
  264. ]
  265. def sent_times(self, utterances=None):
  266. return [
  267. (
  268. line.split(None, 2)[-1].strip(),
  269. int(line.split()[0]),
  270. int(line.split()[1]),
  271. )
  272. for fileid in self._utterance_fileids(utterances, ".txt")
  273. for line in self.open(fileid)
  274. if line.strip()
  275. ]
  276. def phone_trees(self, utterances=None):
  277. if utterances is None:
  278. utterances = self._utterances
  279. if isinstance(utterances, str):
  280. utterances = [utterances]
  281. trees = []
  282. for utterance in utterances:
  283. word_times = self.word_times(utterance)
  284. phone_times = self.phone_times(utterance)
  285. sent_times = self.sent_times(utterance)
  286. while sent_times:
  287. (sent, sent_start, sent_end) = sent_times.pop(0)
  288. trees.append(Tree("S", []))
  289. while (
  290. word_times and phone_times and phone_times[0][2] <= word_times[0][1]
  291. ):
  292. trees[-1].append(phone_times.pop(0)[0])
  293. while word_times and word_times[0][2] <= sent_end:
  294. (word, word_start, word_end) = word_times.pop(0)
  295. trees[-1].append(Tree(word, []))
  296. while phone_times and phone_times[0][2] <= word_end:
  297. trees[-1][-1].append(phone_times.pop(0)[0])
  298. while phone_times and phone_times[0][2] <= sent_end:
  299. trees[-1].append(phone_times.pop(0)[0])
  300. return trees
  301. # [xx] NOTE: This is currently broken -- we're assuming that the
  302. # fileids are WAV fileids (aka RIFF), but they're actually NIST SPHERE
  303. # fileids.
  304. def wav(self, utterance, start=0, end=None):
  305. # nltk.chunk conflicts with the stdlib module 'chunk'
  306. wave = import_from_stdlib("wave")
  307. w = wave.open(self.open(utterance + ".wav"), "rb")
  308. if end is None:
  309. end = w.getnframes()
  310. # Skip past frames before start, then read the frames we want
  311. w.readframes(start)
  312. frames = w.readframes(end - start)
  313. # Open a new temporary file -- the wave module requires
  314. # an actual file, and won't work w/ stringio. :(
  315. tf = tempfile.TemporaryFile()
  316. out = wave.open(tf, "w")
  317. # Write the parameters & data to the new file.
  318. out.setparams(w.getparams())
  319. out.writeframes(frames)
  320. out.close()
  321. # Read the data back from the file, and return it. The
  322. # file will automatically be deleted when we return.
  323. tf.seek(0)
  324. return tf.read()
  325. def audiodata(self, utterance, start=0, end=None):
  326. assert end is None or end > start
  327. headersize = 44
  328. if end is None:
  329. data = self.open(utterance + ".wav").read()
  330. else:
  331. data = self.open(utterance + ".wav").read(headersize + end * 2)
  332. return data[headersize + start * 2 :]
  333. def _utterance_fileids(self, utterances, extension):
  334. if utterances is None:
  335. utterances = self._utterances
  336. if isinstance(utterances, str):
  337. utterances = [utterances]
  338. return ["%s%s" % (u, extension) for u in utterances]
  339. def play(self, utterance, start=0, end=None):
  340. """
  341. Play the given audio sample.
  342. :param utterance: The utterance id of the sample to play
  343. """
  344. # Method 1: os audio dev.
  345. try:
  346. import ossaudiodev
  347. try:
  348. dsp = ossaudiodev.open("w")
  349. dsp.setfmt(ossaudiodev.AFMT_S16_LE)
  350. dsp.channels(1)
  351. dsp.speed(16000)
  352. dsp.write(self.audiodata(utterance, start, end))
  353. dsp.close()
  354. except IOError as e:
  355. print(
  356. (
  357. "can't acquire the audio device; please "
  358. "activate your audio device."
  359. ),
  360. file=sys.stderr,
  361. )
  362. print("system error message:", str(e), file=sys.stderr)
  363. return
  364. except ImportError:
  365. pass
  366. # Method 2: pygame
  367. try:
  368. # FIXME: this won't work under python 3
  369. import pygame.mixer, StringIO
  370. pygame.mixer.init(16000)
  371. f = StringIO.StringIO(self.wav(utterance, start, end))
  372. pygame.mixer.Sound(f).play()
  373. while pygame.mixer.get_busy():
  374. time.sleep(0.01)
  375. return
  376. except ImportError:
  377. pass
  378. # Method 3: complain. :)
  379. print(
  380. ("you must install pygame or ossaudiodev " "for audio playback."),
  381. file=sys.stderr,
  382. )
  383. class SpeakerInfo(object):
  384. def __init__(
  385. self, id, sex, dr, use, recdate, birthdate, ht, race, edu, comments=None
  386. ):
  387. self.id = id
  388. self.sex = sex
  389. self.dr = dr
  390. self.use = use
  391. self.recdate = recdate
  392. self.birthdate = birthdate
  393. self.ht = ht
  394. self.race = race
  395. self.edu = edu
  396. self.comments = comments
  397. def __repr__(self):
  398. attribs = "id sex dr use recdate birthdate ht race edu comments"
  399. args = ["%s=%r" % (attr, getattr(self, attr)) for attr in attribs.split()]
  400. return "SpeakerInfo(%s)" % (", ".join(args))
  401. def read_timit_block(stream):
  402. """
  403. Block reader for timit tagged sentences, which are preceded by a sentence
  404. number that will be ignored.
  405. """
  406. line = stream.readline()
  407. if not line:
  408. return []
  409. n, sent = line.split(" ", 1)
  410. return [sent]