-
Notifications
You must be signed in to change notification settings - Fork 348
/
imdbpy2sql.py
executable file
·3068 lines (2809 loc) · 113 KB
/
imdbpy2sql.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""
imdbpy2sql.py script.
This script puts the data of the plain text data files into a
SQL database.
Copyright 2005-2016 Davide Alberani <da@erlug.linux.it>
2006 Giuseppe "Cowo" Corbelli <cowo --> lugbs.linux.it>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""
import os
import sys
import getopt
import time
import re
import warnings
import anydbm
from itertools import islice, chain
try:
from hashlib import md5
except ImportError:
from md5 import md5
from gzip import GzipFile
from types import UnicodeType
#from imdb.parser.sql.dbschema import *
from imdb.parser.sql.dbschema import dropTables, createTables, createIndexes
from imdb.parser.sql import soundex
from imdb.utils import analyze_title, analyze_name, date_and_notes, \
build_name, build_title, normalizeName, normalizeTitle, _articles, \
build_company_name, analyze_company_name, canonicalTitle
from imdb._exceptions import IMDbParserError, IMDbError
HELP = """imdbpy2sql.py usage:
%s -d /directory/with/PlainTextDataFiles/ -u URI [-c /directory/for/CSV_files] [-o sqlobject,sqlalchemy] [-i table,dbm] [--CSV-OPTIONS] [--COMPATIBILITY-OPTIONS]
# NOTE: URI is something along the line:
scheme://[user[:password]@]host[:port]/database[?parameters]
Examples:
mysql://user:password@host/database
postgres://user:password@host/database
sqlite:/tmp/imdb.db
sqlite:/C|/full/path/to/database
# NOTE: CSV mode (-c path):
A directory is used to store CSV files; on supported
database servers it should be really fast.
# NOTE: ORMs (-o orm):
Valid options are 'sqlobject', 'sqlalchemy' or the
preferred order separating the voices with a comma.
# NOTE: imdbIDs store/restore (-i method):
Valid options are 'table' (imdbIDs stored in a temporary
table of the database) or 'dbm' (imdbIDs stored on a dbm
file - this is the default if CSV is used).
# NOTE: --CSV-OPTIONS can be:
--csv-ext STRING files extension (.csv)
--csv-only-write exit after the CSV files are written.
--csv-only-load load an existing set of CSV files.
# NOTE: --COMPATIBILITY-OPTIONS can be one of:
--mysql-innodb insert data into a MySQL MyISAM db,
and then convert it to InnoDB.
--mysql-force-myisam force the creation of MyISAM tables.
--ms-sqlserver compatibility mode for Microsoft SQL Server
and SQL Express.
--sqlite-transactions uses transactions, to speed-up SQLite.
See README.sqldb for more information.
""" % sys.argv[0]
# Directory containing the IMDb's Plain Text Data Files.
IMDB_PTDF_DIR = None
# URI used to connect to the database.
URI = None
# ORM to use (list of options) and actually used (string).
USE_ORM = None
USED_ORM = None
# List of tables of the database.
DB_TABLES = []
# Max allowed recursion, inserting data.
MAX_RECURSION = 10
# Method used to (re)store imdbIDs.
IMDBIDS_METHOD = None
# If set, this directory is used to output CSV files.
CSV_DIR = None
CSV_CURS = None
CSV_ONLY_WRITE = False
CSV_ONLY_LOAD = False
CSV_EXT = '.csv'
CSV_EOL = '\n'
CSV_DELIMITER = ','
CSV_QUOTE = '"'
CSV_ESCAPE = '"'
CSV_NULL = 'NULL'
CSV_QUOTEINT = False
CSV_LOAD_SQL = None
CSV_MYSQL = "LOAD DATA LOCAL INFILE '%(file)s' INTO TABLE `%(table)s` FIELDS TERMINATED BY '%(delimiter)s' ENCLOSED BY '%(quote)s' ESCAPED BY '%(escape)s' LINES TERMINATED BY '%(eol)s'"
CSV_PGSQL = "COPY %(table)s FROM '%(file)s' WITH DELIMITER AS '%(delimiter)s' NULL AS '%(null)s' QUOTE AS '%(quote)s' ESCAPE AS '%(escape)s' CSV"
CSV_DB2 = "CALL SYSPROC.ADMIN_CMD('LOAD FROM %(file)s OF del MODIFIED BY lobsinfile INSERT INTO %(table)s')"
# Temporary fix for old style titles.
#FIX_OLD_STYLE_TITLES = True
# Store custom queries specified on the command line.
CUSTOM_QUERIES = {}
# Allowed time specification, for custom queries.
ALLOWED_TIMES = ('BEGIN', 'BEFORE_DROP', 'BEFORE_CREATE', 'AFTER_CREATE',
'BEFORE_MOVIES', 'BEFORE_COMPANIES', 'BEFORE_CAST',
'BEFORE_RESTORE', 'BEFORE_INDEXES', 'END', 'BEFORE_MOVIES_TODB',
'AFTER_MOVIES_TODB', 'BEFORE_PERSONS_TODB',
'AFTER_PERSONS_TODB','BEFORE_SQLDATA_TODB',
'AFTER_SQLDATA_TODB', 'BEFORE_AKAMOVIES_TODB',
'AFTER_AKAMOVIES_TODB', 'BEFORE_CHARACTERS_TODB',
'AFTER_CHARACTERS_TODB', 'BEFORE_COMPANIES_TODB',
'AFTER_COMPANIES_TODB', 'BEFORE_EVERY_TODB',
'AFTER_EVERY_TODB', 'BEFORE_CSV_LOAD', 'BEFORE_CSV_TODB',
'AFTER_CSV_TODB')
# Shortcuts for some compatibility options.
MYSQLFORCEMYISAM_OPTS = ['-e',
'AFTER_CREATE:FOR_EVERY_TABLE:ALTER TABLE %(table)s ENGINE=MyISAM;']
MYSQLINNODB_OPTS = ['-e',
'AFTER_CREATE:FOR_EVERY_TABLE:ALTER TABLE %(table)s ENGINE=MyISAM;',
'-e',
'BEFORE_INDEXES:FOR_EVERY_TABLE:ALTER TABLE %(table)s ENGINE=InnoDB;']
SQLSERVER_OPTS = ['-e', 'BEFORE_MOVIES_TODB:SET IDENTITY_INSERT %(table)s ON;',
'-e', 'AFTER_MOVIES_TODB:SET IDENTITY_INSERT %(table)s OFF;',
'-e', 'BEFORE_PERSONS_TODB:SET IDENTITY_INSERT %(table)s ON;',
'-e', 'AFTER_PERSONS_TODB:SET IDENTITY_INSERT %(table)s OFF;',
'-e', 'BEFORE_COMPANIES_TODB:SET IDENTITY_INSERT %(table)s ON;',
'-e', 'AFTER_COMPANIES_TODB:SET IDENTITY_INSERT %(table)s OFF;',
'-e', 'BEFORE_CHARACTERS_TODB:SET IDENTITY_INSERT %(table)s ON;',
'-e', 'AFTER_CHARACTERS_TODB:SET IDENTITY_INSERT %(table)s OFF;',
'-e', 'BEFORE_AKAMOVIES_TODB:SET IDENTITY_INSERT %(table)s ON;',
'-e', 'AFTER_AKAMOVIES_TODB:SET IDENTITY_INSERT %(table)s OFF;']
SQLITE_OPTS = ['-e', 'BEGIN:PRAGMA synchronous = OFF;',
'-e', 'BEFORE_EVERY_TODB:BEGIN TRANSACTION;',
'-e', 'AFTER_EVERY_TODB:COMMIT;',
'-e', 'BEFORE_INDEXES:BEGIN TRANSACTION;',
'e', 'END:COMMIT;']
if '--mysql-innodb' in sys.argv[1:]:
sys.argv += MYSQLINNODB_OPTS
if '--mysql-force-myisam' in sys.argv[1:]:
sys.argv += MYSQLFORCEMYISAM_OPTS
if '--ms-sqlserver' in sys.argv[1:]:
sys.argv += SQLSERVER_OPTS
if '--sqlite-transactions' in sys.argv[1:]:
sys.argv += SQLITE_OPTS
# Manage arguments list.
try:
optlist, args = getopt.getopt(sys.argv[1:], 'u:d:e:o:c:i:h',
['uri=', 'data=', 'execute=',
'mysql-innodb', 'ms-sqlserver',
'sqlite-transactions',
'fix-old-style-titles',
'mysql-force-myisam', 'orm',
'csv-only-write',
'csv-only-load',
'csv=', 'csv-ext=',
'imdbids=', 'help'])
except getopt.error, e:
print 'Troubles with arguments.'
print HELP
sys.exit(2)
for opt in optlist:
if opt[0] in ('-d', '--data'):
IMDB_PTDF_DIR = opt[1]
elif opt[0] in ('-u', '--uri'):
URI = opt[1]
elif opt[0] in ('-c', '--csv'):
CSV_DIR = opt[1]
elif opt[0] == '--csv-ext':
CSV_EXT = opt[1]
elif opt[0] in ('-i', '--imdbids'):
IMDBIDS_METHOD = opt[1]
elif opt[0] in ('-e', '--execute'):
if opt[1].find(':') == -1:
print 'WARNING: wrong command syntax: "%s"' % opt[1]
continue
when, cmd = opt[1].split(':', 1)
if when not in ALLOWED_TIMES:
print 'WARNING: unknown time: "%s"' % when
continue
if when == 'BEFORE_EVERY_TODB':
for nw in ('BEFORE_MOVIES_TODB', 'BEFORE_PERSONS_TODB',
'BEFORE_SQLDATA_TODB', 'BEFORE_AKAMOVIES_TODB',
'BEFORE_CHARACTERS_TODB', 'BEFORE_COMPANIES_TODB'):
CUSTOM_QUERIES.setdefault(nw, []).append(cmd)
elif when == 'AFTER_EVERY_TODB':
for nw in ('AFTER_MOVIES_TODB', 'AFTER_PERSONS_TODB',
'AFTER_SQLDATA_TODB', 'AFTER_AKAMOVIES_TODB',
'AFTER_CHARACTERS_TODB', 'AFTER_COMPANIES_TODB'):
CUSTOM_QUERIES.setdefault(nw, []).append(cmd)
else:
CUSTOM_QUERIES.setdefault(when, []).append(cmd)
elif opt[0] in ('-o', '--orm'):
USE_ORM = opt[1].split(',')
elif opt[0] == '--fix-old-style-titles':
warnings.warn('The --fix-old-style-titles argument is obsolete.')
elif opt[0] == '--csv-only-write':
CSV_ONLY_WRITE = True
elif opt[0] == '--csv-only-load':
CSV_ONLY_LOAD = True
elif opt[0] in ('-h', '--help'):
print HELP
sys.exit(0)
if IMDB_PTDF_DIR is None:
print 'You must supply the directory with the plain text data files'
print HELP
sys.exit(2)
if URI is None:
print 'You must supply the URI for the database connection'
print HELP
sys.exit(2)
if IMDBIDS_METHOD not in (None, 'dbm', 'table'):
print 'the method to (re)store imdbIDs must be one of "dbm" or "table"'
print HELP
sys.exit(2)
if (CSV_ONLY_WRITE or CSV_ONLY_LOAD) and not CSV_DIR:
print 'You must specify the CSV directory with the -c argument'
print HELP
sys.exit(3)
# Some warnings and notices.
URIlower = URI.lower()
if URIlower.startswith('mysql'):
if '--mysql-force-myisam' in sys.argv[1:] and \
'--mysql-innodb' in sys.argv[1:]:
print '\nWARNING: there is no sense in mixing the --mysql-innodb and\n'\
'--mysql-force-myisam command line options!\n'
elif '--mysql-innodb' in sys.argv[1:]:
print "\nNOTICE: you've specified the --mysql-innodb command line\n"\
"option; you should do this ONLY IF your system uses InnoDB\n"\
"tables or you really want to use InnoDB; if you're running\n"\
"a MyISAM-based database, please omit any option; if you\n"\
"want to force MyISAM usage on a InnoDB-based database,\n"\
"try the --mysql-force-myisam command line option, instead.\n"
elif '--mysql-force-myisam' in sys.argv[1:]:
print "\nNOTICE: you've specified the --mysql-force-myisam command\n"\
"line option; you should do this ONLY IF your system uses\n"\
"InnoDB tables and you want to use MyISAM tables, instead.\n"
else:
print "\nNOTICE: IF you're using InnoDB tables, data insertion can\n"\
"be very slow; you can switch to MyISAM tables - forcing it\n"\
"with the --mysql-force-myisam option - OR use the\n"\
"--mysql-innodb command line option, but DON'T USE these if\n"\
"you're already working on MyISAM tables, because it will\n"\
"force MySQL to use InnoDB, and performances will be poor.\n"
elif URIlower.startswith('mssql') and \
'--ms-sqlserver' not in sys.argv[1:]:
print "\nWARNING: you're using MS SQLServer without the --ms-sqlserver\n"\
"command line option: if something goes wrong, try using it.\n"
elif URIlower.startswith('sqlite') and \
'--sqlite-transactions' not in sys.argv[1:]:
print "\nWARNING: you're using SQLite without the --sqlite-transactions\n"\
"command line option: you'll have very poor performances! Try\n"\
"using it.\n"
if ('--mysql-force-myisam' in sys.argv[1:] and
not URIlower.startswith('mysql')) or ('--mysql-innodb' in
sys.argv[1:] and not URIlower.startswith('mysql')) or ('--ms-sqlserver'
in sys.argv[1:] and not URIlower.startswith('mssql')) or \
('--sqlite-transactions' in sys.argv[1:] and
not URIlower.startswith('sqlite')):
print "\nWARNING: you've specified command line options that don't\n"\
"belong to the database server you're using: proceed at your\n"\
"own risk!\n"
if CSV_DIR:
if URIlower.startswith('mysql'):
CSV_LOAD_SQL = CSV_MYSQL
elif URIlower.startswith('postgres'):
CSV_LOAD_SQL = CSV_PGSQL
elif URIlower.startswith('ibm'):
CSV_LOAD_SQL = CSV_DB2
CSV_NULL = ''
else:
print "\nERROR: importing CSV files is not supported for this database"
sys.exit(3)
if USE_ORM is None:
USE_ORM = ('sqlobject', 'sqlalchemy')
if not isinstance(USE_ORM, (tuple, list)):
USE_ORM = [USE_ORM]
nrMods = len(USE_ORM)
_gotError = False
for idx, mod in enumerate(USE_ORM):
mod = mod.lower()
try:
if mod == 'sqlalchemy':
from imdb.parser.sql.alchemyadapter import getDBTables, setConnection
elif mod == 'sqlobject':
from imdb.parser.sql.objectadapter import getDBTables, setConnection
else:
warnings.warn('unknown module "%s".' % mod)
continue
DB_TABLES = getDBTables(URI)
for t in DB_TABLES:
globals()[t._imdbpyName] = t
if _gotError:
warnings.warn('falling back to "%s".' % mod)
USED_ORM = mod
break
except ImportError, e:
if idx+1 >= nrMods:
raise IMDbError('unable to use any ORM in %s: %s' % (
str(USE_ORM), str(e)))
else:
warnings.warn('unable to use "%s": %s' % (mod, str(e)))
_gotError = True
continue
else:
raise IMDbError('unable to use any ORM in %s' % str(USE_ORM))
#-----------------------
# CSV Handling.
class CSVCursor(object):
"""Emulate a cursor object, but instead it writes data to a set
of CSV files."""
def __init__(self, csvDir, csvExt=CSV_EXT, csvEOL=CSV_EOL,
delimeter=CSV_DELIMITER, quote=CSV_QUOTE, escape=CSV_ESCAPE,
null=CSV_NULL, quoteInteger=CSV_QUOTEINT):
"""Initialize a CSVCursor object; csvDir is the directory where the
CSV files will be stored."""
self.csvDir = csvDir
self.csvExt = csvExt
self.csvEOL = csvEOL
self.delimeter = delimeter
self.quote = quote
self.escape = escape
self.escaped = '%s%s' % (escape, quote)
self.null = null
self.quoteInteger = quoteInteger
self._fdPool = {}
self._lobFDPool = {}
self._counters = {}
def buildLine(self, items, tableToAddID=False, rawValues=(),
lobFD=None, lobFN=None):
"""Build a single text line for a set of information."""
# FIXME: there are too many special cases to handle, and that
# affects performances: management of LOB files, at least,
# must be moved away from here.
quote = self.quote
null = self.null
escaped = self.escaped
quoteInteger = self.quoteInteger
if not tableToAddID:
r = []
else:
_counters = self._counters
r = [_counters[tableToAddID]]
_counters[tableToAddID] += 1
r += list(items)
for idx, val in enumerate(r):
if val is None:
r[idx] = null
continue
if (not quoteInteger) and isinstance(val, (int, long)):
r[idx] = str(val)
continue
if lobFD and idx == 3:
continue
val = str(val)
if quote:
val = '%s%s%s' % (quote, val.replace(quote, escaped), quote)
r[idx] = val
# Add RawValue(s), if present.
rinsert = r.insert
if tableToAddID:
shift = 1
else:
shift = 0
for idx, item in rawValues:
rinsert(idx + shift, item)
if lobFD:
# XXX: totally tailored to suit person_info.info column!
val3 = r[3]
val3len = len(val3 or '') or -1
if val3len == -1:
val3off = 0
else:
val3off = lobFD.tell()
r[3] = '%s.%d.%d/' % (lobFN, val3off, val3len)
lobFD.write(val3)
# Build the line and add the end-of-line.
return '%s%s' % (self.delimeter.join(r), self.csvEOL)
def executemany(self, sqlstr, items):
"""Emulate the executemany method of a cursor, but writes the
data in a set of CSV files."""
# XXX: find a safer way to get the table/file name!
tName = sqlstr.split()[2]
lobFD = None
lobFN = None
doLOB = False
# XXX: ugly special case, to create the LOB file.
if URIlower.startswith('ibm') and tName == 'person_info':
doLOB = True
# Open the file descriptor or get it from the pool.
if tName in self._fdPool:
tFD = self._fdPool[tName]
lobFD = self._lobFDPool.get(tName)
lobFN = getattr(lobFD, 'name', None)
if lobFN:
lobFN = os.path.basename(lobFN)
else:
tFD = open(os.path.join(CSV_DIR, tName + self.csvExt), 'wb')
self._fdPool[tName] = tFD
if doLOB:
lobFN = '%s.lob' % tName
lobFD = open(os.path.join(CSV_DIR, lobFN), 'wb')
self._lobFDPool[tName] = lobFD
buildLine = self.buildLine
tableToAddID = False
if tName in ('cast_info', 'movie_info', 'person_info',
'movie_companies', 'movie_link', 'aka_name',
'complete_cast', 'movie_info_idx', 'movie_keyword'):
tableToAddID = tName
if tName not in self._counters:
self._counters[tName] = 1
# Identify if there are RawValue in the VALUES (...) portion of
# the query.
parIdx = sqlstr.rfind('(')
rawValues = []
vals = sqlstr[parIdx+1:-1]
if parIdx != 0:
vals = sqlstr[parIdx+1:-1]
for idx, item in enumerate(vals.split(', ')):
if item[0] in ('%', '?', ':'):
continue
rawValues.append((idx, item))
# Write these lines.
tFD.writelines(buildLine(i, tableToAddID=tableToAddID,
rawValues=rawValues, lobFD=lobFD, lobFN=lobFN)
for i in items)
# Flush to disk, so that no truncaded entries are ever left.
# XXX: is this a good idea?
tFD.flush()
def fileNames(self):
"""Return the list of file names."""
return [fd.name for fd in self._fdPool.values()]
def buildFakeFileNames(self):
"""Populate the self._fdPool dictionary with fake objects
taking file names from the content of the self.csvDir directory."""
class _FakeFD(object): pass
for fname in os.listdir(self.csvDir):
if not fname.endswith(CSV_EXT):
continue
fpath = os.path.join(self.csvDir, fname)
if not os.path.isfile(fpath):
continue
fd = _FakeFD()
fd.name = fname
self._fdPool[fname[:-len(CSV_EXT)]] = fd
def close(self, tName):
"""Close a given table/file."""
if tName in self._fdPool:
self._fdPool[tName].close()
def closeAll(self):
"""Close all open file descriptors."""
for fd in self._fdPool.values():
fd.close()
for fd in self._lobFDPool.values():
fd.close()
def loadCSVFiles():
"""Load every CSV file into the database."""
CSV_REPL = {'quote': CSV_QUOTE, 'delimiter': CSV_DELIMITER,
'escape': CSV_ESCAPE, 'null': CSV_NULL, 'eol': CSV_EOL}
for fName in CSV_CURS.fileNames():
connectObject.commit()
tName = os.path.basename(fName[:-len(CSV_EXT)])
cfName = os.path.join(CSV_DIR, fName)
CSV_REPL['file'] = cfName
CSV_REPL['table'] = tName
sqlStr = CSV_LOAD_SQL % CSV_REPL
print ' * LOADING CSV FILE %s...' % cfName
sys.stdout.flush()
executeCustomQueries('BEFORE_CSV_TODB')
try:
CURS.execute(sqlStr)
try:
res = CURS.fetchall()
if res:
print 'LOADING OUTPUT:', res
except:
pass
except Exception, e:
print 'ERROR: unable to import CSV file %s: %s' % (cfName, str(e))
continue
connectObject.commit()
executeCustomQueries('AFTER_CSV_TODB')
#-----------------------
conn = setConnection(URI, DB_TABLES)
if CSV_DIR:
# Go for a CSV ride...
CSV_CURS = CSVCursor(CSV_DIR)
# Extract exceptions to trap.
try:
OperationalError = conn.module.OperationalError
except AttributeError, e:
warnings.warn('Unable to import OperationalError; report this as a bug, ' \
'since it will mask important exceptions: %s' % e)
OperationalError = Exception
try:
IntegrityError = conn.module.IntegrityError
except AttributeError, e:
warnings.warn('Unable to import IntegrityError')
IntegrityError = Exception
connectObject = conn.getConnection()
# XXX: fix for a problem that should be fixed in objectadapter.py (see it).
if URI and URI.startswith('sqlite') and USED_ORM == 'sqlobject':
major = sys.version_info[0]
minor = sys.version_info[1]
if major > 2 or (major == 2 and minor > 5):
connectObject.text_factory = str
# Cursor object.
CURS = connectObject.cursor()
# Name of the database and style of the parameters.
DB_NAME = conn.dbName
PARAM_STYLE = conn.paramstyle
def _get_imdbids_method():
"""Return the method to be used to (re)store
imdbIDs (one of 'dbm' or 'table')."""
if IMDBIDS_METHOD:
return IMDBIDS_METHOD
if CSV_DIR:
return 'dbm'
return 'table'
def tableName(table):
"""Return a string with the name of the table in the current db."""
return table.sqlmeta.table
def colName(table, column):
"""Return a string with the name of the column in the current db."""
if column == 'id':
return table.sqlmeta.idName
return table.sqlmeta.columns[column].dbName
class RawValue(object):
"""String-like objects to store raw SQL parameters, that are not
intended to be replaced with positional parameters, in the query."""
def __init__(self, s, v):
self.string = s
self.value = v
def __str__(self):
return self.string
def _makeConvNamed(cols):
"""Return a function to be used to convert a list of parameters
from positional style to named style (convert from a list of
tuples to a list of dictionaries."""
nrCols = len(cols)
def _converter(params):
for paramIndex, paramSet in enumerate(params):
d = {}
for i in xrange(nrCols):
d[cols[i]] = paramSet[i]
params[paramIndex] = d
return params
return _converter
def createSQLstr(table, cols, command='INSERT'):
"""Given a table and a list of columns returns a sql statement
useful to insert a set of data in the database.
Along with the string, also a function useful to convert parameters
from positional to named style is returned."""
sqlstr = '%s INTO %s ' % (command, tableName(table))
colNames = []
values = []
convCols = []
count = 1
def _valStr(s, index):
if DB_NAME in ('mysql', 'postgres'): return '%s'
elif PARAM_STYLE == 'format': return '%s'
elif PARAM_STYLE == 'qmark': return '?'
elif PARAM_STYLE == 'numeric': return ':%s' % index
elif PARAM_STYLE == 'named': return ':%s' % s
elif PARAM_STYLE == 'pyformat': return '%(' + s + ')s'
return '%s'
for col in cols:
if isinstance(col, RawValue):
colNames.append(colName(table, col.string))
values.append(str(col.value))
elif col == 'id':
colNames.append(table.sqlmeta.idName)
values.append(_valStr('id', count))
convCols.append(col)
count += 1
else:
colNames.append(colName(table, col))
values.append(_valStr(col, count))
convCols.append(col)
count += 1
sqlstr += '(%s) ' % ', '.join(colNames)
sqlstr += 'VALUES (%s)' % ', '.join(values)
if DB_NAME not in ('mysql', 'postgres') and \
PARAM_STYLE in ('named', 'pyformat'):
converter = _makeConvNamed(convCols)
else:
# Return the list itself.
converter = lambda x: x
return sqlstr, converter
def _(s, truncateAt=None):
"""Nicely print a string to sys.stdout, optionally
truncating it a the given char."""
if not isinstance(s, UnicodeType):
s = unicode(s, 'utf_8')
if truncateAt is not None:
s = s[:truncateAt]
s = s.encode(sys.stdout.encoding or 'utf_8', 'replace')
return s
if not hasattr(os, 'times'):
def times():
"""Fake times() function."""
return 0.0, 0.0, 0.0, 0.0, 0.0
os.times = times
# Show time consumed by the single function call.
CTIME = int(time.time())
BEGIN_TIME = CTIME
CTIMES = os.times()
BEGIN_TIMES = CTIMES
def _minSec(*t):
"""Return a tuple of (mins, secs, ...) - two for every item passed."""
l = []
for i in t:
l.extend(divmod(int(i), 60))
return tuple(l)
def t(s, sinceBegin=False):
"""Pretty-print timing information."""
global CTIME, CTIMES
nt = int(time.time())
ntimes = os.times()
if not sinceBegin:
ct = CTIME
cts = CTIMES
else:
ct = BEGIN_TIME
cts = BEGIN_TIMES
print '# TIME', s, \
': %dmin, %dsec (wall) %dmin, %dsec (user) %dmin, %dsec (system)' \
% _minSec(nt-ct, ntimes[0]-cts[0], ntimes[1]-cts[1])
if not sinceBegin:
CTIME = nt
CTIMES = ntimes
def title_soundex(title):
"""Return the soundex code for the given title; the (optional) starting
article is pruned. It assumes to receive a title without year/imdbIndex
or kind indications, but just the title string, as the one in the
analyze_title(title)['title'] value."""
if not title: return None
# Convert to canonical format.
title = canonicalTitle(title)
ts = title.split(', ')
# Strip the ending article, if any.
if ts[-1].lower() in _articles:
title = ', '.join(ts[:-1])
return soundex(title)
def name_soundexes(name, character=False):
"""Return three soundex codes for the given name; the name is assumed
to be in the 'surname, name' format, without the imdbIndex indication,
as the one in the analyze_name(name)['name'] value.
The first one is the soundex of the name in the canonical format.
The second is the soundex of the name in the normal format, if different
from the first one.
The third is the soundex of the surname, if different from the
other two values."""
##if not isinstance(name, unicode): name = unicode(name, 'utf_8')
# Prune non-ascii chars from the string.
##name = name.encode('ascii', 'ignore')
if not name: return None, None, None
s1 = soundex(name)
name_normal = normalizeName(name)
s2 = soundex(name_normal)
if s1 == s2: s2 = None
if not character:
namesplit = name.split(', ')
s3 = soundex(namesplit[0])
else:
s3 = soundex(name.split(' ')[-1])
if s3 and s3 in (s1, s2): s3 = None
return s1, s2, s3
# Tags to identify where the meaningful data begin/end in files.
MOVIES = 'movies.list.gz'
MOVIES_START = ('MOVIES LIST', '===========', '')
MOVIES_STOP = '--------------------------------------------------'
CAST_START = ('Name', '----')
CAST_STOP = '-----------------------------'
RAT_START = ('MOVIE RATINGS REPORT', '',
'New Distribution Votes Rank Title')
RAT_STOP = '\n'
RAT_TOP250_START = ('note: for this top 250', '', 'New Distribution')
RAT_BOT10_START = ('BOTTOM 10 MOVIES', '', 'New Distribution')
TOPBOT_STOP = '\n'
AKAT_START = ('AKA TITLES LIST', '=============', '', '', '')
AKAT_IT_START = ('AKA TITLES LIST ITALIAN', '=======================', '', '')
AKAT_DE_START = ('AKA TITLES LIST GERMAN', '======================', '')
AKAT_ISO_START = ('AKA TITLES LIST ISO', '===================', '')
AKAT_HU_START = ('AKA TITLES LIST HUNGARIAN', '=========================', '')
AKAT_NO_START = ('AKA TITLES LIST NORWEGIAN', '=========================', '')
AKAN_START = ('AKA NAMES LIST', '=============', '')
AV_START = ('ALTERNATE VERSIONS LIST', '=======================', '', '')
MINHASH_STOP = '-------------------------'
GOOFS_START = ('GOOFS LIST', '==========', '')
QUOTES_START = ('QUOTES LIST', '=============')
CC_START = ('CRAZY CREDITS', '=============')
BIO_START = ('BIOGRAPHY LIST', '==============')
BUS_START = ('BUSINESS LIST', '=============', '')
BUS_STOP = ' ====='
CER_START = ('CERTIFICATES LIST', '=================')
COL_START = ('COLOR INFO LIST', '===============')
COU_START = ('COUNTRIES LIST', '==============')
DIS_START = ('DISTRIBUTORS LIST', '=================', '')
GEN_START = ('8: THE GENRES LIST', '==================', '')
KEY_START = ('8: THE KEYWORDS LIST', '====================', '')
LAN_START = ('LANGUAGE LIST', '=============')
LOC_START = ('LOCATIONS LIST', '==============', '')
MIS_START = ('MISCELLANEOUS COMPANY LIST', '============================')
MIS_STOP = '--------------------------------------------------------------------------------'
PRO_START = ('PRODUCTION COMPANIES LIST', '=========================', '')
RUN_START = ('RUNNING TIMES LIST', '==================')
SOU_START = ('SOUND-MIX LIST', '==============')
SFX_START = ('SFXCO COMPANIES LIST', '====================', '')
TCN_START = ('TECHNICAL LIST', '==============', '', '')
LSD_START = ('LASERDISC LIST', '==============', '------------------------')
LIT_START = ('LITERATURE LIST', '===============', '')
LIT_STOP = 'COPYING POLICY'
LINK_START = ('MOVIE LINKS LIST', '================', '')
MPAA_START = ('MPAA RATINGS REASONS LIST', '=========================')
PLOT_START = ('PLOT SUMMARIES LIST', '===================', '')
RELDATE_START = ('RELEASE DATES LIST', '==================')
SNDT_START = ('SOUNDTRACKS', '=============', '', '', '')
TAGL_START = ('TAG LINES LIST', '==============', '', '')
TAGL_STOP = '-----------------------------------------'
TRIV_START = ('FILM TRIVIA', '===========', '')
COMPCAST_START = ('CAST COVERAGE TRACKING LIST', '===========================')
COMPCREW_START = ('CREW COVERAGE TRACKING LIST', '===========================')
COMP_STOP = '---------------'
GzipFileRL = GzipFile.readline
class SourceFile(GzipFile):
"""Instances of this class are used to read gzipped files,
starting from a defined line to a (optionally) given end."""
def __init__(self, filename=None, mode=None, start=(), stop=None,
pwarning=1, *args, **kwds):
filename = os.path.join(IMDB_PTDF_DIR, filename)
try:
GzipFile.__init__(self, filename, mode, *args, **kwds)
except IOError, e:
if not pwarning: raise
print 'WARNING WARNING WARNING'
print 'WARNING unable to read the "%s" file.' % filename
print 'WARNING The file will be skipped, and the contained'
print 'WARNING information will NOT be stored in the database.'
print 'WARNING Complete error: ', e
# re-raise the exception.
raise
self.start = start
for item in start:
itemlen = len(item)
for line in self:
if line[:itemlen] == item: break
self.set_stop(stop)
def set_stop(self, stop):
if stop is not None:
self.stop = stop
self.stoplen = len(self.stop)
self.readline = self.readline_checkEnd
else:
self.readline = self.readline_NOcheckEnd
def readline_NOcheckEnd(self, size=-1):
line = GzipFile.readline(self, size)
return unicode(line, 'latin_1').encode('utf_8')
def readline_checkEnd(self, size=-1):
line = GzipFile.readline(self, size)
if self.stop is not None and line[:self.stoplen] == self.stop: return ''
return unicode(line, 'latin_1').encode('utf_8')
def getByHashSections(self):
return getSectionHash(self)
def getByNMMVSections(self):
return getSectionNMMV(self)
def getSectionHash(fp):
"""Return sections separated by lines starting with #."""
curSectList = []
curSectListApp = curSectList.append
curTitle = ''
joiner = ''.join
for line in fp:
if line and line[0] == '#':
if curSectList and curTitle:
yield curTitle, joiner(curSectList)
curSectList[:] = []
curTitle = ''
curTitle = line[2:]
else: curSectListApp(line)
if curSectList and curTitle:
yield curTitle, joiner(curSectList)
curSectList[:] = []
curTitle = ''
NMMVSections = dict([(x, None) for x in ('MV: ', 'NM: ', 'OT: ', 'MOVI')])
def getSectionNMMV(fp):
"""Return sections separated by lines starting with 'NM: ', 'MV: ',
'OT: ' or 'MOVI'."""
curSectList = []
curSectListApp = curSectList.append
curNMMV = ''
joiner = ''.join
for line in fp:
if line[:4] in NMMVSections:
if curSectList and curNMMV:
yield curNMMV, joiner(curSectList)
curSectList[:] = []
curNMMV = ''
if line[:4] == 'MOVI': curNMMV = line[6:]
else: curNMMV = line[4:]
elif not (line and line[0] == '-'): curSectListApp(line)
if curSectList and curNMMV:
yield curNMMV, joiner(curSectList)
curSectList[:] = []
curNMMV = ''
def counter(initValue=1):
"""A counter implemented using a generator."""
i = initValue
while 1:
yield i
i += 1
class _BaseCache(dict):
"""Base class for Movie and Person basic information."""
def __init__(self, d=None, flushEvery=100000):
dict.__init__(self)
# Flush data into the SQL database every flushEvery entries.
self.flushEvery = flushEvery
self._tmpDict = {}
self._flushing = 0
self._deferredData = {}
self._recursionLevel = 0
self._table_name = ''
self._id_for_custom_q = ''
if d is not None:
for k, v in d.iteritems(): self[k] = v
def __setitem__(self, key, counter):
"""Every time a key is set, its value is the counter;
every flushEvery, the temporary dictionary is
flushed to the database, and then zeroed."""
if counter % self.flushEvery == 0:
self.flush()
dict.__setitem__(self, key, counter)
if not self._flushing:
self._tmpDict[key] = counter
else:
self._deferredData[key] = counter
def flush(self, quiet=0, _recursionLevel=0):
"""Flush to the database."""
if self._flushing: return
self._flushing = 1
if _recursionLevel >= MAX_RECURSION:
print 'WARNING recursion level exceded trying to flush data'
print 'WARNING this batch of data is lost (%s).' % self.className
self._tmpDict.clear()
return
if self._tmpDict:
# Horrible hack to know if AFTER_%s_TODB has run.
_after_has_run = False
keys = {'table': self._table_name}
try:
executeCustomQueries('BEFORE_%s_TODB' % self._id_for_custom_q,
_keys=keys, _timeit=False)
self._toDB(quiet)
executeCustomQueries('AFTER_%s_TODB' % self._id_for_custom_q,
_keys=keys, _timeit=False)
_after_has_run = True
self._tmpDict.clear()
except OperationalError, e:
# XXX: I'm not sure this is the right thing (and way)
# to proceed.
if not _after_has_run:
executeCustomQueries('AFTER_%s_TODB'%self._id_for_custom_q,
_keys=keys, _timeit=False)
# Dataset too large; split it in two and retry.
# XXX: new code!
# the same class instance (self) is used, instead of
# creating two separated objects.
_recursionLevel += 1
self._flushing = 0
firstHalf = {}
poptmpd = self._tmpDict.popitem
originalLength = len(self._tmpDict)
for x in xrange(1, 1 + originalLength/2):
k, v = poptmpd()
firstHalf[k] = v
self._secondHalf = self._tmpDict
self._tmpDict = firstHalf
print ' * TOO MANY DATA (%s items in %s), recursion: %s' % \
(originalLength,
self.className,
_recursionLevel)
print ' * SPLITTING (run 1 of 2), recursion: %s' % \
_recursionLevel
self.flush(quiet=quiet, _recursionLevel=_recursionLevel)
self._tmpDict = self._secondHalf
print ' * SPLITTING (run 2 of 2), recursion: %s' % \
_recursionLevel
self.flush(quiet=quiet, _recursionLevel=_recursionLevel)
self._tmpDict.clear()
except Exception, e:
if isinstance(e, KeyboardInterrupt):
raise
print 'WARNING: unknown exception caught committing the data'
print 'WARNING: to the database; report this as a bug, since'
print 'WARNING: many data (%d items) were lost: %s' % \
(len(self._tmpDict), e)
self._flushing = 0
# Flush also deferred data.
if self._deferredData:
self._tmpDict = self._deferredData
self.flush(quiet=1)
self._deferredData = {}
connectObject.commit()
def populate(self):
"""Populate the dictionary from the database."""
raise NotImplementedError
def _toDB(self, quiet=0):
"""Write the dictionary to the database."""
raise NotImplementedError