These modules aren't used here.
[pyTivo/wmcbrine/lucasnz.git] / metadata.py
blob6eb5276f21102a9cfd5bf244b7519ffa10caa150
1 #!/usr/bin/env python
3 import hashlib
4 import logging
5 import os
6 import struct
7 import subprocess
8 import sys
9 from datetime import datetime
10 from xml.dom import minidom
11 from xml.parsers import expat
12 try:
13 import plistlib
14 except:
15 pass
17 import mutagen
18 from lrucache import LRUCache
20 import config
21 import plugins.video.transcode
22 import turing
24 # Something to strip
25 TRIBUNE_CR = ' Copyright Tribune Media Services, Inc.'
27 TV_RATINGS = {'TV-Y7': 1, 'TV-Y': 2, 'TV-G': 3, 'TV-PG': 4, 'TV-14': 5,
28 'TV-MA': 6, 'TV-NR': 7, 'TVY7': 1, 'TVY': 2, 'TVG': 3,
29 'TVPG': 4, 'TV14': 5, 'TVMA': 6, 'TVNR': 7, 'Y7': 1,
30 'Y': 2, 'G': 3, 'PG': 4, '14': 5, 'MA': 6, 'NR': 7,
31 'UNRATED': 7, 'X1': 1, 'X2': 2, 'X3': 3, 'X4': 4, 'X5': 5,
32 'X6': 6, 'X7': 7}
34 MPAA_RATINGS = {'G': 1, 'PG': 2, 'PG-13': 3, 'PG13': 3, 'R': 4, 'X': 5,
35 'NC-17': 6, 'NC17': 6, 'NR': 8, 'UNRATED': 8, 'G1': 1,
36 'P2': 2, 'P3': 3, 'R4': 4, 'X5': 5, 'N6': 6, 'N8': 8}
38 STAR_RATINGS = {'1': 1, '1.5': 2, '2': 3, '2.5': 4, '3': 5, '3.5': 6,
39 '4': 7, '*': 1, '**': 3, '***': 5, '****': 7, 'X1': 1,
40 'X2': 2, 'X3': 3, 'X4': 4, 'X5': 5, 'X6': 6, 'X7': 7}
42 HUMAN = {'mpaaRating': {1: 'G', 2: 'PG', 3: 'PG-13', 4: 'R', 5: 'X',
43 6: 'NC-17', 8: 'NR'},
44 'tvRating': {1: 'Y7', 2: 'Y', 3: 'G', 4: 'PG', 5: '14',
45 6: 'MA', 7: 'NR'},
46 'starRating': {1: '1', 2: '1.5', 3: '2', 4: '2.5', 5: '3',
47 6: '3.5', 7: '4'}}
49 BOM = '\xef\xbb\xbf'
51 GB = 1024 ** 3
52 MB = 1024 ** 2
53 KB = 1024
55 tivo_cache = LRUCache(50)
56 mp4_cache = LRUCache(50)
57 dvrms_cache = LRUCache(50)
58 nfo_cache = LRUCache(50)
60 mswindows = (sys.platform == "win32")
62 def get_mpaa(rating):
63 return HUMAN['mpaaRating'].get(rating, 'NR')
65 def get_tv(rating):
66 return HUMAN['tvRating'].get(rating, 'NR')
68 def get_stars(rating):
69 return HUMAN['starRating'].get(rating, '')
71 def human_size(raw):
72 raw = float(raw)
73 if raw > GB:
74 tsize = '%.2f GB' % (raw / GB)
75 elif raw > MB:
76 tsize = '%.2f MB' % (raw / MB)
77 elif raw > KB:
78 tsize = '%.2f KB' % (raw / KB)
79 else:
80 tsize = '%d Bytes' % raw
81 return tsize
83 def tag_data(element, tag):
84 for name in tag.split('/'):
85 found = False
86 for new_element in element.childNodes:
87 if new_element.nodeName == name:
88 found = True
89 element = new_element
90 break
91 if not found:
92 return ''
93 if not element.firstChild:
94 return ''
95 return element.firstChild.data
97 def _vtag_data(element, tag):
98 for name in tag.split('/'):
99 new_element = element.getElementsByTagName(name)
100 if not new_element:
101 return []
102 element = new_element[0]
103 elements = element.getElementsByTagName('element')
104 return [x.firstChild.data for x in elements if x.firstChild]
106 def _vtag_data_alternate(element, tag):
107 elements = [element]
108 for name in tag.split('/'):
109 new_elements = []
110 for elmt in elements:
111 new_elements += elmt.getElementsByTagName(name)
112 elements = new_elements
113 return [x.firstChild.data for x in elements if x.firstChild]
115 def _tag_value(element, tag):
116 item = element.getElementsByTagName(tag)
117 if item:
118 value = item[0].attributes['value'].value
119 return int(value[0])
121 def from_moov(full_path):
122 if full_path in mp4_cache:
123 return mp4_cache[full_path]
125 metadata = {}
126 len_desc = 0
128 try:
129 mp4meta = mutagen.File(unicode(full_path, 'utf-8'))
130 assert(mp4meta)
131 except:
132 mp4_cache[full_path] = {}
133 return {}
135 # The following 1-to-1 correspondence of atoms to pyTivo
136 # variables is TV-biased
137 keys = {'tvnn': 'callsign', 'tven': 'episodeNumber',
138 'tvsh': 'seriesTitle'}
140 for key, value in mp4meta.items():
141 if type(value) == list:
142 value = value[0]
143 if key == 'stik':
144 metadata['isEpisode'] = ['false', 'true'][value == 'TV Show']
145 elif key in keys:
146 metadata[keys[key]] = value
147 # These keys begin with the copyright symbol \xA9
148 elif key == '\xa9day':
149 if len(value) == 4:
150 value += '-01-01T16:00:00Z'
151 metadata['originalAirDate'] = value
152 #metadata['time'] = value
153 elif key in ['\xa9gen', 'gnre']:
154 for k in ('vProgramGenre', 'vSeriesGenre'):
155 if k in metadata:
156 metadata[k].append(value)
157 else:
158 metadata[k] = [value]
159 elif key == '\xa9nam':
160 if 'tvsh' in mp4meta:
161 metadata['episodeTitle'] = value
162 else:
163 metadata['title'] = value
165 # Description in desc, cmt, and/or ldes tags. Keep the longest.
166 elif key in ['desc', '\xa9cmt', 'ldes'] and len(value) > len_desc:
167 metadata['description'] = value
168 len_desc = len(value)
170 # A common custom "reverse DNS format" tag
171 elif (key == '----:com.apple.iTunes:iTunEXTC' and
172 ('us-tv' in value or 'mpaa' in value)):
173 rating = value.split("|")[1].upper()
174 if rating in TV_RATINGS and 'us-tv' in value:
175 metadata['tvRating'] = TV_RATINGS[rating]
176 elif rating in MPAA_RATINGS and 'mpaa' in value:
177 metadata['mpaaRating'] = MPAA_RATINGS[rating]
179 # Actors, directors, producers, AND screenwriters may be in a long
180 # embedded XML plist.
181 elif (key == '----:com.apple.iTunes:iTunMOVI' and
182 'plistlib' in sys.modules):
183 items = {'cast': 'vActor', 'directors': 'vDirector',
184 'producers': 'vProducer', 'screenwriters': 'vWriter'}
185 try:
186 data = plistlib.readPlistFromString(value)
187 except:
188 pass
189 else:
190 for item in items:
191 if item in data:
192 metadata[items[item]] = [x['name'] for x in data[item]]
194 mp4_cache[full_path] = metadata
195 return metadata
197 def from_mscore(rawmeta):
198 metadata = {}
199 keys = {'title': ['Title'],
200 'description': ['Description', 'WM/SubTitleDescription'],
201 'episodeTitle': ['WM/SubTitle'],
202 'callsign': ['WM/MediaStationCallSign'],
203 'displayMajorNumber': ['WM/MediaOriginalChannel'],
204 'originalAirDate': ['WM/MediaOriginalBroadcastDateTime'],
205 'rating': ['WM/ParentalRating'],
206 'credits': ['WM/MediaCredits'], 'genre': ['WM/Genre']}
208 for tagname in keys:
209 for tag in keys[tagname]:
210 try:
211 if tag in rawmeta:
212 value = rawmeta[tag][0]
213 if type(value) not in (str, unicode):
214 value = str(value)
215 if value:
216 metadata[tagname] = value
217 except:
218 pass
220 if 'episodeTitle' in metadata and 'title' in metadata:
221 metadata['seriesTitle'] = metadata['title']
222 if 'genre' in metadata:
223 value = metadata['genre'].split(',')
224 metadata['vProgramGenre'] = value
225 metadata['vSeriesGenre'] = value
226 del metadata['genre']
227 if 'credits' in metadata:
228 value = [x.split('/') for x in metadata['credits'].split(';')]
229 if len(value) > 3:
230 metadata['vActor'] = [x for x in (value[0] + value[3]) if x]
231 metadata['vDirector'] = [x for x in value[1] if x]
232 del metadata['credits']
233 if 'rating' in metadata:
234 rating = metadata['rating']
235 if rating in TV_RATINGS:
236 metadata['tvRating'] = TV_RATINGS[rating]
237 del metadata['rating']
239 return metadata
241 def from_dvrms(full_path):
242 if full_path in dvrms_cache:
243 return dvrms_cache[full_path]
245 try:
246 rawmeta = mutagen.File(unicode(full_path, 'utf-8'))
247 assert(rawmeta)
248 except:
249 dvrms_cache[full_path] = {}
250 return {}
252 metadata = from_mscore(rawmeta)
253 dvrms_cache[full_path] = metadata
254 return metadata
256 def from_eyetv(full_path):
257 keys = {'TITLE': 'title', 'SUBTITLE': 'episodeTitle',
258 'DESCRIPTION': 'description', 'YEAR': 'movieYear',
259 'EPISODENUM': 'episodeNumber'}
260 metadata = {}
261 path = os.path.dirname(unicode(full_path, 'utf-8'))
262 eyetvp = [x for x in os.listdir(path) if x.endswith('.eyetvp')][0]
263 eyetvp = os.path.join(path, eyetvp)
264 try:
265 eyetv = plistlib.readPlist(eyetvp)
266 except:
267 return metadata
268 if 'epg info' in eyetv:
269 info = eyetv['epg info']
270 for key in keys:
271 if info[key]:
272 metadata[keys[key]] = info[key]
273 if info['SUBTITLE']:
274 metadata['seriesTitle'] = info['TITLE']
275 if info['ACTORS']:
276 metadata['vActor'] = [x.strip() for x in info['ACTORS'].split(',')]
277 if info['DIRECTOR']:
278 metadata['vDirector'] = [info['DIRECTOR']]
280 for ptag, etag, ratings in [('tvRating', 'TV_RATING', TV_RATINGS),
281 ('mpaaRating', 'MPAA_RATING', MPAA_RATINGS),
282 ('starRating', 'STAR_RATING', STAR_RATINGS)]:
283 x = info[etag].upper()
284 if x and x in ratings:
285 metadata[ptag] = ratings[x]
287 # movieYear must be set for the mpaa/star ratings to work
288 if (('mpaaRating' in metadata or 'starRating' in metadata) and
289 'movieYear' not in metadata):
290 metadata['movieYear'] = eyetv['info']['start'].year
291 return metadata
293 def from_text(full_path):
294 metadata = {}
295 full_path = unicode(full_path, 'utf-8')
296 path, name = os.path.split(full_path)
297 title, ext = os.path.splitext(name)
299 search_paths = []
300 ptmp = full_path
301 while ptmp:
302 parent = os.path.dirname(ptmp)
303 if ptmp != parent:
304 ptmp = parent
305 else:
306 break
307 search_paths.append(os.path.join(ptmp, 'default.txt'))
309 search_paths.append(os.path.join(path, title) + '.properties')
310 search_paths.reverse()
312 search_paths += [full_path + '.txt',
313 os.path.join(path, '.meta', 'default.txt'),
314 os.path.join(path, '.meta', name) + '.txt']
316 for metafile in search_paths:
317 if os.path.exists(metafile):
318 sep = ':='[metafile.endswith('.properties')]
319 for line in file(metafile, 'U'):
320 if line.startswith(BOM):
321 line = line[3:]
322 if line.strip().startswith('#') or not sep in line:
323 continue
324 key, value = [x.strip() for x in line.split(sep, 1)]
325 if not key or not value:
326 continue
327 if key.startswith('v'):
328 if key in metadata:
329 metadata[key].append(value)
330 else:
331 metadata[key] = [value]
332 else:
333 metadata[key] = value
335 for rating, ratings in [('tvRating', TV_RATINGS),
336 ('mpaaRating', MPAA_RATINGS),
337 ('starRating', STAR_RATINGS)]:
338 x = metadata.get(rating, '').upper()
339 if x in ratings:
340 metadata[rating] = ratings[x]
341 else:
342 try:
343 x = int(x)
344 metadata[rating] = x
345 except:
346 pass
348 return metadata
350 def basic(full_path):
351 base_path, name = os.path.split(full_path)
352 title, ext = os.path.splitext(name)
353 mtime = os.stat(unicode(full_path, 'utf-8')).st_mtime
354 if (mtime < 0):
355 mtime = 0
356 originalAirDate = datetime.utcfromtimestamp(mtime)
358 metadata = {'title': title,
359 'originalAirDate': originalAirDate.isoformat()}
360 ext = ext.lower()
361 if ext in ['.mp4', '.m4v', '.mov']:
362 metadata.update(from_moov(full_path))
363 elif ext in ['.dvr-ms', '.asf', '.wmv']:
364 metadata.update(from_dvrms(full_path))
365 elif 'plistlib' in sys.modules and base_path.endswith('.eyetv'):
366 metadata.update(from_eyetv(full_path))
367 metadata.update(from_nfo(full_path))
368 metadata.update(from_text(full_path))
370 return metadata
372 def from_container(xmldoc):
373 metadata = {}
375 keys = {'title': 'Title', 'episodeTitle': 'EpisodeTitle',
376 'description': 'Description', 'programId': 'ProgramId',
377 'seriesId': 'SeriesId', 'episodeNumber': 'EpisodeNumber',
378 'tvRating': 'TvRating', 'displayMajorNumber': 'SourceChannel',
379 'callsign': 'SourceStation', 'showingBits': 'ShowingBits',
380 'mpaaRating': 'MpaaRating'}
382 details = xmldoc.getElementsByTagName('Details')[0]
384 for key in keys:
385 data = tag_data(details, keys[key])
386 if data:
387 if key == 'description':
388 data = data.replace(TRIBUNE_CR, '')
389 elif key == 'tvRating':
390 data = int(data)
391 elif key == 'displayMajorNumber':
392 if '-' in data:
393 data, metadata['displayMinorNumber'] = data.split('-')
394 metadata[key] = data
396 return metadata
398 def from_details(xml):
399 metadata = {}
401 xmldoc = minidom.parseString(xml)
402 showing = xmldoc.getElementsByTagName('showing')[0]
403 program = showing.getElementsByTagName('program')[0]
405 items = {'description': 'program/description',
406 'title': 'program/title',
407 'episodeTitle': 'program/episodeTitle',
408 'episodeNumber': 'program/episodeNumber',
409 'programId': 'program/uniqueId',
410 'seriesId': 'program/series/uniqueId',
411 'seriesTitle': 'program/series/seriesTitle',
412 'originalAirDate': 'program/originalAirDate',
413 'isEpisode': 'program/isEpisode',
414 'movieYear': 'program/movieYear',
415 'partCount': 'partCount',
416 'partIndex': 'partIndex',
417 'time': 'time'}
419 for item in items:
420 data = tag_data(showing, items[item])
421 if data:
422 if item == 'description':
423 data = data.replace(TRIBUNE_CR, '')
424 metadata[item] = data
426 vItems = ['vActor', 'vChoreographer', 'vDirector',
427 'vExecProducer', 'vProgramGenre', 'vGuestStar',
428 'vHost', 'vProducer', 'vWriter']
430 for item in vItems:
431 data = _vtag_data(program, item)
432 if data:
433 metadata[item] = data
435 sb = showing.getElementsByTagName('showingBits')
436 if sb:
437 metadata['showingBits'] = sb[0].attributes['value'].value
439 #for tag in ['starRating', 'mpaaRating', 'colorCode']:
440 for tag in ['starRating', 'mpaaRating']:
441 value = _tag_value(program, tag)
442 if value:
443 metadata[tag] = value
445 rating = _tag_value(showing, 'tvRating')
446 if rating:
447 metadata['tvRating'] = rating
449 return metadata
451 def _nfo_vitems(source, metadata):
453 vItems = {'vGenre': 'genre',
454 'vWriter': 'credits',
455 'vDirector': 'director',
456 'vActor': 'actor/name'}
458 for key in vItems:
459 data = _vtag_data_alternate(source, vItems[key])
460 if data:
461 metadata.setdefault(key, [])
462 for dat in data:
463 if not dat in metadata[key]:
464 metadata[key].append(dat)
466 if 'vGenre' in metadata:
467 metadata['vSeriesGenre'] = metadata['vProgramGenre'] = metadata['vGenre']
469 return metadata
471 def _parse_nfo(nfo_path, nfo_data=None):
472 # nfo files can contain XML or a URL to seed the XBMC metadata scrapers
473 # It's also possible to have both (a URL after the XML metadata)
474 # pyTivo only parses the XML metadata, but we'll try to stip the URL
475 # from mixed XML/URL files. Returns `None` when XML can't be parsed.
476 if nfo_data is None:
477 nfo_data = [line.strip() for line in file(nfo_path, 'rU')]
478 xmldoc = None
479 try:
480 xmldoc = minidom.parseString(os.linesep.join(nfo_data))
481 except expat.ExpatError, err:
482 if expat.ErrorString(err.code) == expat.errors.XML_ERROR_INVALID_TOKEN:
483 # might be a URL outside the xml
484 while len(nfo_data) > err.lineno:
485 if len(nfo_data[-1]) == 0:
486 nfo_data.pop()
487 else:
488 break
489 if len(nfo_data) == err.lineno:
490 # last non-blank line contains the error
491 nfo_data.pop()
492 return _parse_nfo(nfo_path, nfo_data)
493 return xmldoc
495 def _from_tvshow_nfo(tvshow_nfo_path):
496 if tvshow_nfo_path in nfo_cache:
497 return nfo_cache[tvshow_nfo_path]
499 items = {'description': 'plot',
500 'title': 'title',
501 'seriesTitle': 'showtitle',
502 'starRating': 'rating',
503 'tvRating': 'mpaa'}
505 nfo_cache[tvshow_nfo_path] = metadata = {}
507 xmldoc = _parse_nfo(tvshow_nfo_path)
508 if not xmldoc:
509 return metadata
511 tvshow = xmldoc.getElementsByTagName('tvshow')
512 if tvshow:
513 tvshow = tvshow[0]
514 else:
515 return metadata
517 for item in items:
518 data = tag_data(tvshow, items[item])
519 if data:
520 metadata[item] = data
522 metadata = _nfo_vitems(tvshow, metadata)
524 nfo_cache[tvshow_nfo_path] = metadata
525 return metadata
527 def _from_episode_nfo(nfo_path, xmldoc):
528 metadata = {}
530 items = {'description': 'plot',
531 'episodeTitle': 'title',
532 'seriesTitle': 'showtitle',
533 'originalAirDate': 'aired',
534 'starRating': 'rating',
535 'tvRating': 'mpaa'}
537 # find tvshow.nfo
538 path = nfo_path
539 while True:
540 basepath = os.path.dirname(path)
541 if path == basepath:
542 break
543 path = basepath
544 tv_nfo = os.path.join(path, 'tvshow.nfo')
545 if os.path.exists(tv_nfo):
546 metadata.update(_from_tvshow_nfo(tv_nfo))
547 break
549 episode = xmldoc.getElementsByTagName('episodedetails')
550 if episode:
551 episode = episode[0]
552 else:
553 return metadata
555 metadata['isEpisode'] = 'true'
556 for item in items:
557 data = tag_data(episode, items[item])
558 if data:
559 metadata[item] = data
561 season = tag_data(episode, 'displayseason')
562 if not season or season == "-1":
563 season = tag_data(episode, 'season')
564 if not season:
565 season = 1
567 ep_num = tag_data(episode, 'displayepisode')
568 if not ep_num or ep_num == "-1":
569 ep_num = tag_data(episode, 'episode')
570 if ep_num and ep_num != "-1":
571 metadata['episodeNumber'] = "%d%02d" % (int(season), int(ep_num))
573 if 'originalAirDate' in metadata:
574 metadata['originalAirDate'] += 'T00:00:00Z'
576 metadata = _nfo_vitems(episode, metadata)
578 return metadata
580 def _from_movie_nfo(xmldoc):
581 metadata = {}
583 movie = xmldoc.getElementsByTagName('movie')
584 if movie:
585 movie = movie[0]
586 else:
587 return metadata
589 items = {'description': 'plot',
590 'title': 'title',
591 'movieYear': 'year',
592 'starRating': 'rating',
593 'mpaaRating': 'mpaa'}
595 metadata['isEpisode'] = 'false'
597 for item in items:
598 data = tag_data(movie, items[item])
599 if data:
600 metadata[item] = data
602 metadata['movieYear'] = "%04d" % int(metadata.get('movieYear', 0))
604 metadata = _nfo_vitems(movie, metadata)
605 return metadata
607 def from_nfo(full_path):
608 if full_path in nfo_cache:
609 return nfo_cache[full_path]
611 metadata = nfo_cache[full_path] = {}
613 nfo_path = "%s.nfo" % os.path.splitext(full_path)[0]
614 if not os.path.exists(nfo_path):
615 return metadata
617 xmldoc = _parse_nfo(nfo_path)
618 if not xmldoc:
619 return metadata
621 if xmldoc.getElementsByTagName('episodedetails'):
622 # it's an episode
623 metadata.update(_from_episode_nfo(nfo_path, xmldoc))
624 elif xmldoc.getElementsByTagName('movie'):
625 # it's a movie
626 metadata.update(_from_movie_nfo(xmldoc))
628 # common nfo cleanup
629 if 'starRating' in metadata:
630 # .NFO 0-10 -> TiVo 1-7
631 rating = int(float(metadata['starRating']) * 6 / 10 + 1.5)
632 metadata['starRating'] = rating
634 for key, mapping in [('mpaaRating', MPAA_RATINGS),
635 ('tvRating', TV_RATINGS)]:
636 if key in metadata:
637 rating = mapping.get(metadata[key], None)
638 if rating:
639 metadata[key] = str(rating)
640 else:
641 del metadata[key]
643 nfo_cache[full_path] = metadata
644 return metadata
646 def _tdcat_bin(tdcat_path, full_path, tivo_mak):
647 fname = unicode(full_path, 'utf-8')
648 if mswindows:
649 fname = fname.encode('iso8859-1')
650 tcmd = [tdcat_path, '-m', tivo_mak, '-2', fname]
651 tdcat = subprocess.Popen(tcmd, stdout=subprocess.PIPE)
652 return tdcat.stdout.read()
654 def _tdcat_py(full_path, tivo_mak):
655 xml_data = {}
657 tfile = open(full_path, 'rb')
658 header = tfile.read(16)
659 offset, chunks = struct.unpack('>LH', header[10:])
660 rawdata = tfile.read(offset - 16)
661 tfile.close()
663 count = 0
664 for i in xrange(chunks):
665 chunk_size, data_size, id, enc = struct.unpack('>LLHH',
666 rawdata[count:count + 12])
667 count += 12
668 data = rawdata[count:count + data_size]
669 xml_data[id] = {'enc': enc, 'data': data, 'start': count + 16}
670 count += chunk_size - 12
672 chunk = xml_data[2]
673 details = chunk['data']
674 if chunk['enc']:
675 xml_key = xml_data[3]['data']
677 hexmak = hashlib.md5('tivo:TiVo DVR:' + tivo_mak).hexdigest()
678 key = hashlib.sha1(hexmak + xml_key).digest()[:16] + '\0\0\0\0'
680 turkey = hashlib.sha1(key[:17]).digest()
681 turiv = hashlib.sha1(key).digest()
683 details = turing.Turing(turkey, turiv).crypt(details, chunk['start'])
685 return details
687 def from_tivo(full_path):
688 if full_path in tivo_cache:
689 return tivo_cache[full_path]
691 tdcat_path = config.get_bin('tdcat')
692 tivo_mak = config.get_server('tivo_mak')
693 try:
694 assert(tivo_mak)
695 if tdcat_path:
696 details = _tdcat_bin(tdcat_path, full_path, tivo_mak)
697 else:
698 details = _tdcat_py(full_path, tivo_mak)
699 metadata = from_details(details)
700 tivo_cache[full_path] = metadata
701 except:
702 raise
703 metadata = {}
705 return metadata
707 def force_utf8(text):
708 if type(text) == str:
709 try:
710 text = text.decode('utf8')
711 except:
712 if sys.platform == 'darwin':
713 text = text.decode('macroman')
714 else:
715 text = text.decode('iso8859-1')
716 return text.encode('utf-8')
718 def dump(output, metadata):
719 for key in metadata:
720 value = metadata[key]
721 if type(value) == list:
722 for item in value:
723 output.write('%s: %s\n' % (key, item.encode('utf-8')))
724 else:
725 if key in HUMAN and value in HUMAN[key]:
726 output.write('%s: %s\n' % (key, HUMAN[key][value]))
727 else:
728 output.write('%s: %s\n' % (key, value.encode('utf-8')))
730 if __name__ == '__main__':
731 if len(sys.argv) > 1:
732 metadata = {}
733 config.init([])
734 logging.basicConfig()
735 fname = force_utf8(sys.argv[1])
736 ext = os.path.splitext(fname)[1].lower()
737 if ext == '.tivo':
738 metadata.update(from_tivo(fname))
739 elif ext in ['.mp4', '.m4v', '.mov']:
740 metadata.update(from_moov(fname))
741 elif ext in ['.dvr-ms', '.asf', '.wmv']:
742 metadata.update(from_dvrms(fname))
743 elif ext == '.wtv':
744 vInfo = plugins.video.transcode.video_info(fname)
745 metadata.update(from_mscore(vInfo['rawmeta']))
746 dump(sys.stdout, metadata)