From 8d4454400b095d2b4d5f425c2a5983d526db782d Mon Sep 17 00:00:00 2001 From: Zafer Cakmak Date: Wed, 2 Jan 2013 08:22:51 +0100 Subject: [PATCH 01/58] README updated. Running help added --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index a92db7e..444168e 100644 --- a/README.md +++ b/README.md @@ -24,3 +24,5 @@ Execute ~/imdb-data-parser$ python3 imdbparser.py You can use -h parameter to see list of optional arguments + + ~/imdb-data-parser$ ./imdbparser.py -h From 422018c21f9177d3b4483a99aaa6b87dc3d0a369 Mon Sep 17 00:00:00 2001 From: Zafer CAKMAK Date: Wed, 2 Jan 2013 20:39:44 +0200 Subject: [PATCH 02/58] added license file for imdbparser. #1 --- imdbparser.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/imdbparser.py b/imdbparser.py index 654ce70..4933abc 100755 --- a/imdbparser.py +++ b/imdbparser.py @@ -1,5 +1,22 @@ #!/usr/bin/env python3 +""" +This file is part of imdb-data-parser. + +imdb-data-parser 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 3 of the License, or +(at your option) any later version. + +imdb-data-parser 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 imdb-data-parser. If not, see . +""" + import sys import argparse import logging From 6fbf7c05ba520856505bf90e3e45eb8942d709c9 Mon Sep 17 00:00:00 2001 From: Aykut Akin Date: Thu, 3 Jan 2013 09:27:45 +0200 Subject: [PATCH 03/58] Changes regex and hardcoded csv to seperator --- idp/parser/moviesparser.py | 130 ++++++++++++++++++------------------- 1 file changed, 65 insertions(+), 65 deletions(-) diff --git a/idp/parser/moviesparser.py b/idp/parser/moviesparser.py index 021fb73..ba87e75 100644 --- a/idp/parser/moviesparser.py +++ b/idp/parser/moviesparser.py @@ -1,65 +1,65 @@ -from .baseparser import BaseParser -from ..utils.regexhelper import * -import logging - -class MoviesParser(BaseParser): - """ - RegExp: /(.*?) (\(\S{4,}\))\s?(\(.+\))?\s?(\{(.*?)(\(.+?\))\})?\s*(\{\{SUSPENDED\}\})?\s*(.*$)/gm - pattern: (.*?) (\(\S{4,}\))\s?(\(.+\))?\s?(\{(.*?)(\(.+?\))\})?\s*(\{\{SUSPENDED\}\})?\s*(.*$) - flags: gm - 6 capturing groups: - group 1: (.*?) title - group 2: (\(\S{4,}\)) year - group 3: (\(.+\)) type ex:(TV) - group 4: (\{(.*?)(\(.+?\))\}) series info ex: {Ally Abroad (#3.1)} - group 5: (.*?) episode name ex: Ally Abroad - group 6: (\(.+?\)) episode number ex: (#3.1) - group 7: (\{\{SUSPENDED\}\}) is suspended? - group 8: (.*$) year - """ - - # properties - baseMatcherPattern = "(.*?) (\(\S{4,}\))\s?(\(.+\))?\s?(\{(.*?)(\(.+?\))\})?\s*(\{\{SUSPENDED\}\})?\s*(.*$)" - inputFileName = "movies.list" - numberOfLinesToBeSkipped = 15 - - def __init__(self, preferencesMap): - self._preferencesMap = preferencesMap - - @property - def preferencesMap(self): - return self._preferencesMap - - def parse_into_tsv(self): - import time - - startTime = time.time() - - inputFile = self.get_input_file() - outputFile = self.get_output_file() - counter = 0 - fuckedUpCount = 0 - numberOfProcessedLines = 0 - - for line in inputFile : - if(numberOfProcessedLines > self.numberOfLinesToBeSkipped): - matcher = RegExHelper(line) - isMatch = matcher.match(self.baseMatcherPattern) - - if(isMatch): - outputFile.write(matcher.group(1) + "," + matcher.group(2) + "," + matcher.group(3) + "," + matcher.group(5) + "," + matcher.group(6) + "," + matcher.group(7) + "," + matcher.group(8) + "\n") - else: - logging.critical("This line is fucked up: " + line) - fuckedUpCount += 1 - numberOfProcessedLines += 1 - - outputFile.flush() - outputFile.close() - inputFile .close() - - logging.info("Finished with " + str(fuckedUpCount) + " fucked up line\n") - logging.info("Duration: " + str(round(time.time() - startTime))) - - def parse_into_db(self): - #TODO - pass +from .baseparser import BaseParser +from ..utils.regexhelper import * +import logging + +class MoviesParser(BaseParser): + """ + RegExp: /((.*? \(\S{4,}\))\s?(\(.+\))?\s?(\{(.*?)\s?(\(.+?\))\})?\s?(\{\{SUSPENDED\}\})?)\s*(.*$)/gm + pattern: ((.*? \(\S{4,}\))\s?(\(.+\))?\s?(\{(.*?)\s?(\(.+?\))\})?\s?(\{\{SUSPENDED\}\})?)\s*(.*$) + flags: gm + 6 capturing groups: + group 1: #TITLE (UNIQUE KEY) + group 2: (.*? \(\S{4,}\)) movie name + year + group 3: (\(.+\)) type ex:(TV) + group 4: (\{(.*?)\s?(\(.+?\))\}) series info ex: {Ally Abroad (#3.1)} + group 5: (.*?) episode name ex: Ally Abroad + group 6: (\(.+?\)) episode number ex: (#3.1) + group 7: (\{\{SUSPENDED\}\}) is suspended? + group 8: (.*$) year + """ + + # properties + baseMatcherPattern = "((.*? \(\S{4,}\))\s?(\(.+\))?\s?(\{(.*?)\s?(\(.+?\))\})?\s?(\{\{SUSPENDED\}\})?)\s*(.*$)" + inputFileName = "movies.list" + numberOfLinesToBeSkipped = 15 + + def __init__(self, preferencesMap): + self._preferencesMap = preferencesMap + + @property + def preferencesMap(self): + return self._preferencesMap + + def parse_into_tsv(self): + import time + + startTime = time.time() + + inputFile = self.get_input_file() + outputFile = self.get_output_file() + counter = 0 + fuckedUpCount = 0 + numberOfProcessedLines = 0 + + for line in inputFile : + if(numberOfProcessedLines > self.numberOfLinesToBeSkipped): + matcher = RegExHelper(line) + isMatch = matcher.match(self.baseMatcherPattern) + + if(isMatch): + outputFile.write(matcher.group(1).strip() + self.seperator + matcher.group(2) + self.seperator + matcher.group(3) + self.seperator + matcher.group(5) + self.seperator + matcher.group(6) + self.seperator + matcher.group(7) + self.seperator + matcher.group(8) + "\n") + else: + logging.critical("This line is fucked up: " + line) + fuckedUpCount += 1 + numberOfProcessedLines += 1 + + outputFile.flush() + outputFile.close() + inputFile .close() + + logging.info("Finished with " + str(fuckedUpCount) + " fucked up line\n") + logging.info("Duration: " + str(round(time.time() - startTime))) + + def parse_into_db(self): + #TODO + pass From c2d056efe11d620b1a67e8802bd78659858e43d4 Mon Sep 17 00:00:00 2001 From: Aykut Akin Date: Fri, 4 Jan 2013 19:33:59 +0200 Subject: [PATCH 04/58] Adds genre parser --- idp/parser/genresparser.py | 65 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 idp/parser/genresparser.py diff --git a/idp/parser/genresparser.py b/idp/parser/genresparser.py new file mode 100644 index 0000000..1f83576 --- /dev/null +++ b/idp/parser/genresparser.py @@ -0,0 +1,65 @@ +from .baseparser import BaseParser +from ..utils.regexhelper import * +import logging + +class GenresParser(BaseParser): + """ + RegExp: /((.*? \(\S{4,}\))\s?(\(.+\))?\s?(\{(.*?)\s?(\(.+?\))\})?\s?(\{\{SUSPENDED\}\})?)\s*(.*$)/gm + pattern: ((.*? \(\S{4,}\))\s?(\(.+\))?\s?(\{(.*?)\s?(\(.+?\))\})?\s?(\{\{SUSPENDED\}\})?)\s*(.*$) + flags: gm + 6 capturing groups: + group 1: #TITLE (UNIQUE KEY) + group 2: (.*? \(\S{4,}\)) movie name + year + group 3: (\(.+\)) type ex:(TV) + group 4: (\{(.*?)\s?(\(.+?\))\}) series info ex: {Ally Abroad (#3.1)} + group 5: (.*?) episode name ex: Ally Abroad + group 6: (\(.+?\)) episode number ex: (#3.1) + group 7: (\{\{SUSPENDED\}\}) is suspended? + group 8: (.*$) genre + """ + + # properties + baseMatcherPattern = "((.*? \(\S{4,}\))\s?(\(.+\))?\s?(\{(.*?)\s?(\(.+?\))\})?\s?(\{\{SUSPENDED\}\})?)\s*(.*$)" + inputFileName = "genres.list" + numberOfLinesToBeSkipped = 378 + + def __init__(self, preferencesMap): + self._preferencesMap = preferencesMap + + @property + def preferencesMap(self): + return self._preferencesMap + + def parse_into_tsv(self): + import time + + startTime = time.time() + + inputFile = self.get_input_file() + outputFile = self.get_output_file() + counter = 0 + fuckedUpCount = 0 + numberOfProcessedLines = 0 + + for line in inputFile : + if(numberOfProcessedLines > self.numberOfLinesToBeSkipped): + matcher = RegExHelper(line) + isMatch = matcher.match(self.baseMatcherPattern) + + if(isMatch): + outputFile.write(matcher.group(1).strip() + self.seperator + matcher.group(2) + self.seperator + matcher.group(3) + self.seperator + matcher.group(5) + self.seperator + matcher.group(6) + self.seperator + matcher.group(7) + self.seperator + matcher.group(8) + "\n") + else: + logging.critical("This line is fucked up: " + line) + fuckedUpCount += 1 + numberOfProcessedLines += 1 + + outputFile.flush() + outputFile.close() + inputFile .close() + + logging.info("Finished with " + str(fuckedUpCount) + " fucked up line\n") + logging.info("Duration: " + str(round(time.time() - startTime))) + + def parse_into_db(self): + #TODO + pass From 2bf5032f5de3f3332c6655c99c689346465700c2 Mon Sep 17 00:00:00 2001 From: Aykut Akin Date: Sat, 5 Jan 2013 17:22:46 +0200 Subject: [PATCH 05/58] Adds rating parser --- idp/parser/ratingsparser.py | 67 +++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 idp/parser/ratingsparser.py diff --git a/idp/parser/ratingsparser.py b/idp/parser/ratingsparser.py new file mode 100644 index 0000000..0be3088 --- /dev/null +++ b/idp/parser/ratingsparser.py @@ -0,0 +1,67 @@ +from .baseparser import BaseParser +from ..utils.regexhelper import * +import logging + +class RatingsParser(BaseParser): + """ + RegExp: /\s*(\S*)\s*(\S*)\s*(\S*)\s*((.*? \(\S{4,}\))\s?(\(.+\))?\s?(\{(.*?)\s?(\(.+?\))\})?\s?(\{\{SUSPENDED\}\})?)/gm + pattern: \s*(\S*)\s*(\S*)\s*(\S*)\s*((.*? \(\S{4,}\))\s?(\(.+\))?\s?(\{(.*?)\s?(\(.+?\))\})?\s?(\{\{SUSPENDED\}\})?) + flags: gm + 10 capturing groups: + group 1: (\S*) distribution + group 2: (\S*) votes + group 3: (\S*) rank + group 4: #TITLE (UNIQUE KEY) + group 5: (.*? \(\S{4,}\)) movie name + year + group 6: (\(.+\)) type ex:(TV) + group 7: (\{(.*?)\s?(\(.+?\))\}) series info ex: {Ally Abroad (#3.1)} + group 8: (.*?) episode name ex: Ally Abroad + group 9: (\(.+?\)) episode number ex: (#3.1) + group 10: (\{\{SUSPENDED\}\}) is suspended? + """ + + # properties + baseMatcherPattern = "\s*(\S*)\s*(\S*)\s*(\S*)\s*((.*? \(\S{4,}\))\s?(\(.+\))?\s?(\{(.*?)\s?(\(.+?\))\})?\s?(\{\{SUSPENDED\}\})?)" + inputFileName = "ratings.list" + numberOfLinesToBeSkipped = 28 + + def __init__(self, preferencesMap): + self._preferencesMap = preferencesMap + + @property + def preferencesMap(self): + return self._preferencesMap + + def parse_into_tsv(self): + import time + + startTime = time.time() + + inputFile = self.get_input_file() + outputFile = self.get_output_file() + counter = 0 + fuckedUpCount = 0 + numberOfProcessedLines = 0 + + for line in inputFile : + if(numberOfProcessedLines > self.numberOfLinesToBeSkipped): + matcher = RegExHelper(line) + isMatch = matcher.match(self.baseMatcherPattern) + + if(isMatch): + outputFile.write(matcher.group(1) + self.seperator + matcher.group(2) + self.seperator + matcher.group(3) + self.seperator + matcher.group(4).strip() + self.seperator + matcher.group(5) + self.seperator + matcher.group(6) + self.seperator + matcher.group(8) + self.seperator + matcher.group(8) + self.seperator + matcher.group(9) + self.seperator + matcher.group(10) + "\n") + else: + logging.critical("This line is fucked up: " + line) + fuckedUpCount += 1 + numberOfProcessedLines += 1 + + outputFile.flush() + outputFile.close() + inputFile .close() + + logging.info("Finished with " + str(fuckedUpCount) + " fucked up line\n") + logging.info("Duration: " + str(round(time.time() - startTime))) + + def parse_into_db(self): + #TODO + pass From 5a23522850c759944da472123da3cf272d14e864 Mon Sep 17 00:00:00 2001 From: Zafer CAKMAK Date: Mon, 7 Jan 2013 00:04:08 +0200 Subject: [PATCH 06/58] #1 added full text of GPLv3 --- LICENSE | 674 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 674 insertions(+) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..20d40b6 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + 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 3 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, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. \ No newline at end of file From 3114bedd034e3b66930e3a83e38f40669beca915 Mon Sep 17 00:00:00 2001 From: Zafer CAKMAK Date: Mon, 7 Jan 2013 00:09:30 +0200 Subject: [PATCH 07/58] closes #1 project is GPLv3 now. - GPL statement added to all source files. --- README.md | 3 +++ idp/parser/baseparser.py | 17 +++++++++++++++++ idp/parser/genresparser.py | 17 +++++++++++++++++ idp/parser/moviesparser.py | 17 +++++++++++++++++ idp/parser/parsinghelper.py | 17 +++++++++++++++++ idp/parser/plotparser.py | 17 +++++++++++++++++ idp/parser/ratingsparser.py | 17 +++++++++++++++++ idp/settings.py.example | 17 +++++++++++++++++ idp/utils/filehandler.py | 17 +++++++++++++++++ idp/utils/listdownloader.py | 17 +++++++++++++++++ idp/utils/regexhelper.py | 17 +++++++++++++++++ idp/utils/test/__init__.py | 0 idp/utils/test/filehandler_test.py | 14 ++++++++++++++ imdb parse path.txt => imdb_parse_path.txt | 19 +++++++++++++++++++ 14 files changed, 206 insertions(+) create mode 100644 idp/utils/test/__init__.py create mode 100644 idp/utils/test/filehandler_test.py rename imdb parse path.txt => imdb_parse_path.txt (67%) diff --git a/README.md b/README.md index 444168e..6d73b43 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,9 @@ imdb-data-parser Parses the IMDB dumps into CSV and Relational Database insert queries Uses IMDB dumps from: http://www.imdb.com/interfaces +imdb-data-parser is a free software licensed by GPLv3. + + Requirements ================ Python 3.x diff --git a/idp/parser/baseparser.py b/idp/parser/baseparser.py index c2468b4..bb13bd2 100644 --- a/idp/parser/baseparser.py +++ b/idp/parser/baseparser.py @@ -1,3 +1,20 @@ +""" +This file is part of imdb-data-parser. + +imdb-data-parser 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 3 of the License, or +(at your option) any later version. + +imdb-data-parser 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 imdb-data-parser. If not, see . +""" + from abc import * from ..utils.filehandler import * diff --git a/idp/parser/genresparser.py b/idp/parser/genresparser.py index 1f83576..1b7b1a4 100644 --- a/idp/parser/genresparser.py +++ b/idp/parser/genresparser.py @@ -1,3 +1,20 @@ +""" +This file is part of imdb-data-parser. + +imdb-data-parser 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 3 of the License, or +(at your option) any later version. + +imdb-data-parser 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 imdb-data-parser. If not, see . +""" + from .baseparser import BaseParser from ..utils.regexhelper import * import logging diff --git a/idp/parser/moviesparser.py b/idp/parser/moviesparser.py index ba87e75..33bd0ea 100644 --- a/idp/parser/moviesparser.py +++ b/idp/parser/moviesparser.py @@ -1,3 +1,20 @@ +""" +This file is part of imdb-data-parser. + +imdb-data-parser 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 3 of the License, or +(at your option) any later version. + +imdb-data-parser 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 imdb-data-parser. If not, see . +""" + from .baseparser import BaseParser from ..utils.regexhelper import * import logging diff --git a/idp/parser/parsinghelper.py b/idp/parser/parsinghelper.py index 00be657..d32908f 100644 --- a/idp/parser/parsinghelper.py +++ b/idp/parser/parsinghelper.py @@ -1,3 +1,20 @@ +""" +This file is part of imdb-data-parser. + +imdb-data-parser 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 3 of the License, or +(at your option) any later version. + +imdb-data-parser 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 imdb-data-parser. If not, see . +""" + from idp import settings import logging diff --git a/idp/parser/plotparser.py b/idp/parser/plotparser.py index 39ac5d7..d919c88 100644 --- a/idp/parser/plotparser.py +++ b/idp/parser/plotparser.py @@ -1,3 +1,20 @@ +""" +This file is part of imdb-data-parser. + +imdb-data-parser 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 3 of the License, or +(at your option) any later version. + +imdb-data-parser 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 imdb-data-parser. If not, see . +""" + from .baseparser import BaseParser from ..utils.regexhelper import * import logging diff --git a/idp/parser/ratingsparser.py b/idp/parser/ratingsparser.py index 0be3088..4694a01 100644 --- a/idp/parser/ratingsparser.py +++ b/idp/parser/ratingsparser.py @@ -1,3 +1,20 @@ +""" +This file is part of imdb-data-parser. + +imdb-data-parser 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 3 of the License, or +(at your option) any later version. + +imdb-data-parser 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 imdb-data-parser. If not, see . +""" + from .baseparser import BaseParser from ..utils.regexhelper import * import logging diff --git a/idp/settings.py.example b/idp/settings.py.example index 19119b8..44ef1ec 100644 --- a/idp/settings.py.example +++ b/idp/settings.py.example @@ -1,3 +1,20 @@ +""" +This file is part of imdb-data-parser. + +imdb-data-parser 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 3 of the License, or +(at your option) any later version. + +imdb-data-parser 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 imdb-data-parser. If not, see . +""" + SOURCE_PATH = "/home/destan/Desktop/" DESTINATION_PATH = "/home/destan/Desktop/" diff --git a/idp/utils/filehandler.py b/idp/utils/filehandler.py index bd4bc84..faa2441 100644 --- a/idp/utils/filehandler.py +++ b/idp/utils/filehandler.py @@ -1,3 +1,20 @@ +""" +This file is part of imdb-data-parser. + +imdb-data-parser 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 3 of the License, or +(at your option) any later version. + +imdb-data-parser 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 imdb-data-parser. If not, see . +""" + import gzip import os.path from ..settings import * diff --git a/idp/utils/listdownloader.py b/idp/utils/listdownloader.py index 8629741..642fd77 100644 --- a/idp/utils/listdownloader.py +++ b/idp/utils/listdownloader.py @@ -1,3 +1,20 @@ +""" +This file is part of imdb-data-parser. + +imdb-data-parser 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 3 of the License, or +(at your option) any later version. + +imdb-data-parser 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 imdb-data-parser. If not, see . +""" + from ..settings import * from ftplib import FTP import gzip diff --git a/idp/utils/regexhelper.py b/idp/utils/regexhelper.py index f3d4ca3..773bc03 100644 --- a/idp/utils/regexhelper.py +++ b/idp/utils/regexhelper.py @@ -1,3 +1,20 @@ +""" +This file is part of imdb-data-parser. + +imdb-data-parser 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 3 of the License, or +(at your option) any later version. + +imdb-data-parser 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 imdb-data-parser. If not, see . +""" + import re class RegExHelper(object): diff --git a/idp/utils/test/__init__.py b/idp/utils/test/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/idp/utils/test/filehandler_test.py b/idp/utils/test/filehandler_test.py new file mode 100644 index 0000000..9d84396 --- /dev/null +++ b/idp/utils/test/filehandler_test.py @@ -0,0 +1,14 @@ +import unittest +from ..filehandler import * +from ... import settings + +class FileHandlerTests(unittest.TestCase): + def setUp(self): + self.list = 'movies' + + def test_get_full_path(self): + self.assertEqual(get_full_path(self.list), settings.SOURCE_PATH+self.list) + + +if __name__ == '__main__': + unittest.main() diff --git a/imdb parse path.txt b/imdb_parse_path.txt similarity index 67% rename from imdb parse path.txt rename to imdb_parse_path.txt index c85dc23..2f11e7d 100644 --- a/imdb parse path.txt +++ b/imdb_parse_path.txt @@ -1,3 +1,22 @@ +/* +This file is part of imdb-data-parser. + +imdb-data-parser 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 3 of the License, or +(at your option) any later version. + +imdb-data-parser 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 imdb-data-parser. If not, see . +*/ + + + /******************************************************************************** * * * -> optional * From fd43af0284aa1c7e3392842678e7ba3ea7a32860 Mon Sep 17 00:00:00 2001 From: Zafer CAKMAK Date: Mon, 7 Jan 2013 01:02:52 +0200 Subject: [PATCH 08/58] started to convert filehandler to object --- idp/utils/filehandler.py | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/idp/utils/filehandler.py b/idp/utils/filehandler.py index faa2441..a848583 100644 --- a/idp/utils/filehandler.py +++ b/idp/utils/filehandler.py @@ -20,6 +20,28 @@ from ..settings import * import logging +class IMDBList(object): + def __init__(self, listname): + #TODO: check listname finishes with .list + self.listname = listname + + fullFilePath = os.path.join(SOURCE_PATH, self.listname) + print(fullFilePath) + logging.info("Trying to find file: %s", fullFilePath) + if os.path.isfile(fullFilePath): + logging.info("File found: %s", fullFilePath) + self.file = open(fullFilePath, "r", encoding='iso-8859-1') + else: + logging.error("File cannot be found: %s", fullFilePath) + + def full_path(self): + if self.listname.lower().endswith(".gz"): + return os.path.join(SOURCE_PATH, self.listname) + ".gz" + return os.path.join(SOURCE_PATH, self.listname) + + def tsv_path(self): + return self.full_path() + ".tsv" + def get_full_path(filename, isCompressed = False): """ constructs a full path for a dump file in the SOURCE_PATH @@ -77,4 +99,9 @@ def openfile(fullFilePath): raise RuntimeError("Unknown error occured") logging.error("File cannot be found: %s", fullFilePath + ".gz") - raise RuntimeError("FileNotFoundError: " + fullFilePath) \ No newline at end of file + raise RuntimeError("FileNotFoundError: " + fullFilePath) + +if __name__ == "__main__": + f = IMDBList("movies.list") + print(f.full_path()) + print(f.tsv_path()) \ No newline at end of file From 4ef0b08083504b7b71f5fde3c8c08ead8f935529 Mon Sep 17 00:00:00 2001 From: Aykut Akin Date: Tue, 8 Jan 2013 20:55:36 +0200 Subject: [PATCH 09/58] Adds directors parser and improves #TITLE regex --- idp/parser/directorsparser.py | 77 +++++++++++++++++++++++++++++++++++ idp/parser/genresparser.py | 22 +++++----- idp/parser/moviesparser.py | 18 ++++---- idp/parser/ratingsparser.py | 10 ++--- 4 files changed, 102 insertions(+), 25 deletions(-) create mode 100644 idp/parser/directorsparser.py diff --git a/idp/parser/directorsparser.py b/idp/parser/directorsparser.py new file mode 100644 index 0000000..0743873 --- /dev/null +++ b/idp/parser/directorsparser.py @@ -0,0 +1,77 @@ +from .baseparser import BaseParser +from ..utils.regexhelper import * +import logging + +class DirectorsParser(BaseParser): + """ + RegExp: /(.*?)(, )?(\S*)\t+((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)(\(.*\))?$/gm + pattern: (.*?)(, )?(\S*)\t+((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)(\(.*\))?$ + flags: gm + 11 capturing groups: + group 1: (.*?) surname + group 2: (, ) just grouping , + group 3: (\S*) name + group 4: #TITLE (UNIQUE KEY) + group 5: (.*? \(\S{4,}\)) movie name + year + group 6: (\(\S+\)) type ex:(TV) + group 7: (\{(.*?) ?(\(\S+?\))?\}) series info ex: {Ally Abroad (#3.1)} + group 8: (.*?) episode name ex: Ally Abroad + group 9: (\(\S+?\)) episode number ex: (#3.1) + group 10: (\{\{SUSPENDED\}\}) is suspended? + group 11: (\(.*\)) info + """ + + # properties + baseMatcherPattern = "(.*?)(, )?(\S*)\t+((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)(\(.*\))?$" + inputFileName = "directors.list" + numberOfLinesToBeSkipped = 0 #235 + + def __init__(self, preferencesMap): + self._preferencesMap = preferencesMap + + @property + def preferencesMap(self): + return self._preferencesMap + + def parse_into_tsv(self): + import time + + startTime = time.time() + + inputFile = self.get_input_file() + outputFile = self.get_output_file() + counter = 0 + fuckedUpCount = 0 + numberOfProcessedLines = 0 + + for line in inputFile : + if(numberOfProcessedLines > self.numberOfLinesToBeSkipped): + matcher = RegExHelper(line) + isMatch = matcher.match(self.baseMatcherPattern) + + if(isMatch): + if(len(matcher.group(1)) > 0 or len(matcher.group(3)) > 0): + if(len(matcher.group(2)) > 0): + surname = matcher.group(1) + name = matcher.group(3) + else: + name = matcher.group(1) + matcher.group(3) + surname = "" + outputFile.write(name + self.seperator + surname + self.seperator + matcher.group(5) + self.seperator + matcher.group(6) + self.seperator + matcher.group(7) + self.seperator + matcher.group(8) + self.seperator + matcher.group(9) + self.seperator + matcher.group(10) + self.seperator + matcher.group(11) + "\n") + elif(len(line) == 1): + continue + else: + logging.critical("This line is fucked up: " + line) + fuckedUpCount += 1 + numberOfProcessedLines += 1 + + outputFile.flush() + outputFile.close() + inputFile .close() + + logging.info("Finished with " + str(fuckedUpCount) + " fucked up line\n") + logging.info("Duration: " + str(round(time.time() - startTime))) + + def parse_into_db(self): + #TODO + pass diff --git a/idp/parser/genresparser.py b/idp/parser/genresparser.py index 1b7b1a4..10e8b86 100644 --- a/idp/parser/genresparser.py +++ b/idp/parser/genresparser.py @@ -21,24 +21,24 @@ class GenresParser(BaseParser): """ - RegExp: /((.*? \(\S{4,}\))\s?(\(.+\))?\s?(\{(.*?)\s?(\(.+?\))\})?\s?(\{\{SUSPENDED\}\})?)\s*(.*$)/gm - pattern: ((.*? \(\S{4,}\))\s?(\(.+\))?\s?(\{(.*?)\s?(\(.+?\))\})?\s?(\{\{SUSPENDED\}\})?)\s*(.*$) + RegExp: /((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\t+(.*)$/gm + pattern: ((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\t+(.*)$ flags: gm - 6 capturing groups: + 8 capturing groups: group 1: #TITLE (UNIQUE KEY) group 2: (.*? \(\S{4,}\)) movie name + year - group 3: (\(.+\)) type ex:(TV) - group 4: (\{(.*?)\s?(\(.+?\))\}) series info ex: {Ally Abroad (#3.1)} + group 3: (\(\S+\)) type ex:(TV) + group 4: (\{(.*?) ?(\(\S+?\))?\}) series info ex: {Ally Abroad (#3.1)} group 5: (.*?) episode name ex: Ally Abroad - group 6: (\(.+?\)) episode number ex: (#3.1) + group 6: ((\(\S+?\)) episode number ex: (#3.1) group 7: (\{\{SUSPENDED\}\}) is suspended? - group 8: (.*$) genre - """ + group 8: (.*) genre + """ # properties - baseMatcherPattern = "((.*? \(\S{4,}\))\s?(\(.+\))?\s?(\{(.*?)\s?(\(.+?\))\})?\s?(\{\{SUSPENDED\}\})?)\s*(.*$)" + baseMatcherPattern = "((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\t+(.*)$" inputFileName = "genres.list" - numberOfLinesToBeSkipped = 378 + numberOfLinesToBeSkipped = 0 #378 def __init__(self, preferencesMap): self._preferencesMap = preferencesMap @@ -64,7 +64,7 @@ def parse_into_tsv(self): isMatch = matcher.match(self.baseMatcherPattern) if(isMatch): - outputFile.write(matcher.group(1).strip() + self.seperator + matcher.group(2) + self.seperator + matcher.group(3) + self.seperator + matcher.group(5) + self.seperator + matcher.group(6) + self.seperator + matcher.group(7) + self.seperator + matcher.group(8) + "\n") + outputFile.write(matcher.group(1) + self.seperator + matcher.group(2) + self.seperator + matcher.group(3) + self.seperator + matcher.group(5) + self.seperator + matcher.group(6) + self.seperator + matcher.group(7) + self.seperator + matcher.group(8) + "\n") else: logging.critical("This line is fucked up: " + line) fuckedUpCount += 1 diff --git a/idp/parser/moviesparser.py b/idp/parser/moviesparser.py index 33bd0ea..5b527c5 100644 --- a/idp/parser/moviesparser.py +++ b/idp/parser/moviesparser.py @@ -21,22 +21,22 @@ class MoviesParser(BaseParser): """ - RegExp: /((.*? \(\S{4,}\))\s?(\(.+\))?\s?(\{(.*?)\s?(\(.+?\))\})?\s?(\{\{SUSPENDED\}\})?)\s*(.*$)/gm - pattern: ((.*? \(\S{4,}\))\s?(\(.+\))?\s?(\{(.*?)\s?(\(.+?\))\})?\s?(\{\{SUSPENDED\}\})?)\s*(.*$) + RegExp: /((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\t+(.*)$/gm + pattern: ((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\t+(.*)$ flags: gm - 6 capturing groups: + 8 capturing groups: group 1: #TITLE (UNIQUE KEY) group 2: (.*? \(\S{4,}\)) movie name + year - group 3: (\(.+\)) type ex:(TV) - group 4: (\{(.*?)\s?(\(.+?\))\}) series info ex: {Ally Abroad (#3.1)} + group 3: (\(\S+\)) type ex:(TV) + group 4: (\{(.*?) ?(\(\S+?\))?\}) series info ex: {Ally Abroad (#3.1)} group 5: (.*?) episode name ex: Ally Abroad - group 6: (\(.+?\)) episode number ex: (#3.1) + group 6: ((\(\S+?\)) episode number ex: (#3.1) group 7: (\{\{SUSPENDED\}\}) is suspended? - group 8: (.*$) year + group 8: (.*) year """ # properties - baseMatcherPattern = "((.*? \(\S{4,}\))\s?(\(.+\))?\s?(\{(.*?)\s?(\(.+?\))\})?\s?(\{\{SUSPENDED\}\})?)\s*(.*$)" + baseMatcherPattern = "((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\t+(.*)$" inputFileName = "movies.list" numberOfLinesToBeSkipped = 15 @@ -64,7 +64,7 @@ def parse_into_tsv(self): isMatch = matcher.match(self.baseMatcherPattern) if(isMatch): - outputFile.write(matcher.group(1).strip() + self.seperator + matcher.group(2) + self.seperator + matcher.group(3) + self.seperator + matcher.group(5) + self.seperator + matcher.group(6) + self.seperator + matcher.group(7) + self.seperator + matcher.group(8) + "\n") + outputFile.write(matcher.group(1) + self.seperator + matcher.group(2) + self.seperator + matcher.group(3) + self.seperator + matcher.group(5) + self.seperator + matcher.group(6) + self.seperator + matcher.group(7) + self.seperator + matcher.group(8) + "\n") else: logging.critical("This line is fucked up: " + line) fuckedUpCount += 1 diff --git a/idp/parser/ratingsparser.py b/idp/parser/ratingsparser.py index 4694a01..72c2c16 100644 --- a/idp/parser/ratingsparser.py +++ b/idp/parser/ratingsparser.py @@ -21,8 +21,8 @@ class RatingsParser(BaseParser): """ - RegExp: /\s*(\S*)\s*(\S*)\s*(\S*)\s*((.*? \(\S{4,}\))\s?(\(.+\))?\s?(\{(.*?)\s?(\(.+?\))\})?\s?(\{\{SUSPENDED\}\})?)/gm - pattern: \s*(\S*)\s*(\S*)\s*(\S*)\s*((.*? \(\S{4,}\))\s?(\(.+\))?\s?(\{(.*?)\s?(\(.+?\))\})?\s?(\{\{SUSPENDED\}\})?) + RegExp: /\s*(\S*)\s*(\S*)\s*(\S*)\s*((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)$/gm + pattern: \s*(\S*)\s*(\S*)\s*(\S*)\s*((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)$ flags: gm 10 capturing groups: group 1: (\S*) distribution @@ -38,9 +38,9 @@ class RatingsParser(BaseParser): """ # properties - baseMatcherPattern = "\s*(\S*)\s*(\S*)\s*(\S*)\s*((.*? \(\S{4,}\))\s?(\(.+\))?\s?(\{(.*?)\s?(\(.+?\))\})?\s?(\{\{SUSPENDED\}\})?)" + baseMatcherPattern = "\s*(\S*)\s*(\S*)\s*(\S*)\s*((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)$" inputFileName = "ratings.list" - numberOfLinesToBeSkipped = 28 + numberOfLinesToBeSkipped = 0 #28 def __init__(self, preferencesMap): self._preferencesMap = preferencesMap @@ -66,7 +66,7 @@ def parse_into_tsv(self): isMatch = matcher.match(self.baseMatcherPattern) if(isMatch): - outputFile.write(matcher.group(1) + self.seperator + matcher.group(2) + self.seperator + matcher.group(3) + self.seperator + matcher.group(4).strip() + self.seperator + matcher.group(5) + self.seperator + matcher.group(6) + self.seperator + matcher.group(8) + self.seperator + matcher.group(8) + self.seperator + matcher.group(9) + self.seperator + matcher.group(10) + "\n") + outputFile.write(matcher.group(1) + self.seperator + matcher.group(2) + self.seperator + matcher.group(3) + self.seperator + matcher.group(4) + self.seperator + matcher.group(5) + self.seperator + matcher.group(6) + self.seperator + matcher.group(8) + self.seperator + matcher.group(8) + self.seperator + matcher.group(9) + self.seperator + matcher.group(10) + "\n") else: logging.critical("This line is fucked up: " + line) fuckedUpCount += 1 From fce043260b0f5dcbba6d344af573ab83b230813c Mon Sep 17 00:00:00 2001 From: Aykut Akin Date: Tue, 8 Jan 2013 21:35:32 +0200 Subject: [PATCH 10/58] Fixes skipped rows numbers and flow --- idp/parser/directorsparser.py | 21 +++- idp/parser/genresparser.py | 4 +- idp/parser/moviesparser.py | 2 +- idp/parser/plotparser.py | 188 +++++++++++++++++----------------- idp/parser/ratingsparser.py | 4 +- 5 files changed, 118 insertions(+), 101 deletions(-) diff --git a/idp/parser/directorsparser.py b/idp/parser/directorsparser.py index 0743873..af8f84b 100644 --- a/idp/parser/directorsparser.py +++ b/idp/parser/directorsparser.py @@ -1,3 +1,20 @@ +""" +This file is part of imdb-data-parser. + +imdb-data-parser 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 3 of the License, or +(at your option) any later version. + +imdb-data-parser 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 imdb-data-parser. If not, see . +""" + from .baseparser import BaseParser from ..utils.regexhelper import * import logging @@ -24,7 +41,7 @@ class DirectorsParser(BaseParser): # properties baseMatcherPattern = "(.*?)(, )?(\S*)\t+((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)(\(.*\))?$" inputFileName = "directors.list" - numberOfLinesToBeSkipped = 0 #235 + numberOfLinesToBeSkipped = 235 def __init__(self, preferencesMap): self._preferencesMap = preferencesMap @@ -45,7 +62,7 @@ def parse_into_tsv(self): numberOfProcessedLines = 0 for line in inputFile : - if(numberOfProcessedLines > self.numberOfLinesToBeSkipped): + if(numberOfProcessedLines >= self.numberOfLinesToBeSkipped): matcher = RegExHelper(line) isMatch = matcher.match(self.baseMatcherPattern) diff --git a/idp/parser/genresparser.py b/idp/parser/genresparser.py index 10e8b86..3568178 100644 --- a/idp/parser/genresparser.py +++ b/idp/parser/genresparser.py @@ -38,7 +38,7 @@ class GenresParser(BaseParser): # properties baseMatcherPattern = "((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\t+(.*)$" inputFileName = "genres.list" - numberOfLinesToBeSkipped = 0 #378 + numberOfLinesToBeSkipped = 378 def __init__(self, preferencesMap): self._preferencesMap = preferencesMap @@ -59,7 +59,7 @@ def parse_into_tsv(self): numberOfProcessedLines = 0 for line in inputFile : - if(numberOfProcessedLines > self.numberOfLinesToBeSkipped): + if(numberOfProcessedLines >= self.numberOfLinesToBeSkipped): matcher = RegExHelper(line) isMatch = matcher.match(self.baseMatcherPattern) diff --git a/idp/parser/moviesparser.py b/idp/parser/moviesparser.py index 5b527c5..7b18078 100644 --- a/idp/parser/moviesparser.py +++ b/idp/parser/moviesparser.py @@ -59,7 +59,7 @@ def parse_into_tsv(self): numberOfProcessedLines = 0 for line in inputFile : - if(numberOfProcessedLines > self.numberOfLinesToBeSkipped): + if(numberOfProcessedLines >= self.numberOfLinesToBeSkipped): matcher = RegExHelper(line) isMatch = matcher.match(self.baseMatcherPattern) diff --git a/idp/parser/plotparser.py b/idp/parser/plotparser.py index d919c88..93d59ed 100644 --- a/idp/parser/plotparser.py +++ b/idp/parser/plotparser.py @@ -1,94 +1,94 @@ -""" -This file is part of imdb-data-parser. - -imdb-data-parser 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 3 of the License, or -(at your option) any later version. - -imdb-data-parser 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 imdb-data-parser. If not, see . -""" - -from .baseparser import BaseParser -from ..utils.regexhelper import * -import logging - -class PlotParser(BaseParser): - """ - RegExp: /(.+?): (.*)/g - pattern: (.+?): (.*) - flags: g - 2 capturing groups: - group 1: (.+?) type of the line - group 2: (.*) if the line-type is PL then this line is plot, not the whole but one line of it - if the line-type is MV then this line is movie - """ - - # properties - baseMatcherPattern = "(.+?): (.*)" - inputFileName = "plot.list" - numberOfLinesToBeSkipped = 15 - - def __init__(self, preferencesMap): - self._preferencesMap = preferencesMap - - @property - def preferencesMap(self): - return self._preferencesMap - - def parse_into_tsv(self): - import time - startTime = time.time() - - inputFile = self.get_input_file() - outputFile = self.get_output_file() - counter = 0 - fuckedUpCount = 0 - - title = "" - plot = "" - - numberOfProcessedLines = 0 - - for line in inputFile : - if(numberOfProcessedLines > self.numberOfLinesToBeSkipped): - matcher = RegExHelper(line) - isMatch = matcher.match(self.baseMatcherPattern) - - if(isMatch): - if(matcher.group(1) == "MV"): #Title - if(title != ""): - outputFile.write(title + self.seperator + plot + "\n") - - plot = "" - title = matcher.group(2) - - elif(matcher.group(1) == "PL"): #Descriptive text - plot += matcher.group(2) - elif(matcher.group(1) == "BY"): - continue - else: - logging.critical("Unhandled abbreviation: " + matcher.group(1) + " in " + line) - #else: - #just ignore this part, useless lines - numberOfProcessedLines += 1 - - # Covers the last item - outputFile.write(title + self.seperator + plot + "\n") - - outputFile.flush() - outputFile.close() - inputFile.close() - - logging.info("Finished with " + str(fuckedUpCount) + " fucked up line\n") - logging.info("Duration: " + str(round(time.time() - startTime))) - - def parse_into_db(self): - #TODO - pass +""" +This file is part of imdb-data-parser. + +imdb-data-parser 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 3 of the License, or +(at your option) any later version. + +imdb-data-parser 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 imdb-data-parser. If not, see . +""" + +from .baseparser import BaseParser +from ..utils.regexhelper import * +import logging + +class PlotParser(BaseParser): + """ + RegExp: /(.+?): (.*)/g + pattern: (.+?): (.*) + flags: g + 2 capturing groups: + group 1: (.+?) type of the line + group 2: (.*) if the line-type is PL then this line is plot, not the whole but one line of it + if the line-type is MV then this line is movie + """ + + # properties + baseMatcherPattern = "(.+?): (.*)" + inputFileName = "plot.list" + numberOfLinesToBeSkipped = 15 + + def __init__(self, preferencesMap): + self._preferencesMap = preferencesMap + + @property + def preferencesMap(self): + return self._preferencesMap + + def parse_into_tsv(self): + import time + startTime = time.time() + + inputFile = self.get_input_file() + outputFile = self.get_output_file() + counter = 0 + fuckedUpCount = 0 + + title = "" + plot = "" + + numberOfProcessedLines = 0 + + for line in inputFile : + if(numberOfProcessedLines >= self.numberOfLinesToBeSkipped): + matcher = RegExHelper(line) + isMatch = matcher.match(self.baseMatcherPattern) + + if(isMatch): + if(matcher.group(1) == "MV"): #Title + if(title != ""): + outputFile.write(title + self.seperator + plot + "\n") + + plot = "" + title = matcher.group(2) + + elif(matcher.group(1) == "PL"): #Descriptive text + plot += matcher.group(2) + elif(matcher.group(1) == "BY"): + continue + else: + logging.critical("Unhandled abbreviation: " + matcher.group(1) + " in " + line) + #else: + #just ignore this part, useless lines + numberOfProcessedLines += 1 + + # Covers the last item + outputFile.write(title + self.seperator + plot + "\n") + + outputFile.flush() + outputFile.close() + inputFile.close() + + logging.info("Finished with " + str(fuckedUpCount) + " fucked up line\n") + logging.info("Duration: " + str(round(time.time() - startTime))) + + def parse_into_db(self): + #TODO + pass diff --git a/idp/parser/ratingsparser.py b/idp/parser/ratingsparser.py index 72c2c16..adcbd61 100644 --- a/idp/parser/ratingsparser.py +++ b/idp/parser/ratingsparser.py @@ -40,7 +40,7 @@ class RatingsParser(BaseParser): # properties baseMatcherPattern = "\s*(\S*)\s*(\S*)\s*(\S*)\s*((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)$" inputFileName = "ratings.list" - numberOfLinesToBeSkipped = 0 #28 + numberOfLinesToBeSkipped = 28 def __init__(self, preferencesMap): self._preferencesMap = preferencesMap @@ -61,7 +61,7 @@ def parse_into_tsv(self): numberOfProcessedLines = 0 for line in inputFile : - if(numberOfProcessedLines > self.numberOfLinesToBeSkipped): + if(numberOfProcessedLines >= self.numberOfLinesToBeSkipped): matcher = RegExHelper(line) isMatch = matcher.match(self.baseMatcherPattern) From e7d3cad252c959dff6ce3c1ed0bfd44cac7f9c43 Mon Sep 17 00:00:00 2001 From: Destan Sarpkaya Date: Thu, 10 Jan 2013 17:22:49 +0200 Subject: [PATCH 11/58] refactor Parsing classes and CLI arguments --- idp/parser/baseparser.py | 67 +++++++++++++++++---- idp/parser/directorsparser.py | 67 ++++++++------------- idp/parser/genresparser.py | 48 +++++---------- idp/parser/moviesparser.py | 51 +++++----------- idp/parser/parsinghelper.py | 4 +- idp/parser/plotparser.py | 95 +++++++++++++----------------- idp/parser/ratingsparser.py | 48 +++++---------- idp/settings.py.example | 4 +- idp/utils/filehandler.py | 12 ++-- idp/utils/listdownloader.py | 2 +- idp/utils/regexhelper.py | 8 ++- idp/utils/test/filehandler_test.py | 2 +- imdbparser.py | 25 ++++---- 13 files changed, 197 insertions(+), 236 deletions(-) diff --git a/idp/parser/baseparser.py b/idp/parser/baseparser.py index bb13bd2..33f2ceb 100644 --- a/idp/parser/baseparser.py +++ b/idp/parser/baseparser.py @@ -17,27 +17,70 @@ from abc import * from ..utils.filehandler import * +from ..utils.regexhelper import * class BaseParser(metaclass=ABCMeta): """Common methods for all parser classes""" - seperator = "\t" + seperator = "\t" #TODO: get from settings @abstractmethod - def parse_into_tsv(self): + def parse_into_tsv(self, matcher): raise NotImplemented @abstractmethod - def parse_into_db(self): + def parse_into_db(self, matcher): raise NotImplemented def start_processing(self): - if(self.preferencesMap["mode"] == "TSV"): - self.parse_into_tsv() - elif(self.preferencesMap["mode"] == "SQL"): - self.parse_into_db() - else: - raise NotImplemented("Mode: " + self.preferencesMap["mode"]) + import time + + startTime = time.time() + inputFile = self.get_input_file() + + if(self.mode == "TSV"): + self.outputFile = self.get_output_file() + elif(self.mode == "SQL"): + pass + #TODO: drop table if exists + #TODO: create table + # databaseHelper = DatabaseHelper() + # databaseHelper.execute("") + + self.fuckedUpCount = 0 + counter = 0 + numberOfProcessedLines = 0 + + for line in inputFile : + if(numberOfProcessedLines >= self.numberOfLinesToBeSkipped): + matcher = RegExHelper(line) + + if(self.mode == "TSV"): + ''' + give the matcher directly to implementing class + and let it decide what to do when regEx is matched and unmatched + ''' + self.parse_into_tsv(matcher) + elif(self.mode == "SQL"): + self.parse_into_db(matcher) + else: + raise NotImplemented("Mode: " + self.mode) + + numberOfProcessedLines += 1 + + inputFile .close() + + if 'outputFile' in locals(): + self.outputFile.flush() + self.outputFile.close() + + if 'databaseHelper' in locals(): + databaseHelper.commit() + databaseHelper.close() + + # fuckedUpCount is calculated in implementing class + logging.info("Finished with " + str(self.fuckedUpCount) + " fucked up line\n") + logging.info("Duration: " + str(round(time.time() - startTime))) def get_input_file(self): return openfile(get_full_path(self.inputFileName)) @@ -45,6 +88,8 @@ def get_input_file(self): def get_output_file(self): return open(get_full_path_for_tsv(self.inputFileName), "w") + # Below methods force associated properties to be defined in any derived class + @abstractproperty def baseMatcherPattern(self): raise NotImplemented @@ -58,5 +103,5 @@ def numberOfLinesToBeSkipped(self): raise NotImplemented @abstractproperty - def preferencesMap(self): - raise NotImplemented \ No newline at end of file + def scripts(self): + raise NotImplemented diff --git a/idp/parser/directorsparser.py b/idp/parser/directorsparser.py index af8f84b..528bad1 100644 --- a/idp/parser/directorsparser.py +++ b/idp/parser/directorsparser.py @@ -42,53 +42,34 @@ class DirectorsParser(BaseParser): baseMatcherPattern = "(.*?)(, )?(\S*)\t+((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)(\(.*\))?$" inputFileName = "directors.list" numberOfLinesToBeSkipped = 235 + scripts = { #TODO: fill + 'drop' : '', + 'create' : '', + 'insert' : '' + } def __init__(self, preferencesMap): - self._preferencesMap = preferencesMap + self.mode = preferencesMap['mode'] - @property - def preferencesMap(self): - return self._preferencesMap + def parse_into_tsv(self, matcher): + isMatch = matcher.match(self.baseMatcherPattern) - def parse_into_tsv(self): - import time + if(isMatch): + if(len(matcher.group(1)) > 0 or len(matcher.group(3)) > 0): + if(len(matcher.group(2)) > 0): + surname = matcher.group(1) + name = matcher.group(3) + else: + name = matcher.group(1) + matcher.group(3) + surname = "" + + self.outputFile.write(name + self.seperator + surname + self.seperator + matcher.group(5) + self.seperator + matcher.group(6) + self.seperator + matcher.group(7) + self.seperator + matcher.group(8) + self.seperator + matcher.group(9) + self.seperator + matcher.group(10) + self.seperator + matcher.group(11) + "\n") + elif(len(matcher.get_last_string()) == 1): + pass + else: + logging.critical("This line is fucked up: " + matcher.get_last_string()) + self.fuckedUpCount += 1 - startTime = time.time() - - inputFile = self.get_input_file() - outputFile = self.get_output_file() - counter = 0 - fuckedUpCount = 0 - numberOfProcessedLines = 0 - - for line in inputFile : - if(numberOfProcessedLines >= self.numberOfLinesToBeSkipped): - matcher = RegExHelper(line) - isMatch = matcher.match(self.baseMatcherPattern) - - if(isMatch): - if(len(matcher.group(1)) > 0 or len(matcher.group(3)) > 0): - if(len(matcher.group(2)) > 0): - surname = matcher.group(1) - name = matcher.group(3) - else: - name = matcher.group(1) + matcher.group(3) - surname = "" - outputFile.write(name + self.seperator + surname + self.seperator + matcher.group(5) + self.seperator + matcher.group(6) + self.seperator + matcher.group(7) + self.seperator + matcher.group(8) + self.seperator + matcher.group(9) + self.seperator + matcher.group(10) + self.seperator + matcher.group(11) + "\n") - elif(len(line) == 1): - continue - else: - logging.critical("This line is fucked up: " + line) - fuckedUpCount += 1 - numberOfProcessedLines += 1 - - outputFile.flush() - outputFile.close() - inputFile .close() - - logging.info("Finished with " + str(fuckedUpCount) + " fucked up line\n") - logging.info("Duration: " + str(round(time.time() - startTime))) - - def parse_into_db(self): + def parse_into_db(self, matcher): #TODO pass diff --git a/idp/parser/genresparser.py b/idp/parser/genresparser.py index 3568178..389be5f 100644 --- a/idp/parser/genresparser.py +++ b/idp/parser/genresparser.py @@ -39,44 +39,24 @@ class GenresParser(BaseParser): baseMatcherPattern = "((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\t+(.*)$" inputFileName = "genres.list" numberOfLinesToBeSkipped = 378 + scripts = { #TODO: fill + 'drop' : '', + 'create' : '', + 'insert' : '' + } def __init__(self, preferencesMap): - self._preferencesMap = preferencesMap + self.mode = preferencesMap['mode'] - @property - def preferencesMap(self): - return self._preferencesMap + def parse_into_tsv(self, matcher): + isMatch = matcher.match(self.baseMatcherPattern) - def parse_into_tsv(self): - import time + if(isMatch): + self.outputFile.write(matcher.group(1) + self.seperator + matcher.group(2) + self.seperator + matcher.group(3) + self.seperator + matcher.group(5) + self.seperator + matcher.group(6) + self.seperator + matcher.group(7) + self.seperator + matcher.group(8) + "\n") + else: + logging.critical("This line is fucked up: " + matcher.get_last_string()) + self.fuckedUpCount += 1 - startTime = time.time() - - inputFile = self.get_input_file() - outputFile = self.get_output_file() - counter = 0 - fuckedUpCount = 0 - numberOfProcessedLines = 0 - - for line in inputFile : - if(numberOfProcessedLines >= self.numberOfLinesToBeSkipped): - matcher = RegExHelper(line) - isMatch = matcher.match(self.baseMatcherPattern) - - if(isMatch): - outputFile.write(matcher.group(1) + self.seperator + matcher.group(2) + self.seperator + matcher.group(3) + self.seperator + matcher.group(5) + self.seperator + matcher.group(6) + self.seperator + matcher.group(7) + self.seperator + matcher.group(8) + "\n") - else: - logging.critical("This line is fucked up: " + line) - fuckedUpCount += 1 - numberOfProcessedLines += 1 - - outputFile.flush() - outputFile.close() - inputFile .close() - - logging.info("Finished with " + str(fuckedUpCount) + " fucked up line\n") - logging.info("Duration: " + str(round(time.time() - startTime))) - - def parse_into_db(self): + def parse_into_db(self, matcher): #TODO pass diff --git a/idp/parser/moviesparser.py b/idp/parser/moviesparser.py index 7b18078..73e41b9 100644 --- a/idp/parser/moviesparser.py +++ b/idp/parser/moviesparser.py @@ -16,11 +16,12 @@ """ from .baseparser import BaseParser -from ..utils.regexhelper import * import logging class MoviesParser(BaseParser): """ + Parses movies.list dump + RegExp: /((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\t+(.*)$/gm pattern: ((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\t+(.*)$ flags: gm @@ -39,44 +40,24 @@ class MoviesParser(BaseParser): baseMatcherPattern = "((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\t+(.*)$" inputFileName = "movies.list" numberOfLinesToBeSkipped = 15 + scripts = { #TODO: fill + 'drop' : '', + 'create' : '', + 'insert' : '' + } def __init__(self, preferencesMap): - self._preferencesMap = preferencesMap - - @property - def preferencesMap(self): - return self._preferencesMap - - def parse_into_tsv(self): - import time - - startTime = time.time() - - inputFile = self.get_input_file() - outputFile = self.get_output_file() - counter = 0 - fuckedUpCount = 0 - numberOfProcessedLines = 0 - - for line in inputFile : - if(numberOfProcessedLines >= self.numberOfLinesToBeSkipped): - matcher = RegExHelper(line) - isMatch = matcher.match(self.baseMatcherPattern) - - if(isMatch): - outputFile.write(matcher.group(1) + self.seperator + matcher.group(2) + self.seperator + matcher.group(3) + self.seperator + matcher.group(5) + self.seperator + matcher.group(6) + self.seperator + matcher.group(7) + self.seperator + matcher.group(8) + "\n") - else: - logging.critical("This line is fucked up: " + line) - fuckedUpCount += 1 - numberOfProcessedLines += 1 + self.mode = preferencesMap['mode'] - outputFile.flush() - outputFile.close() - inputFile .close() + def parse_into_tsv(self, matcher): + isMatch = matcher.match(self.baseMatcherPattern) - logging.info("Finished with " + str(fuckedUpCount) + " fucked up line\n") - logging.info("Duration: " + str(round(time.time() - startTime))) + if(isMatch): + self.outputFile.write(matcher.group(1) + self.seperator + matcher.group(2) + self.seperator + matcher.group(3) + self.seperator + matcher.group(5) + self.seperator + matcher.group(6) + self.seperator + matcher.group(7) + self.seperator + matcher.group(8) + "\n") + else: + logging.critical("This line is fucked up: " + matcher.get_last_string()) + self.fuckedUpCount += 1 - def parse_into_db(self): + def parse_into_db(self, matcher): #TODO pass diff --git a/idp/parser/parsinghelper.py b/idp/parser/parsinghelper.py index d32908f..fbad055 100644 --- a/idp/parser/parsinghelper.py +++ b/idp/parser/parsinghelper.py @@ -17,6 +17,7 @@ from idp import settings import logging +import traceback class ParsingHelper(object): """ParsingHelper manages parsing order""" @@ -47,5 +48,6 @@ def get_parser_class_for( itemName ): try: parser.start_processing() except Exception as e: - logging.error("File not found for " + item + "\n\tException is: " + str(e)) + logging.error("Exception occured while parsing item: " + item + "\n\tException is: " + str(e)) + traceback.print_exc() logging.info("Parsing finished.") \ No newline at end of file diff --git a/idp/parser/plotparser.py b/idp/parser/plotparser.py index 93d59ed..ac19d03 100644 --- a/idp/parser/plotparser.py +++ b/idp/parser/plotparser.py @@ -34,61 +34,48 @@ class PlotParser(BaseParser): baseMatcherPattern = "(.+?): (.*)" inputFileName = "plot.list" numberOfLinesToBeSkipped = 15 + scripts = { #TODO: fill + 'drop' : '', + 'create' : '', + 'insert' : '' + } def __init__(self, preferencesMap): - self._preferencesMap = preferencesMap - - @property - def preferencesMap(self): - return self._preferencesMap - - def parse_into_tsv(self): - import time - startTime = time.time() - - inputFile = self.get_input_file() - outputFile = self.get_output_file() - counter = 0 - fuckedUpCount = 0 - - title = "" - plot = "" - - numberOfProcessedLines = 0 - - for line in inputFile : - if(numberOfProcessedLines >= self.numberOfLinesToBeSkipped): - matcher = RegExHelper(line) - isMatch = matcher.match(self.baseMatcherPattern) - - if(isMatch): - if(matcher.group(1) == "MV"): #Title - if(title != ""): - outputFile.write(title + self.seperator + plot + "\n") - - plot = "" - title = matcher.group(2) - - elif(matcher.group(1) == "PL"): #Descriptive text - plot += matcher.group(2) - elif(matcher.group(1) == "BY"): - continue - else: - logging.critical("Unhandled abbreviation: " + matcher.group(1) + " in " + line) - #else: - #just ignore this part, useless lines - numberOfProcessedLines += 1 - - # Covers the last item - outputFile.write(title + self.seperator + plot + "\n") - - outputFile.flush() - outputFile.close() - inputFile.close() - - logging.info("Finished with " + str(fuckedUpCount) + " fucked up line\n") - logging.info("Duration: " + str(round(time.time() - startTime))) - - def parse_into_db(self): + self.mode = preferencesMap['mode'] + + # specific to this class + self.title = "" + self.plot = "" + + def parse_into_tsv(self, matcher): + isMatch = matcher.match(self.baseMatcherPattern) + + if(isMatch): + if(matcher.group(1) == "MV"): #Title + if(self.title != ""): + self.outputFile.write(self.title + self.seperator + self.plot + "\n") + + self.plot = "" + self.title = matcher.group(2) + + elif(matcher.group(1) == "PL"): #Descriptive text + self.plot += matcher.group(2) + elif(matcher.group(1) == "BY"): + pass + else: + logging.critical("Unhandled abbreviation: " + matcher.group(1) + " in " + line) + #else: + #just ignore this part, useless lines + + """ + FIXME: this parsing misses the last entry + need to execute following just after looping the input file's lines: + # Covers the last item + outputFile.write(title + self.seperator + plot + "\n") + + consider writing to the file in "BY:" condition + """ + + def parse_into_db(self, matcher): #TODO pass diff --git a/idp/parser/ratingsparser.py b/idp/parser/ratingsparser.py index adcbd61..f9230ac 100644 --- a/idp/parser/ratingsparser.py +++ b/idp/parser/ratingsparser.py @@ -41,44 +41,24 @@ class RatingsParser(BaseParser): baseMatcherPattern = "\s*(\S*)\s*(\S*)\s*(\S*)\s*((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)$" inputFileName = "ratings.list" numberOfLinesToBeSkipped = 28 + scripts = { #TODO: fill + 'drop' : '', + 'create' : '', + 'insert' : '' + } def __init__(self, preferencesMap): - self._preferencesMap = preferencesMap + self.mode = preferencesMap['mode'] - @property - def preferencesMap(self): - return self._preferencesMap + def parse_into_tsv(self, matcher): + isMatch = matcher.match(self.baseMatcherPattern) - def parse_into_tsv(self): - import time + if(isMatch): + self.outputFile.write(matcher.group(1) + self.seperator + matcher.group(2) + self.seperator + matcher.group(3) + self.seperator + matcher.group(4) + self.seperator + matcher.group(5) + self.seperator + matcher.group(6) + self.seperator + matcher.group(8) + self.seperator + matcher.group(8) + self.seperator + matcher.group(9) + self.seperator + matcher.group(10) + "\n") + else: + logging.critical("This line is fucked up: " + matcher.get_last_string()) + self.fuckedUpCount += 1 - startTime = time.time() - - inputFile = self.get_input_file() - outputFile = self.get_output_file() - counter = 0 - fuckedUpCount = 0 - numberOfProcessedLines = 0 - - for line in inputFile : - if(numberOfProcessedLines >= self.numberOfLinesToBeSkipped): - matcher = RegExHelper(line) - isMatch = matcher.match(self.baseMatcherPattern) - - if(isMatch): - outputFile.write(matcher.group(1) + self.seperator + matcher.group(2) + self.seperator + matcher.group(3) + self.seperator + matcher.group(4) + self.seperator + matcher.group(5) + self.seperator + matcher.group(6) + self.seperator + matcher.group(8) + self.seperator + matcher.group(8) + self.seperator + matcher.group(9) + self.seperator + matcher.group(10) + "\n") - else: - logging.critical("This line is fucked up: " + line) - fuckedUpCount += 1 - numberOfProcessedLines += 1 - - outputFile.flush() - outputFile.close() - inputFile .close() - - logging.info("Finished with " + str(fuckedUpCount) + " fucked up line\n") - logging.info("Duration: " + str(round(time.time() - startTime))) - - def parse_into_db(self): + def parse_into_db(self, matcher): #TODO pass diff --git a/idp/settings.py.example b/idp/settings.py.example index 44ef1ec..a154c39 100644 --- a/idp/settings.py.example +++ b/idp/settings.py.example @@ -15,8 +15,8 @@ You should have received a copy of the GNU General Public License along with imdb-data-parser. If not, see . """ -SOURCE_PATH = "/home/destan/Desktop/" -DESTINATION_PATH = "/home/destan/Desktop/" +INPUT_DIR = "/home/destan/Desktop/" +OUTPUT_DIR = "/home/destan/Desktop/" INTERFACES_SERVER = "ftp.fu-berlin.de" INTERFACES_DIRECTORY = "pub/misc/movies/database/" diff --git a/idp/utils/filehandler.py b/idp/utils/filehandler.py index a848583..11b8ca7 100644 --- a/idp/utils/filehandler.py +++ b/idp/utils/filehandler.py @@ -25,7 +25,7 @@ def __init__(self, listname): #TODO: check listname finishes with .list self.listname = listname - fullFilePath = os.path.join(SOURCE_PATH, self.listname) + fullFilePath = os.path.join(INPUT_DIR, self.listname) print(fullFilePath) logging.info("Trying to find file: %s", fullFilePath) if os.path.isfile(fullFilePath): @@ -36,21 +36,21 @@ def __init__(self, listname): def full_path(self): if self.listname.lower().endswith(".gz"): - return os.path.join(SOURCE_PATH, self.listname) + ".gz" - return os.path.join(SOURCE_PATH, self.listname) + return os.path.join(INPUT_DIR, self.listname) + ".gz" + return os.path.join(INPUT_DIR, self.listname) def tsv_path(self): return self.full_path() + ".tsv" def get_full_path(filename, isCompressed = False): """ - constructs a full path for a dump file in the SOURCE_PATH + constructs a full path for a dump file in the INPUT_DIR filename should be without '.list' """ if(isCompressed): - return os.path.join(SOURCE_PATH, filename) + ".gz" + return os.path.join(INPUT_DIR, filename) + ".gz" else: - return os.path.join(SOURCE_PATH, filename) + return os.path.join(INPUT_DIR, filename) def get_full_path_for_tsv(filename): return get_full_path(filename) + ".tsv" diff --git a/idp/utils/listdownloader.py b/idp/utils/listdownloader.py index 642fd77..5243485 100644 --- a/idp/utils/listdownloader.py +++ b/idp/utils/listdownloader.py @@ -31,7 +31,7 @@ def download(): try: logging.info("started to download list:" + list) r = ftp.retrbinary('RETR '+INTERFACES_DIRECTORY+list+'.list.gz', - open(SOURCE_PATH+list+'.list.gz', 'wb').write) + open(INPUT_DIR+list+'.list.gz', 'wb').write) logging.info(list + "list downloaded successfully") download_count = download_count+1 extract(get_full_path(list+".list", True)) diff --git a/idp/utils/regexhelper.py b/idp/utils/regexhelper.py index 773bc03..e7d9d75 100644 --- a/idp/utils/regexhelper.py +++ b/idp/utils/regexhelper.py @@ -29,4 +29,10 @@ def group(self,i): if self.rematch.group(i) is None : return "" else: - return self.rematch.group(i) \ No newline at end of file + return self.rematch.group(i) + + def get_last_string(self): + """ + returns the last string that is examined + """ + return self.matchstring \ No newline at end of file diff --git a/idp/utils/test/filehandler_test.py b/idp/utils/test/filehandler_test.py index 9d84396..d445ddf 100644 --- a/idp/utils/test/filehandler_test.py +++ b/idp/utils/test/filehandler_test.py @@ -7,7 +7,7 @@ def setUp(self): self.list = 'movies' def test_get_full_path(self): - self.assertEqual(get_full_path(self.list), settings.SOURCE_PATH+self.list) + self.assertEqual(get_full_path(self.list), settings.INPUT_DIR+self.list) if __name__ == '__main__': diff --git a/imdbparser.py b/imdbparser.py index 4933abc..a74d496 100755 --- a/imdbparser.py +++ b/imdbparser.py @@ -32,14 +32,14 @@ parser = argparse.ArgumentParser(description="an IMDB data parser") parser.add_argument('-m', '--mode', help='Parsing mode, defines output of parsing process. Default: CSV', choices=['TSV', 'SQL', 'DB']) -parser.add_argument('-s', '--source_dir', help='source directory of interface lists') -parser.add_argument('-d', '--destination_dir', help='destination directory for outputs') +parser.add_argument('-i', '--input_dir', help='source directory of interface lists') +parser.add_argument('-o', '--output_dir', help='destination directory for outputs') parser.add_argument('-u', '--update_lists', action='store_true', help='downloads lists from server') args = parser.parse_args() logging.info("mode:%s", args.mode) -logging.info("source_dir:%s", args.source_dir) -logging.info("destination_dir:%s", args.destination_dir) +logging.info("input_dir:%s", args.input_dir) +logging.info("output_dir:%s", args.output_dir) logging.info("update_lists:%s", args.update_lists) if args.update_lists: @@ -55,21 +55,20 @@ else: #default mode = "TSV" -if args.source_dir: - sourcePath = args.source_dir +if args.input_dir: + inputDir = args.input_dir else: - sourcePath = SOURCE_PATH + inputDir = INPUT_DIR -if args.destination_dir: - destinationPath = args.source_dir +if args.input_dir: + outputDir = args.output_dir else: - destinationPath = DESTINATION_PATH + outputDir = OUTPUT_DIR preferencesMap = { "mode":mode, - "destinationDir": args.destination_dir, - "sourcePath": sourcePath, - "destinationPath": destinationPath + "inputDir": inputDir, + "outputDir": outputDir } ParsingHelper.parse_all(preferencesMap) From d3d5067843a4d43eba0e0ddb9c51c7255138378f Mon Sep 17 00:00:00 2001 From: Destan Sarpkaya Date: Thu, 10 Jan 2013 17:38:07 +0200 Subject: [PATCH 12/58] fix help text: executing section --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 6d73b43..602c879 100644 --- a/README.md +++ b/README.md @@ -21,10 +21,10 @@ You need to copy this file as `settings.py` and edit this file before running th cp settings.py.example settings.py your_favourite_editor settings.py -Execute -------- +Executing +--------- - ~/imdb-data-parser$ python3 imdbparser.py + ~/imdb-data-parser$ ./imdbparser.py You can use -h parameter to see list of optional arguments From 78a8d3f927f7a1508e058041e9a87be6c6b29f66 Mon Sep 17 00:00:00 2001 From: Zafer CAKMAK Date: Sat, 12 Jan 2013 10:38:58 +0200 Subject: [PATCH 13/58] updated example settings file to use all active lists --- idp/settings.py.example | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/idp/settings.py.example b/idp/settings.py.example index a154c39..0a8097d 100644 --- a/idp/settings.py.example +++ b/idp/settings.py.example @@ -25,12 +25,13 @@ INTERFACES_DIRECTORY = "pub/misc/movies/database/" #ftp://ftp.sunet.se/pub/tv+movies/imdb/ LISTS = [ + "directors", + "genres", "movies", "plot", "actors", "actresses", "aka-names", "aka-titles", - "directors", "ratings" ] \ No newline at end of file From ed0f41709dc632c99c222c6fbede6a3940db077e Mon Sep 17 00:00:00 2001 From: Zafer CAKMAK Date: Sat, 12 Jan 2013 10:41:41 +0200 Subject: [PATCH 14/58] removed real paths from example file --- idp/settings.py.example | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/idp/settings.py.example b/idp/settings.py.example index 0a8097d..8ca4049 100644 --- a/idp/settings.py.example +++ b/idp/settings.py.example @@ -15,8 +15,8 @@ You should have received a copy of the GNU General Public License along with imdb-data-parser. If not, see . """ -INPUT_DIR = "/home/destan/Desktop/" -OUTPUT_DIR = "/home/destan/Desktop/" +INPUT_DIR = "/path/to/lists/files/" +OUTPUT_DIR = "/path/to/tsv/outputs/" INTERFACES_SERVER = "ftp.fu-berlin.de" INTERFACES_DIRECTORY = "pub/misc/movies/database/" From 9148a4244d1b3763dc3d1546694e795b31a805a6 Mon Sep 17 00:00:00 2001 From: Zafer CAKMAK Date: Sat, 12 Jan 2013 13:59:00 +0200 Subject: [PATCH 15/58] added database config to example settings file #11 --- idp/settings.py.example | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/idp/settings.py.example b/idp/settings.py.example index 8ca4049..7e51103 100644 --- a/idp/settings.py.example +++ b/idp/settings.py.example @@ -24,6 +24,11 @@ INTERFACES_DIRECTORY = "pub/misc/movies/database/" #ftp://ftp.funet.fi/pub/mirrors/ftp.imdb.com/pub/ #ftp://ftp.sunet.se/pub/tv+movies/imdb/ +DBHOST = "database_host" +DBNAME = "database_name" +DBUSER = "database_user" +DBPASSWORD = "database_password" + LISTS = [ "directors", "genres", From 07684ef2f3f4f366b702f06df5cd62b4523d9d87 Mon Sep 17 00:00:00 2001 From: Zafer CAKMAK Date: Mon, 14 Jan 2013 07:33:36 +0200 Subject: [PATCH 16/58] parse_all method splitted as parse_one --- idp/parser/parsinghelper.py | 45 ++++++++++++++++++++++++------------- 1 file changed, 30 insertions(+), 15 deletions(-) diff --git a/idp/parser/parsinghelper.py b/idp/parser/parsinghelper.py index fbad055..21602ff 100644 --- a/idp/parser/parsinghelper.py +++ b/idp/parser/parsinghelper.py @@ -23,9 +23,9 @@ class ParsingHelper(object): """ParsingHelper manages parsing order""" @staticmethod - def parse_all(preferencesMap): + def parse_one(item, preferencesMap): - def get_parser_class_for( itemName ): + def get_parser_class_for(itemName): """ Thanks to http://stackoverflow.com/a/452981 """ @@ -36,18 +36,33 @@ def get_parser_class_for( itemName ): for comp in parts[1:]: m = getattr(m, comp) return m + + try: + ParserClass = get_parser_class_for(item) + except Exception as e: + logging.error("No parser found for: " + item + "\n\tException is: " + str(e)) + return 1 + logging.info("Parsing " + item + "...") + parser = ParserClass(preferencesMap) + try: + parser.start_processing() + except Exception as e: + logging.error("Exception occured while parsing item: " + item + "\n\tException is: " + str(e)) + traceback.print_exc() + logging.info("Parsing finished for item: " + item) + + @staticmethod + def parse_all(preferencesMap): for item in settings.LISTS: - try: - ParserClass = get_parser_class_for(item) - except Exception as e: - logging.error("No parser found for: " + item + "\n\tException is: " + str(e)) - continue - logging.info("Parsing " + item + "...") - parser = ParserClass(preferencesMap) - try: - parser.start_processing() - except Exception as e: - logging.error("Exception occured while parsing item: " + item + "\n\tException is: " + str(e)) - traceback.print_exc() - logging.info("Parsing finished.") \ No newline at end of file + ParsingHelper.parse_one(item, preferencesMap) + logging.info("Parsing finished.") + +if __name__ == "__main__": + print("hede") + preferencesMap = { + "mode":"TSV", + "inputDir": "/home/xaph/imdb_lists/", + "outputDir": "/home/xaph/idp_files/" + } + ParsingHelper.parse_one("movies", preferencesMap) \ No newline at end of file From 46921cbfe2f280b349b43eab2ff246fab8b8e134 Mon Sep 17 00:00:00 2001 From: Zafer CAKMAK Date: Mon, 14 Jan 2013 07:34:31 +0200 Subject: [PATCH 17/58] file handler objectified --- idp/utils/filehandler.py | 44 ++++++++++++++++++++++++++-------------- 1 file changed, 29 insertions(+), 15 deletions(-) diff --git a/idp/utils/filehandler.py b/idp/utils/filehandler.py index 11b8ca7..de6ef21 100644 --- a/idp/utils/filehandler.py +++ b/idp/utils/filehandler.py @@ -21,26 +21,43 @@ import logging class IMDBList(object): - def __init__(self, listname): + def __init__(self, listname, preferencesMap): #TODO: check listname finishes with .list self.listname = listname + self.preferencesMap = preferencesMap - fullFilePath = os.path.join(INPUT_DIR, self.listname) - print(fullFilePath) + def full_path(self): + if self.listname.lower().endswith(".gz"): + return os.path.join(self.preferencesMap['inputDir'], self.listname) + ".gz" + return os.path.join(self.preferencesMap['inputDir'], self.listname) + + def tsv_path(self): + return os.path.join(self.preferencesMap['outputDir'], self.listname) + ".tsv" + + def get_input_file(self): + fullFilePath = self.full_path() logging.info("Trying to find file: %s", fullFilePath) if os.path.isfile(fullFilePath): logging.info("File found: %s", fullFilePath) - self.file = open(fullFilePath, "r", encoding='iso-8859-1') - else: - logging.error("File cannot be found: %s", fullFilePath) + return open(fullFilePath, "r", encoding='iso-8859-1') + + logging.error("File cannot be found: %s", fullFilePath) + + logging.info("Trying to find file: %s", fullFilePath + ".gz") + if os.path.isfile(fullFilePath + ".gz"): + logging.info("File found: %s", fullFilePath + ".gz") + if extract(fullFilePath + ".gz") == 0: + return open(fullFilePath, "r", encoding='iso-8859-1') + else: + raise RuntimeError("Unknown error occured") + logging.error("File cannot be found: %s", fullFilePath + ".gz") + + raise RuntimeError("FileNotFoundError: " + fullFilePath) + + def get_output_file(self): + return open(self.tsv_path(), "w") - def full_path(self): - if self.listname.lower().endswith(".gz"): - return os.path.join(INPUT_DIR, self.listname) + ".gz" - return os.path.join(INPUT_DIR, self.listname) - def tsv_path(self): - return self.full_path() + ".tsv" def get_full_path(filename, isCompressed = False): """ @@ -52,9 +69,6 @@ def get_full_path(filename, isCompressed = False): else: return os.path.join(INPUT_DIR, filename) -def get_full_path_for_tsv(filename): - return get_full_path(filename) + ".tsv" - def get_decompressed_file_name(fullpath): return fullpath[:-3] From 6cb2e7c6e5dadb87a5786cd6dc0a02be3d6bed54 Mon Sep 17 00:00:00 2001 From: Zafer CAKMAK Date: Mon, 14 Jan 2013 07:35:51 +0200 Subject: [PATCH 18/58] parsers uses objectified file handler --- idp/parser/baseparser.py | 14 ++++---------- idp/parser/directorsparser.py | 4 ++++ idp/parser/genresparser.py | 4 ++++ idp/parser/moviesparser.py | 4 ++++ idp/parser/plotparser.py | 4 ++++ idp/parser/ratingsparser.py | 4 ++++ 6 files changed, 24 insertions(+), 10 deletions(-) diff --git a/idp/parser/baseparser.py b/idp/parser/baseparser.py index 33f2ceb..f6a83d9 100644 --- a/idp/parser/baseparser.py +++ b/idp/parser/baseparser.py @@ -36,10 +36,10 @@ def start_processing(self): import time startTime = time.time() - inputFile = self.get_input_file() if(self.mode == "TSV"): - self.outputFile = self.get_output_file() + #self.outputFile = self.get_output_file() + pass elif(self.mode == "SQL"): pass #TODO: drop table if exists @@ -51,7 +51,7 @@ def start_processing(self): counter = 0 numberOfProcessedLines = 0 - for line in inputFile : + for line in self.inputFile : if(numberOfProcessedLines >= self.numberOfLinesToBeSkipped): matcher = RegExHelper(line) @@ -68,7 +68,7 @@ def start_processing(self): numberOfProcessedLines += 1 - inputFile .close() + self.inputFile.close() if 'outputFile' in locals(): self.outputFile.flush() @@ -82,12 +82,6 @@ def start_processing(self): logging.info("Finished with " + str(self.fuckedUpCount) + " fucked up line\n") logging.info("Duration: " + str(round(time.time() - startTime))) - def get_input_file(self): - return openfile(get_full_path(self.inputFileName)) - - def get_output_file(self): - return open(get_full_path_for_tsv(self.inputFileName), "w") - # Below methods force associated properties to be defined in any derived class @abstractproperty diff --git a/idp/parser/directorsparser.py b/idp/parser/directorsparser.py index 528bad1..01b6e7b 100644 --- a/idp/parser/directorsparser.py +++ b/idp/parser/directorsparser.py @@ -17,6 +17,7 @@ from .baseparser import BaseParser from ..utils.regexhelper import * +from ..utils.filehandler import IMDBList import logging class DirectorsParser(BaseParser): @@ -50,6 +51,9 @@ class DirectorsParser(BaseParser): def __init__(self, preferencesMap): self.mode = preferencesMap['mode'] + self.list = IMDBList(self.inputFileName, preferencesMap) + self.inputFile = self.list.get_input_file() + self.outputFile = self.list.get_output_file() def parse_into_tsv(self, matcher): isMatch = matcher.match(self.baseMatcherPattern) diff --git a/idp/parser/genresparser.py b/idp/parser/genresparser.py index 389be5f..8327b9c 100644 --- a/idp/parser/genresparser.py +++ b/idp/parser/genresparser.py @@ -17,6 +17,7 @@ from .baseparser import BaseParser from ..utils.regexhelper import * +from ..utils.filehandler import IMDBList import logging class GenresParser(BaseParser): @@ -47,6 +48,9 @@ class GenresParser(BaseParser): def __init__(self, preferencesMap): self.mode = preferencesMap['mode'] + self.list = IMDBList(self.inputFileName, preferencesMap) + self.inputFile = self.list.get_input_file() + self.outputFile = self.list.get_output_file() def parse_into_tsv(self, matcher): isMatch = matcher.match(self.baseMatcherPattern) diff --git a/idp/parser/moviesparser.py b/idp/parser/moviesparser.py index 73e41b9..66fb464 100644 --- a/idp/parser/moviesparser.py +++ b/idp/parser/moviesparser.py @@ -16,6 +16,7 @@ """ from .baseparser import BaseParser +from ..utils.filehandler import IMDBList import logging class MoviesParser(BaseParser): @@ -48,6 +49,9 @@ class MoviesParser(BaseParser): def __init__(self, preferencesMap): self.mode = preferencesMap['mode'] + self.list = IMDBList(self.inputFileName, preferencesMap) + self.inputFile = self.list.get_input_file() + self.outputFile = self.list.get_output_file() def parse_into_tsv(self, matcher): isMatch = matcher.match(self.baseMatcherPattern) diff --git a/idp/parser/plotparser.py b/idp/parser/plotparser.py index ac19d03..506ee8e 100644 --- a/idp/parser/plotparser.py +++ b/idp/parser/plotparser.py @@ -17,6 +17,7 @@ from .baseparser import BaseParser from ..utils.regexhelper import * +from ..utils.filehandler import IMDBList import logging class PlotParser(BaseParser): @@ -42,6 +43,9 @@ class PlotParser(BaseParser): def __init__(self, preferencesMap): self.mode = preferencesMap['mode'] + self.list = IMDBList(self.inputFileName, preferencesMap) + self.inputFile = self.list.get_input_file() + self.outputFile = self.list.get_output_file() # specific to this class self.title = "" diff --git a/idp/parser/ratingsparser.py b/idp/parser/ratingsparser.py index f9230ac..29f68ba 100644 --- a/idp/parser/ratingsparser.py +++ b/idp/parser/ratingsparser.py @@ -17,6 +17,7 @@ from .baseparser import BaseParser from ..utils.regexhelper import * +from ..utils.filehandler import IMDBList import logging class RatingsParser(BaseParser): @@ -49,6 +50,9 @@ class RatingsParser(BaseParser): def __init__(self, preferencesMap): self.mode = preferencesMap['mode'] + self.list = IMDBList(self.inputFileName, preferencesMap) + self.inputFile = self.list.get_input_file() + self.outputFile = self.list.get_output_file() def parse_into_tsv(self, matcher): isMatch = matcher.match(self.baseMatcherPattern) From 7360ce363f87c267d8e849cce7634eaeb1733e58 Mon Sep 17 00:00:00 2001 From: Aykut Akin Date: Tue, 15 Jan 2013 15:42:45 +0200 Subject: [PATCH 19/58] Fixes encoding problem & improves director regex A few miss still there for director regex.. Also regex must be improved for this kind of records: Warman, Bernardo (I) Dragonboy (2011) --- idp/parser/directorsparser.py | 6 +- idp/utils/filehandler.py | 240 +++++++++++++++++----------------- 2 files changed, 123 insertions(+), 123 deletions(-) diff --git a/idp/parser/directorsparser.py b/idp/parser/directorsparser.py index 01b6e7b..c473b2e 100644 --- a/idp/parser/directorsparser.py +++ b/idp/parser/directorsparser.py @@ -22,8 +22,8 @@ class DirectorsParser(BaseParser): """ - RegExp: /(.*?)(, )?(\S*)\t+((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)(\(.*\))?$/gm - pattern: (.*?)(, )?(\S*)\t+((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)(\(.*\))?$ + RegExp: /(.*?)(, )?(\S*)\t+((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\s*(\(.*\))?(<.*>)?$/gm + pattern: (.*?)(, )?(\S*)\t+((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\s*(\(.*\))?(<.*>)?$ flags: gm 11 capturing groups: group 1: (.*?) surname @@ -40,7 +40,7 @@ class DirectorsParser(BaseParser): """ # properties - baseMatcherPattern = "(.*?)(, )?(\S*)\t+((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)(\(.*\))?$" + baseMatcherPattern = "(.*?)(, )?(\S*)\t+((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\s*(\(.*\))?(<.*>)?$" inputFileName = "directors.list" numberOfLinesToBeSkipped = 235 scripts = { #TODO: fill diff --git a/idp/utils/filehandler.py b/idp/utils/filehandler.py index de6ef21..1b513ea 100644 --- a/idp/utils/filehandler.py +++ b/idp/utils/filehandler.py @@ -1,121 +1,121 @@ -""" -This file is part of imdb-data-parser. - -imdb-data-parser 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 3 of the License, or -(at your option) any later version. - -imdb-data-parser 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 imdb-data-parser. If not, see . -""" - -import gzip -import os.path -from ..settings import * -import logging - -class IMDBList(object): - def __init__(self, listname, preferencesMap): - #TODO: check listname finishes with .list - self.listname = listname - self.preferencesMap = preferencesMap - - def full_path(self): - if self.listname.lower().endswith(".gz"): - return os.path.join(self.preferencesMap['inputDir'], self.listname) + ".gz" - return os.path.join(self.preferencesMap['inputDir'], self.listname) - - def tsv_path(self): - return os.path.join(self.preferencesMap['outputDir'], self.listname) + ".tsv" - - def get_input_file(self): - fullFilePath = self.full_path() - logging.info("Trying to find file: %s", fullFilePath) - if os.path.isfile(fullFilePath): - logging.info("File found: %s", fullFilePath) - return open(fullFilePath, "r", encoding='iso-8859-1') - - logging.error("File cannot be found: %s", fullFilePath) - - logging.info("Trying to find file: %s", fullFilePath + ".gz") - if os.path.isfile(fullFilePath + ".gz"): - logging.info("File found: %s", fullFilePath + ".gz") - if extract(fullFilePath + ".gz") == 0: - return open(fullFilePath, "r", encoding='iso-8859-1') - else: - raise RuntimeError("Unknown error occured") - logging.error("File cannot be found: %s", fullFilePath + ".gz") - - raise RuntimeError("FileNotFoundError: " + fullFilePath) - - def get_output_file(self): - return open(self.tsv_path(), "w") - - - -def get_full_path(filename, isCompressed = False): - """ - constructs a full path for a dump file in the INPUT_DIR - filename should be without '.list' - """ - if(isCompressed): - return os.path.join(INPUT_DIR, filename) + ".gz" - else: - return os.path.join(INPUT_DIR, filename) - -def get_decompressed_file_name(fullpath): - return fullpath[:-3] - -def extract(fullpath): - try: - logging.info('started to extract list: %s', fullpath) - with gzip.open(fullpath, 'rb') as f: - file_content = f.read() - listfile = open(get_decompressed_file_name(fullpath), 'wb') - listfile.write(file_content) - listfile.close() - logging.info(fullpath + ' list extracted successfully') - except Exception as e: - logging.error('error when extracting list: ' + fullpath + "\n\t" + str(e)) - return 1 - return 0 - -def openfile(fullFilePath): - - logging.info("Trying to find file: %s", fullFilePath) - if os.path.isfile(fullFilePath): - logging.info("File found: %s", fullFilePath) - return open(fullFilePath, "r", encoding='iso-8859-1') - - logging.error("File cannot be found: %s", fullFilePath) - -# -#this part removed until python 3.3 becomes available for ubuntu LTS and debian -# -# print("Trying to find file:", fullFilePath) -# if os.path.isfile(fullFilePath): -# print("File found:", fullFilePath) -# return gzip.open(fullFilePath, 'rt') -# print("File cannot be found:", fullFilePath) - - logging.info("Trying to find file: %s", fullFilePath + ".gz") - if os.path.isfile(fullFilePath + ".gz"): - logging.info("File found: %s", fullFilePath + ".gz") - if extract(fullFilePath + ".gz") == 0: - return open(fullFilePath, "r", encoding='iso-8859-1') - else: - raise RuntimeError("Unknown error occured") - logging.error("File cannot be found: %s", fullFilePath + ".gz") - - raise RuntimeError("FileNotFoundError: " + fullFilePath) - -if __name__ == "__main__": - f = IMDBList("movies.list") - print(f.full_path()) +""" +This file is part of imdb-data-parser. + +imdb-data-parser 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 3 of the License, or +(at your option) any later version. + +imdb-data-parser 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 imdb-data-parser. If not, see . +""" + +import gzip +import os.path +from ..settings import * +import logging + +class IMDBList(object): + def __init__(self, listname, preferencesMap): + #TODO: check listname finishes with .list + self.listname = listname + self.preferencesMap = preferencesMap + + def full_path(self): + if self.listname.lower().endswith(".gz"): + return os.path.join(self.preferencesMap['inputDir'], self.listname) + ".gz" + return os.path.join(self.preferencesMap['inputDir'], self.listname) + + def tsv_path(self): + return os.path.join(self.preferencesMap['outputDir'], self.listname) + ".tsv" + + def get_input_file(self): + fullFilePath = self.full_path() + logging.info("Trying to find file: %s", fullFilePath) + if os.path.isfile(fullFilePath): + logging.info("File found: %s", fullFilePath) + return open(fullFilePath, "r", encoding='iso-8859-1') + + logging.error("File cannot be found: %s", fullFilePath) + + logging.info("Trying to find file: %s", fullFilePath + ".gz") + if os.path.isfile(fullFilePath + ".gz"): + logging.info("File found: %s", fullFilePath + ".gz") + if extract(fullFilePath + ".gz") == 0: + return open(fullFilePath, "r", encoding='iso-8859-1') + else: + raise RuntimeError("Unknown error occured") + logging.error("File cannot be found: %s", fullFilePath + ".gz") + + raise RuntimeError("FileNotFoundError: " + fullFilePath) + + def get_output_file(self): + return open(self.tsv_path(), "w", encoding='iso-8859-1') + + + +def get_full_path(filename, isCompressed = False): + """ + constructs a full path for a dump file in the INPUT_DIR + filename should be without '.list' + """ + if(isCompressed): + return os.path.join(INPUT_DIR, filename) + ".gz" + else: + return os.path.join(INPUT_DIR, filename) + +def get_decompressed_file_name(fullpath): + return fullpath[:-3] + +def extract(fullpath): + try: + logging.info('started to extract list: %s', fullpath) + with gzip.open(fullpath, 'rb') as f: + file_content = f.read() + listfile = open(get_decompressed_file_name(fullpath), 'wb') + listfile.write(file_content) + listfile.close() + logging.info(fullpath + ' list extracted successfully') + except Exception as e: + logging.error('error when extracting list: ' + fullpath + "\n\t" + str(e)) + return 1 + return 0 + +def openfile(fullFilePath): + + logging.info("Trying to find file: %s", fullFilePath) + if os.path.isfile(fullFilePath): + logging.info("File found: %s", fullFilePath) + return open(fullFilePath, "r", encoding='iso-8859-1') + + logging.error("File cannot be found: %s", fullFilePath) + +# +#this part removed until python 3.3 becomes available for ubuntu LTS and debian +# +# print("Trying to find file:", fullFilePath) +# if os.path.isfile(fullFilePath): +# print("File found:", fullFilePath) +# return gzip.open(fullFilePath, 'rt') +# print("File cannot be found:", fullFilePath) + + logging.info("Trying to find file: %s", fullFilePath + ".gz") + if os.path.isfile(fullFilePath + ".gz"): + logging.info("File found: %s", fullFilePath + ".gz") + if extract(fullFilePath + ".gz") == 0: + return open(fullFilePath, "r", encoding='iso-8859-1') + else: + raise RuntimeError("Unknown error occured") + logging.error("File cannot be found: %s", fullFilePath + ".gz") + + raise RuntimeError("FileNotFoundError: " + fullFilePath) + +if __name__ == "__main__": + f = IMDBList("movies.list") + print(f.full_path()) print(f.tsv_path()) \ No newline at end of file From abdc2372cfcf6160093eef933a20e85297d2cece Mon Sep 17 00:00:00 2001 From: Aykut Akin Date: Sun, 20 Jan 2013 16:19:57 +0200 Subject: [PATCH 20/58] adds end of data separator and #fixes 13 --- idp/parser/baseparser.py | 206 +++++++++++++++++----------------- idp/parser/directorsparser.py | 47 ++++---- 2 files changed, 130 insertions(+), 123 deletions(-) diff --git a/idp/parser/baseparser.py b/idp/parser/baseparser.py index f6a83d9..6fe451d 100644 --- a/idp/parser/baseparser.py +++ b/idp/parser/baseparser.py @@ -1,101 +1,105 @@ -""" -This file is part of imdb-data-parser. - -imdb-data-parser 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 3 of the License, or -(at your option) any later version. - -imdb-data-parser 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 imdb-data-parser. If not, see . -""" - -from abc import * -from ..utils.filehandler import * -from ..utils.regexhelper import * - -class BaseParser(metaclass=ABCMeta): - """Common methods for all parser classes""" - - seperator = "\t" #TODO: get from settings - - @abstractmethod - def parse_into_tsv(self, matcher): - raise NotImplemented - - @abstractmethod - def parse_into_db(self, matcher): - raise NotImplemented - - def start_processing(self): - import time - - startTime = time.time() - - if(self.mode == "TSV"): - #self.outputFile = self.get_output_file() - pass - elif(self.mode == "SQL"): - pass - #TODO: drop table if exists - #TODO: create table - # databaseHelper = DatabaseHelper() - # databaseHelper.execute("") - - self.fuckedUpCount = 0 - counter = 0 - numberOfProcessedLines = 0 - - for line in self.inputFile : - if(numberOfProcessedLines >= self.numberOfLinesToBeSkipped): - matcher = RegExHelper(line) - - if(self.mode == "TSV"): - ''' - give the matcher directly to implementing class - and let it decide what to do when regEx is matched and unmatched - ''' - self.parse_into_tsv(matcher) - elif(self.mode == "SQL"): - self.parse_into_db(matcher) - else: - raise NotImplemented("Mode: " + self.mode) - - numberOfProcessedLines += 1 - - self.inputFile.close() - - if 'outputFile' in locals(): - self.outputFile.flush() - self.outputFile.close() - - if 'databaseHelper' in locals(): - databaseHelper.commit() - databaseHelper.close() - - # fuckedUpCount is calculated in implementing class - logging.info("Finished with " + str(self.fuckedUpCount) + " fucked up line\n") - logging.info("Duration: " + str(round(time.time() - startTime))) - - # Below methods force associated properties to be defined in any derived class - - @abstractproperty - def baseMatcherPattern(self): - raise NotImplemented - - @abstractproperty - def inputFileName(self): - raise NotImplemented - - @abstractproperty - def numberOfLinesToBeSkipped(self): - raise NotImplemented - - @abstractproperty - def scripts(self): - raise NotImplemented +""" +This file is part of imdb-data-parser. + +imdb-data-parser 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 3 of the License, or +(at your option) any later version. + +imdb-data-parser 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 imdb-data-parser. If not, see . +""" + +from abc import * +from ..utils.filehandler import * +from ..utils.regexhelper import * + +class BaseParser(metaclass=ABCMeta): + """Common methods for all parser classes""" + + seperator = "\t" #TODO: get from settings + + @abstractmethod + def parse_into_tsv(self, matcher): + raise NotImplemented + + @abstractmethod + def parse_into_db(self, matcher): + raise NotImplemented + + def start_processing(self): + import time + + startTime = time.time() + + if(self.mode == "TSV"): + #self.outputFile = self.get_output_file() + pass + elif(self.mode == "SQL"): + pass + #TODO: drop table if exists + #TODO: create table + # databaseHelper = DatabaseHelper() + # databaseHelper.execute("") + + self.fuckedUpCount = 0 + counter = 0 + numberOfProcessedLines = 0 + + for line in self.inputFile : + if(numberOfProcessedLines >= self.numberOfLinesToBeSkipped): + #end of data + if("--------------" in line): + break + + matcher = RegExHelper(line) + + if(self.mode == "TSV"): + ''' + give the matcher directly to implementing class + and let it decide what to do when regEx is matched and unmatched + ''' + self.parse_into_tsv(matcher) + elif(self.mode == "SQL"): + self.parse_into_db(matcher) + else: + raise NotImplemented("Mode: " + self.mode) + + numberOfProcessedLines += 1 + + self.inputFile.close() + + if 'outputFile' in locals(): + self.outputFile.flush() + self.outputFile.close() + + if 'databaseHelper' in locals(): + databaseHelper.commit() + databaseHelper.close() + + # fuckedUpCount is calculated in implementing class + logging.info("Finished with " + str(self.fuckedUpCount) + " fucked up line\n") + logging.info("Duration: " + str(round(time.time() - startTime))) + + # Below methods force associated properties to be defined in any derived class + + @abstractproperty + def baseMatcherPattern(self): + raise NotImplemented + + @abstractproperty + def inputFileName(self): + raise NotImplemented + + @abstractproperty + def numberOfLinesToBeSkipped(self): + raise NotImplemented + + @abstractproperty + def scripts(self): + raise NotImplemented diff --git a/idp/parser/directorsparser.py b/idp/parser/directorsparser.py index c473b2e..2f40312 100644 --- a/idp/parser/directorsparser.py +++ b/idp/parser/directorsparser.py @@ -22,25 +22,24 @@ class DirectorsParser(BaseParser): """ - RegExp: /(.*?)(, )?(\S*)\t+((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\s*(\(.*\))?(<.*>)?$/gm - pattern: (.*?)(, )?(\S*)\t+((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\s*(\(.*\))?(<.*>)?$ + RegExp: /(.*?)\t+((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\s*(\(.*\)"?|EDIT)?\s*(<.*>)?$/gm + pattern: (.*?)\t+((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\s*(\(.*\)"?|EDIT)?\s*(<.*>)?$ flags: gm - 11 capturing groups: - group 1: (.*?) surname - group 2: (, ) just grouping , - group 3: (\S*) name - group 4: #TITLE (UNIQUE KEY) - group 5: (.*? \(\S{4,}\)) movie name + year - group 6: (\(\S+\)) type ex:(TV) - group 7: (\{(.*?) ?(\(\S+?\))?\}) series info ex: {Ally Abroad (#3.1)} - group 8: (.*?) episode name ex: Ally Abroad - group 9: (\(\S+?\)) episode number ex: (#3.1) - group 10: (\{\{SUSPENDED\}\}) is suspended? - group 11: (\(.*\)) info + 10 capturing groups: + group 1: (.*?) surname, name + group 2: #TITLE (UNIQUE KEY) + group 3: (.*? \(\S{4,}\)) movie name + year + group 4: (\(\S+\)) type ex:(TV) + group 5: (\{(.*?) ?(\(\S+?\))?\}) series info ex: {Ally Abroad (#3.1)} + group 6: (.*?) episode name ex: Ally Abroad + group 7: (\(\S+?\)) episode number ex: (#3.1) + group 8: (\{\{SUSPENDED\}\}) is suspended? + group 9: (\(.*\)) info + group 10: () """ # properties - baseMatcherPattern = "(.*?)(, )?(\S*)\t+((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\s*(\(.*\))?(<.*>)?$" + baseMatcherPattern = '(.*?)\t+((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\s*(\(.*\)"?|EDIT)?\s*(<.*>)?$' inputFileName = "directors.list" numberOfLinesToBeSkipped = 235 scripts = { #TODO: fill @@ -49,6 +48,9 @@ class DirectorsParser(BaseParser): 'insert' : '' } + name = "" + surname = "" + def __init__(self, preferencesMap): self.mode = preferencesMap['mode'] self.list = IMDBList(self.inputFileName, preferencesMap) @@ -59,15 +61,16 @@ def parse_into_tsv(self, matcher): isMatch = matcher.match(self.baseMatcherPattern) if(isMatch): - if(len(matcher.group(1)) > 0 or len(matcher.group(3)) > 0): - if(len(matcher.group(2)) > 0): - surname = matcher.group(1) - name = matcher.group(3) + if(len(matcher.group(1).strip()) > 0): + namelist = matcher.group(1).split(', ') + if(len(namelist) == 2): + self.name = namelist[1] + self.surname = namelist[0] else: - name = matcher.group(1) + matcher.group(3) - surname = "" + self.name = namelist[0] + self.surname = "" - self.outputFile.write(name + self.seperator + surname + self.seperator + matcher.group(5) + self.seperator + matcher.group(6) + self.seperator + matcher.group(7) + self.seperator + matcher.group(8) + self.seperator + matcher.group(9) + self.seperator + matcher.group(10) + self.seperator + matcher.group(11) + "\n") + self.outputFile.write(self.name + self.seperator + self.surname + self.seperator + matcher.group(2) + self.seperator + matcher.group(3) + self.seperator + matcher.group(4) + self.seperator + matcher.group(6) + self.seperator + matcher.group(7) + self.seperator + matcher.group(8) + self.seperator + matcher.group(9) + "\n") elif(len(matcher.get_last_string()) == 1): pass else: From f8fdeb6732e660a630cd05429123aa2bf61ed899 Mon Sep 17 00:00:00 2001 From: Aykut Akin Date: Sun, 20 Jan 2013 17:14:21 +0200 Subject: [PATCH 21/58] fixes #5 and fixes #4 --- idp/parser/actorsparser.py | 84 +++++++++++++++++++++++++++++++++++ idp/parser/actressesparser.py | 84 +++++++++++++++++++++++++++++++++++ idp/parser/directorsparser.py | 10 ++--- 3 files changed, 173 insertions(+), 5 deletions(-) create mode 100644 idp/parser/actorsparser.py create mode 100644 idp/parser/actressesparser.py diff --git a/idp/parser/actorsparser.py b/idp/parser/actorsparser.py new file mode 100644 index 0000000..9d1389b --- /dev/null +++ b/idp/parser/actorsparser.py @@ -0,0 +1,84 @@ +""" +This file is part of imdb-data-parser. + +imdb-data-parser 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 3 of the License, or +(at your option) any later version. + +imdb-data-parser 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 imdb-data-parser. If not, see . +""" + +from .baseparser import BaseParser +from ..utils.regexhelper import * +from ..utils.filehandler import IMDBList +import logging + +class ActorsParser(BaseParser): + """ + RegExp: /(.*?)\t+((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\s*(\(.*?\))?\s*(\(.*\))?\s*(\[.*\])?\s*(<.*>)?$/gm + pattern: (.*?)\t+((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\s*(\(.*?\))?\s*(\(.*\))?\s*(\[.*\])?\s*(<.*>)?$ + flags: gm + 12 capturing groups: + group 1: (.*?) surname, name + group 2: #TITLE (UNIQUE KEY) + group 3: (.*? \(\S{4,}\)) movie name + year + group 4: (\(\S+\)) type ex:(TV) + group 5: (\{(.*?) ?(\(\S+?\))?\}) series info ex: {Ally Abroad (#3.1)} + group 6: (.*?) episode name ex: Ally Abroad + group 7: (\(\S+?\)) episode number ex: (#3.1) + group 8: (\{\{SUSPENDED\}\}) is suspended? + group 9: (\(.*?\)) info 1 + group 10: (\(.*\)) info 2 + group 11: (\[.*\]) role + group 12: () + """ + + # properties + baseMatcherPattern = '(.*?)\t+((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\s*(\(.*?\))?\s*(\(.*\))?\s*(\[.*\])?\s*(<.*>)?$' + inputFileName = "actors.list" + numberOfLinesToBeSkipped = 239 + scripts = { #TODO: fill + 'drop' : '', + 'create' : '', + 'insert' : '' + } + + name = "" + surname = "" + + def __init__(self, preferencesMap): + self.mode = preferencesMap['mode'] + self.list = IMDBList(self.inputFileName, preferencesMap) + self.inputFile = self.list.get_input_file() + self.outputFile = self.list.get_output_file() + + def parse_into_tsv(self, matcher): + isMatch = matcher.match(self.baseMatcherPattern) + + if(isMatch): + if(len(matcher.group(1).strip()) > 0): + namelist = matcher.group(1).split(', ') + if(len(namelist) == 2): + self.name = namelist[1] + self.surname = namelist[0] + else: + self.name = namelist[0] + self.surname = "" + + self.outputFile.write(self.name + self.seperator + self.surname + self.seperator + matcher.group(2) + self.seperator + matcher.group(3) + self.seperator + matcher.group(4) + self.seperator + matcher.group(6) + self.seperator + matcher.group(7) + self.seperator + matcher.group(8) + self.seperator + matcher.group(9) + self.seperator + matcher.group(10) + self.seperator + matcher.group(11) + "\n") + elif(len(matcher.get_last_string()) == 1): + pass + else: + logging.critical("This line is fucked up: " + matcher.get_last_string()) + self.fuckedUpCount += 1 + + def parse_into_db(self, matcher): + #TODO + pass diff --git a/idp/parser/actressesparser.py b/idp/parser/actressesparser.py new file mode 100644 index 0000000..fdf0242 --- /dev/null +++ b/idp/parser/actressesparser.py @@ -0,0 +1,84 @@ +""" +This file is part of imdb-data-parser. + +imdb-data-parser 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 3 of the License, or +(at your option) any later version. + +imdb-data-parser 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 imdb-data-parser. If not, see . +""" + +from .baseparser import BaseParser +from ..utils.regexhelper import * +from ..utils.filehandler import IMDBList +import logging + +class ActressesParser(BaseParser): + """ + RegExp: /(.*?)\t+((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\s*(\(.*?\))?\s*(\(.*\))?\s*(\[.*\])?\s*(<.*>)?$/gm + pattern: (.*?)\t+((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\s*(\(.*?\))?\s*(\(.*\))?\s*(\[.*\])?\s*(<.*>)?$ + flags: gm + 12 capturing groups: + group 1: (.*?) surname, name + group 2: #TITLE (UNIQUE KEY) + group 3: (.*? \(\S{4,}\)) movie name + year + group 4: (\(\S+\)) type ex:(TV) + group 5: (\{(.*?) ?(\(\S+?\))?\}) series info ex: {Ally Abroad (#3.1)} + group 6: (.*?) episode name ex: Ally Abroad + group 7: (\(\S+?\)) episode number ex: (#3.1) + group 8: (\{\{SUSPENDED\}\}) is suspended? + group 9: (\(.*?\)) info 1 + group 10: (\(.*\)) info 2 + group 11: (\[.*\]) role + group 12: () + """ + + # properties + baseMatcherPattern = '(.*?)\t+((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\s*(\(.*?\))?\s*(\(.*\))?\s*(\[.*\])?\s*(<.*>)?$' + inputFileName = "actresses.list" + numberOfLinesToBeSkipped = 241 + scripts = { #TODO: fill + 'drop' : '', + 'create' : '', + 'insert' : '' + } + + name = "" + surname = "" + + def __init__(self, preferencesMap): + self.mode = preferencesMap['mode'] + self.list = IMDBList(self.inputFileName, preferencesMap) + self.inputFile = self.list.get_input_file() + self.outputFile = self.list.get_output_file() + + def parse_into_tsv(self, matcher): + isMatch = matcher.match(self.baseMatcherPattern) + + if(isMatch): + if(len(matcher.group(1).strip()) > 0): + namelist = matcher.group(1).split(', ') + if(len(namelist) == 2): + self.name = namelist[1] + self.surname = namelist[0] + else: + self.name = namelist[0] + self.surname = "" + + self.outputFile.write(self.name + self.seperator + self.surname + self.seperator + matcher.group(2) + self.seperator + matcher.group(3) + self.seperator + matcher.group(4) + self.seperator + matcher.group(6) + self.seperator + matcher.group(7) + self.seperator + matcher.group(8) + self.seperator + matcher.group(9) + self.seperator + matcher.group(10) + self.seperator + matcher.group(11) + "\n") + elif(len(matcher.get_last_string()) == 1): + pass + else: + logging.critical("This line is fucked up: " + matcher.get_last_string()) + self.fuckedUpCount += 1 + + def parse_into_db(self, matcher): + #TODO + pass diff --git a/idp/parser/directorsparser.py b/idp/parser/directorsparser.py index 2f40312..cee63e2 100644 --- a/idp/parser/directorsparser.py +++ b/idp/parser/directorsparser.py @@ -22,8 +22,8 @@ class DirectorsParser(BaseParser): """ - RegExp: /(.*?)\t+((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\s*(\(.*\)"?|EDIT)?\s*(<.*>)?$/gm - pattern: (.*?)\t+((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\s*(\(.*\)"?|EDIT)?\s*(<.*>)?$ + RegExp: /(.*?)\t+((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\s*(\(.*\)|EDIT)?\s*(<.*>)?$/gm + pattern: (.*?)\t+((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\s*(\(.*\)|EDIT)?\s*(<.*>)?$ flags: gm 10 capturing groups: group 1: (.*?) surname, name @@ -33,13 +33,13 @@ class DirectorsParser(BaseParser): group 5: (\{(.*?) ?(\(\S+?\))?\}) series info ex: {Ally Abroad (#3.1)} group 6: (.*?) episode name ex: Ally Abroad group 7: (\(\S+?\)) episode number ex: (#3.1) - group 8: (\{\{SUSPENDED\}\}) is suspended? - group 9: (\(.*\)) info + group 8: (\{\{SUSPENDED\}\}) is suspended? + group 9: (\(.*\)) info group 10: () """ # properties - baseMatcherPattern = '(.*?)\t+((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\s*(\(.*\)"?|EDIT)?\s*(<.*>)?$' + baseMatcherPattern = '(.*?)\t+((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\s*(\(.*\)|EDIT)?\s*(<.*>)?$' inputFileName = "directors.list" numberOfLinesToBeSkipped = 235 scripts = { #TODO: fill From 6a4c34d1898bc17a38e135a92e736d01a9db3eec Mon Sep 17 00:00:00 2001 From: Aykut Akin Date: Thu, 31 Jan 2013 20:02:29 +0200 Subject: [PATCH 22/58] fixes #16 and fixes #15 Log file path is same as OUTPUT_DIR.. If you want to change log path you can create a new setting variable and change loggerprovider.py file.. --- idp/utils/loggerprovider.py | 45 +++++++++++ imdbparser.py | 150 ++++++++++++++++++------------------ logging.conf | 21 ----- 3 files changed, 120 insertions(+), 96 deletions(-) create mode 100644 idp/utils/loggerprovider.py delete mode 100644 logging.conf diff --git a/idp/utils/loggerprovider.py b/idp/utils/loggerprovider.py new file mode 100644 index 0000000..da5a9f4 --- /dev/null +++ b/idp/utils/loggerprovider.py @@ -0,0 +1,45 @@ +""" +This file is part of imdb-data-parser. + +imdb-data-parser 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 3 of the License, or +(at your option) any later version. + +imdb-data-parser 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 imdb-data-parser. If not, see . +""" + +from ..settings import * +import logging +import os.path + +def initialize_logger(): + logger = logging.getLogger() + logger.setLevel(logging.INFO) + + # create console handler and set level to info + ch = logging.StreamHandler() + ch.setLevel(logging.INFO) + formatter = logging.Formatter("%(levelname)s - %(message)s") + ch.setFormatter(formatter) + logger.addHandler(ch) + + # create error file handler and set level to error + ch = logging.FileHandler(os.path.join(OUTPUT_DIR, 'imdbparserError.log'),'w', encoding=None, delay="true") + ch.setLevel(logging.ERROR) + formatter = logging.Formatter("%(levelname)s - %(message)s") + ch.setFormatter(formatter) + logger.addHandler(ch) + + # create info file handler and set level to info + ch = logging.FileHandler(os.path.join(OUTPUT_DIR, 'imdbparserAll.log'),'w') + ch.setLevel(logging.INFO) + formatter = logging.Formatter("%(levelname)s - %(message)s") + ch.setFormatter(formatter) + logger.addHandler(ch) \ No newline at end of file diff --git a/imdbparser.py b/imdbparser.py index a74d496..8ef45ed 100755 --- a/imdbparser.py +++ b/imdbparser.py @@ -1,76 +1,76 @@ -#!/usr/bin/env python3 - -""" -This file is part of imdb-data-parser. - -imdb-data-parser 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 3 of the License, or -(at your option) any later version. - -imdb-data-parser 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 imdb-data-parser. If not, see . -""" - -import sys -import argparse -import logging -import logging.config -from idp.parser.parsinghelper import ParsingHelper -from idp.settings import * - -# check python version -if sys.version_info.major != 3: - sys.exit("Error: wrong version! You need to install python3 to run this application properly.") - -logging.config.fileConfig("logging.conf") - -parser = argparse.ArgumentParser(description="an IMDB data parser") -parser.add_argument('-m', '--mode', help='Parsing mode, defines output of parsing process. Default: CSV', choices=['TSV', 'SQL', 'DB']) -parser.add_argument('-i', '--input_dir', help='source directory of interface lists') -parser.add_argument('-o', '--output_dir', help='destination directory for outputs') -parser.add_argument('-u', '--update_lists', action='store_true', help='downloads lists from server') - -args = parser.parse_args() -logging.info("mode:%s", args.mode) -logging.info("input_dir:%s", args.input_dir) -logging.info("output_dir:%s", args.output_dir) -logging.info("update_lists:%s", args.update_lists) - -if args.update_lists: - from idp.utils import listdownloader - logging.info("Downloading IMDB dumps, this may take a while depending on your connection speed") - listdownloader.download() - -logging.info("Parsing, please wait. This may take very long time...") - -# preparing preferences map -if args.mode: - mode = args.mode -else: #default - mode = "TSV" - -if args.input_dir: - inputDir = args.input_dir -else: - inputDir = INPUT_DIR - -if args.input_dir: - outputDir = args.output_dir -else: - outputDir = OUTPUT_DIR - -preferencesMap = { - "mode":mode, - "inputDir": inputDir, - "outputDir": outputDir -} - -ParsingHelper.parse_all(preferencesMap) - +#!/usr/bin/env python3 + +""" +This file is part of imdb-data-parser. + +imdb-data-parser 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 3 of the License, or +(at your option) any later version. + +imdb-data-parser 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 imdb-data-parser. If not, see . +""" + +import sys +import argparse +import logging +from idp.utils.loggerprovider import * +from idp.parser.parsinghelper import ParsingHelper +from idp.settings import * + +# check python version +if sys.version_info.major != 3: + sys.exit("Error: wrong version! You need to install python3 to run this application properly.") + +initialize_logger() + +parser = argparse.ArgumentParser(description="an IMDB data parser") +parser.add_argument('-m', '--mode', help='Parsing mode, defines output of parsing process. Default: CSV', choices=['TSV', 'SQL', 'DB']) +parser.add_argument('-i', '--input_dir', help='source directory of interface lists') +parser.add_argument('-o', '--output_dir', help='destination directory for outputs') +parser.add_argument('-u', '--update_lists', action='store_true', help='downloads lists from server') + +args = parser.parse_args() +logging.info("mode:%s", args.mode) +logging.info("input_dir:%s", args.input_dir) +logging.info("output_dir:%s", args.output_dir) +logging.info("update_lists:%s", args.update_lists) + +if args.update_lists: + from idp.utils import listdownloader + logging.info("Downloading IMDB dumps, this may take a while depending on your connection speed") + listdownloader.download() + +logging.info("Parsing, please wait. This may take very long time...") + +# preparing preferences map +if args.mode: + mode = args.mode +else: #default + mode = "TSV" + +if args.input_dir: + inputDir = args.input_dir +else: + inputDir = INPUT_DIR + +if args.input_dir: + outputDir = args.output_dir +else: + outputDir = OUTPUT_DIR + +preferencesMap = { + "mode":mode, + "inputDir": inputDir, + "outputDir": outputDir +} + +ParsingHelper.parse_all(preferencesMap) + print ("All done, enjoy ;)") \ No newline at end of file diff --git a/logging.conf b/logging.conf deleted file mode 100644 index 03d062d..0000000 --- a/logging.conf +++ /dev/null @@ -1,21 +0,0 @@ -[loggers] -keys=root - -[handlers] -keys=consoleHandler - -[formatters] -keys=simpleFormatter - -[logger_root] -level=INFO -handlers=consoleHandler - -[handler_consoleHandler] -class=StreamHandler -level=DEBUG -formatter=simpleFormatter -args=(sys.stdout,) - -[formatter_simpleFormatter] -format=%(levelname)s - %(message)s \ No newline at end of file From 39e207495757325e78adf1e917dd65b142549b77 Mon Sep 17 00:00:00 2001 From: Aykut Akin Date: Thu, 31 Jan 2013 21:16:27 +0200 Subject: [PATCH 23/58] fixes #14 --- idp/utils/loggerprovider.py | 7 +++---- imdbparser.py | 35 ++++++++++++++++++++--------------- 2 files changed, 23 insertions(+), 19 deletions(-) diff --git a/idp/utils/loggerprovider.py b/idp/utils/loggerprovider.py index da5a9f4..250cad4 100644 --- a/idp/utils/loggerprovider.py +++ b/idp/utils/loggerprovider.py @@ -15,11 +15,10 @@ along with imdb-data-parser. If not, see . """ -from ..settings import * import logging import os.path -def initialize_logger(): +def initialize_logger(preferencesMap): logger = logging.getLogger() logger.setLevel(logging.INFO) @@ -31,14 +30,14 @@ def initialize_logger(): logger.addHandler(ch) # create error file handler and set level to error - ch = logging.FileHandler(os.path.join(OUTPUT_DIR, 'imdbparserError.log'),'w', encoding=None, delay="true") + ch = logging.FileHandler(os.path.join(preferencesMap['outputDir'], 'imdbparserError.log'),'w', encoding=None, delay="true") ch.setLevel(logging.ERROR) formatter = logging.Formatter("%(levelname)s - %(message)s") ch.setFormatter(formatter) logger.addHandler(ch) # create info file handler and set level to info - ch = logging.FileHandler(os.path.join(OUTPUT_DIR, 'imdbparserAll.log'),'w') + ch = logging.FileHandler(os.path.join(preferencesMap['outputDir'], 'imdbparserAll.log'),'w') ch.setLevel(logging.INFO) formatter = logging.Formatter("%(levelname)s - %(message)s") ch.setFormatter(formatter) diff --git a/imdbparser.py b/imdbparser.py index 8ef45ed..42159fb 100755 --- a/imdbparser.py +++ b/imdbparser.py @@ -23,13 +23,12 @@ from idp.utils.loggerprovider import * from idp.parser.parsinghelper import ParsingHelper from idp.settings import * +import datetime # check python version if sys.version_info.major != 3: sys.exit("Error: wrong version! You need to install python3 to run this application properly.") -initialize_logger() - parser = argparse.ArgumentParser(description="an IMDB data parser") parser.add_argument('-m', '--mode', help='Parsing mode, defines output of parsing process. Default: CSV', choices=['TSV', 'SQL', 'DB']) parser.add_argument('-i', '--input_dir', help='source directory of interface lists') @@ -37,17 +36,6 @@ parser.add_argument('-u', '--update_lists', action='store_true', help='downloads lists from server') args = parser.parse_args() -logging.info("mode:%s", args.mode) -logging.info("input_dir:%s", args.input_dir) -logging.info("output_dir:%s", args.output_dir) -logging.info("update_lists:%s", args.update_lists) - -if args.update_lists: - from idp.utils import listdownloader - logging.info("Downloading IMDB dumps, this may take a while depending on your connection speed") - listdownloader.download() - -logging.info("Parsing, please wait. This may take very long time...") # preparing preferences map if args.mode: @@ -61,9 +49,12 @@ inputDir = INPUT_DIR if args.input_dir: - outputDir = args.output_dir + outputDir = os.path.join(args.output_dir,datetime.date.today().isoformat() + ' ImdbParserOutput') else: - outputDir = OUTPUT_DIR + outputDir = os.path.join(OUTPUT_DIR,datetime.date.today().isoformat() + ' ImdbParserOutput') + +if not os.path.exists(outputDir): + os.makedirs(outputDir) preferencesMap = { "mode":mode, @@ -71,6 +62,20 @@ "outputDir": outputDir } +initialize_logger(preferencesMap) + +logging.info("mode:%s", args.mode) +logging.info("input_dir:%s", args.input_dir) +logging.info("output_dir:%s", args.output_dir) +logging.info("update_lists:%s", args.update_lists) + +if args.update_lists: + from idp.utils import listdownloader + logging.info("Downloading IMDB dumps, this may take a while depending on your connection speed") + listdownloader.download() + +logging.info("Parsing, please wait. This may take very long time...") + ParsingHelper.parse_all(preferencesMap) print ("All done, enjoy ;)") \ No newline at end of file From ecb0352b8de31b1f759095ad931bf621e8a26878 Mon Sep 17 00:00:00 2001 From: Aykut Akin Date: Thu, 31 Jan 2013 22:42:49 +0200 Subject: [PATCH 24/58] Adds time to folder and initial commit for trivia --- idp/parser/triviaparser.py | 59 +++++++++++++++++++ ...loggerprovider.py => loggerinitializer.py} | 0 imdbparser.py | 7 ++- 3 files changed, 63 insertions(+), 3 deletions(-) create mode 100644 idp/parser/triviaparser.py rename idp/utils/{loggerprovider.py => loggerinitializer.py} (100%) diff --git a/idp/parser/triviaparser.py b/idp/parser/triviaparser.py new file mode 100644 index 0000000..4691ca3 --- /dev/null +++ b/idp/parser/triviaparser.py @@ -0,0 +1,59 @@ +""" +This file is part of imdb-data-parser. + +imdb-data-parser 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 3 of the License, or +(at your option) any later version. + +imdb-data-parser 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 imdb-data-parser. If not, see . +""" + +from .baseparser import BaseParser +from ..utils.regexhelper import * +from ..utils.filehandler import IMDBList +import logging + +class TriviaParser(BaseParser): + """ + RegExp: #TODO + pattern: + flags: g + capturing groups: + """ + + # properties + baseMatcherPattern = "" + inputFileName = "trivia.list" + numberOfLinesToBeSkipped = 15 + scripts = { #TODO: fill + 'drop' : '', + 'create' : '', + 'insert' : '' + } + + def __init__(self, preferencesMap): + self.mode = preferencesMap['mode'] + self.list = IMDBList(self.inputFileName, preferencesMap) + self.inputFile = self.list.get_input_file() + self.outputFile = self.list.get_output_file() + + # specific to this class + self.title = "" + self.plot = "" + + def parse_into_tsv(self, matcher): + isMatch = matcher.match(self.baseMatcherPattern) + + if(isMatch): + #TODO + + def parse_into_db(self, matcher): + #TODO + pass diff --git a/idp/utils/loggerprovider.py b/idp/utils/loggerinitializer.py similarity index 100% rename from idp/utils/loggerprovider.py rename to idp/utils/loggerinitializer.py diff --git a/imdbparser.py b/imdbparser.py index 42159fb..d889e42 100755 --- a/imdbparser.py +++ b/imdbparser.py @@ -20,7 +20,7 @@ import sys import argparse import logging -from idp.utils.loggerprovider import * +from idp.utils.loggerinitializer import * from idp.parser.parsinghelper import ParsingHelper from idp.settings import * import datetime @@ -48,10 +48,11 @@ else: inputDir = INPUT_DIR +postfix = datetime.datetime.now().strftime("%Y-%m-%d_%H%M%S") + ' ImdbParserOutput' if args.input_dir: - outputDir = os.path.join(args.output_dir,datetime.date.today().isoformat() + ' ImdbParserOutput') + outputDir = os.path.join(args.output_dir, postfix) else: - outputDir = os.path.join(OUTPUT_DIR,datetime.date.today().isoformat() + ' ImdbParserOutput') + outputDir = os.path.join(OUTPUT_DIR, postfix) if not os.path.exists(outputDir): os.makedirs(outputDir) From 9eca8f8dc397813b960f5e348f3384472c308e51 Mon Sep 17 00:00:00 2001 From: Aykut Akin Date: Sat, 9 Feb 2013 18:13:12 +0200 Subject: [PATCH 25/58] Adds trivia parser --- idp/parser/triviaparser.py | 130 ++++++++++++++++++++----------------- 1 file changed, 71 insertions(+), 59 deletions(-) diff --git a/idp/parser/triviaparser.py b/idp/parser/triviaparser.py index 4691ca3..94f80d1 100644 --- a/idp/parser/triviaparser.py +++ b/idp/parser/triviaparser.py @@ -1,59 +1,71 @@ -""" -This file is part of imdb-data-parser. - -imdb-data-parser 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 3 of the License, or -(at your option) any later version. - -imdb-data-parser 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 imdb-data-parser. If not, see . -""" - -from .baseparser import BaseParser -from ..utils.regexhelper import * -from ..utils.filehandler import IMDBList -import logging - -class TriviaParser(BaseParser): - """ - RegExp: #TODO - pattern: - flags: g - capturing groups: - """ - - # properties - baseMatcherPattern = "" - inputFileName = "trivia.list" - numberOfLinesToBeSkipped = 15 - scripts = { #TODO: fill - 'drop' : '', - 'create' : '', - 'insert' : '' - } - - def __init__(self, preferencesMap): - self.mode = preferencesMap['mode'] - self.list = IMDBList(self.inputFileName, preferencesMap) - self.inputFile = self.list.get_input_file() - self.outputFile = self.list.get_output_file() - - # specific to this class - self.title = "" - self.plot = "" - - def parse_into_tsv(self, matcher): - isMatch = matcher.match(self.baseMatcherPattern) - - if(isMatch): - #TODO - - def parse_into_db(self, matcher): - #TODO - pass +""" +This file is part of imdb-data-parser. + +imdb-data-parser 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 3 of the License, or +(at your option) any later version. + +imdb-data-parser 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 imdb-data-parser. If not, see . +""" + +from .baseparser import BaseParser +from ..utils.regexhelper import * +from ..utils.filehandler import IMDBList +import logging + +class TriviaParser(BaseParser): + """ + RegExp: /((.+?) (.*))|\n/g + pattern: ((.+?) (.*))|\n + flags: g + 2 capturing groups: + group 1: (.+?) type of the line + group 2: (.*) if the line-type is - then this line is plot, not the whole but one line of it + if the line-type is # then this line is movie + """ + + # properties + baseMatcherPattern = "((.+?) (.*))|\n" + inputFileName = "trivia.list" + numberOfLinesToBeSkipped = 15 + scripts = { #TODO: fill + 'drop' : '', + 'create' : '', + 'insert' : '' + } + + title = "" + trivia = "" + + def __init__(self, preferencesMap): + self.mode = preferencesMap['mode'] + self.list = IMDBList(self.inputFileName, preferencesMap) + self.inputFile = self.list.get_input_file() + self.outputFile = self.list.get_output_file() + + def parse_into_tsv(self, matcher): + isMatch = matcher.match(self.baseMatcherPattern) + + if(isMatch): + if(matcher.group(2) == "#"): #Title + self.title = matcher.group(3) + elif(matcher.group(2) == "-"): #Descriptive text + self.trivia = matcher.group(3) + elif(matcher.group(2) == " "): + self.trivia += ' ' + matcher.group(3) + else: + self.outputFile.write(self.title + self.seperator + self.trivia + "\n") + else: + logging.critical("This line is fucked up: " + matcher.get_last_string()) + self.fuckedUpCount += 1 + + def parse_into_db(self, matcher): + #TODO + pass From d46dfb41f37ae6b4fc8e004df74ac19ce94e4b17 Mon Sep 17 00:00:00 2001 From: Destan Sarpkaya Date: Tue, 26 Feb 2013 11:40:18 +0200 Subject: [PATCH 26/58] fix 'No such file or directory' error ...by converting line endings to unix endings --- imdbparser.py | 167 ++++++++++++++++++++++++++------------------------ 1 file changed, 86 insertions(+), 81 deletions(-) diff --git a/imdbparser.py b/imdbparser.py index d889e42..fd72f5b 100755 --- a/imdbparser.py +++ b/imdbparser.py @@ -1,82 +1,87 @@ -#!/usr/bin/env python3 - -""" -This file is part of imdb-data-parser. - -imdb-data-parser 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 3 of the License, or -(at your option) any later version. - -imdb-data-parser 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 imdb-data-parser. If not, see . -""" - -import sys -import argparse -import logging -from idp.utils.loggerinitializer import * -from idp.parser.parsinghelper import ParsingHelper -from idp.settings import * -import datetime - -# check python version -if sys.version_info.major != 3: - sys.exit("Error: wrong version! You need to install python3 to run this application properly.") - -parser = argparse.ArgumentParser(description="an IMDB data parser") -parser.add_argument('-m', '--mode', help='Parsing mode, defines output of parsing process. Default: CSV', choices=['TSV', 'SQL', 'DB']) -parser.add_argument('-i', '--input_dir', help='source directory of interface lists') -parser.add_argument('-o', '--output_dir', help='destination directory for outputs') -parser.add_argument('-u', '--update_lists', action='store_true', help='downloads lists from server') - -args = parser.parse_args() - -# preparing preferences map -if args.mode: - mode = args.mode -else: #default - mode = "TSV" - -if args.input_dir: - inputDir = args.input_dir -else: - inputDir = INPUT_DIR - -postfix = datetime.datetime.now().strftime("%Y-%m-%d_%H%M%S") + ' ImdbParserOutput' -if args.input_dir: - outputDir = os.path.join(args.output_dir, postfix) -else: - outputDir = os.path.join(OUTPUT_DIR, postfix) - -if not os.path.exists(outputDir): - os.makedirs(outputDir) - -preferencesMap = { - "mode":mode, - "inputDir": inputDir, - "outputDir": outputDir -} - -initialize_logger(preferencesMap) - -logging.info("mode:%s", args.mode) -logging.info("input_dir:%s", args.input_dir) -logging.info("output_dir:%s", args.output_dir) -logging.info("update_lists:%s", args.update_lists) - -if args.update_lists: - from idp.utils import listdownloader - logging.info("Downloading IMDB dumps, this may take a while depending on your connection speed") - listdownloader.download() - -logging.info("Parsing, please wait. This may take very long time...") - -ParsingHelper.parse_all(preferencesMap) - +#!/usr/bin/env python3 + +""" +This file is part of imdb-data-parser. + +imdb-data-parser 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 3 of the License, or +(at your option) any later version. + +imdb-data-parser 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 imdb-data-parser. If not, see . +""" + +""" +Dealing with ": No such file or directory" error: +http://stackoverflow.com/a/8735625/878361 +""" + +import sys +import argparse +import logging +from idp.utils.loggerinitializer import * +from idp.parser.parsinghelper import ParsingHelper +from idp.settings import * +import datetime + +# check python version +if sys.version_info.major != 3: + sys.exit("Error: wrong version! You need to install python3 to run this application properly.") + +parser = argparse.ArgumentParser(description="an IMDB data parser") +parser.add_argument('-m', '--mode', help='Parsing mode, defines output of parsing process. Default: CSV', choices=['TSV', 'SQL', 'DB']) +parser.add_argument('-i', '--input_dir', help='source directory of interface lists') +parser.add_argument('-o', '--output_dir', help='destination directory for outputs') +parser.add_argument('-u', '--update_lists', action='store_true', help='downloads lists from server') + +args = parser.parse_args() + +# preparing preferences map +if args.mode: + mode = args.mode +else: #default + mode = "TSV" + +if args.input_dir: + inputDir = args.input_dir +else: + inputDir = INPUT_DIR + +postfix = datetime.datetime.now().strftime("%Y-%m-%d_%H%M%S") + ' ImdbParserOutput' +if args.input_dir: + outputDir = os.path.join(args.output_dir, postfix) +else: + outputDir = os.path.join(OUTPUT_DIR, postfix) + +if not os.path.exists(outputDir): + os.makedirs(outputDir) + +preferencesMap = { + "mode":mode, + "inputDir": inputDir, + "outputDir": outputDir +} + +initialize_logger(preferencesMap) + +logging.info("mode:%s", args.mode) +logging.info("input_dir:%s", args.input_dir) +logging.info("output_dir:%s", args.output_dir) +logging.info("update_lists:%s", args.update_lists) + +if args.update_lists: + from idp.utils import listdownloader + logging.info("Downloading IMDB dumps, this may take a while depending on your connection speed") + listdownloader.download() + +logging.info("Parsing, please wait. This may take very long time...") + +ParsingHelper.parse_all(preferencesMap) + print ("All done, enjoy ;)") \ No newline at end of file From 2c5b96fe6f72d2b412a59fca953f528ed14cd48e Mon Sep 17 00:00:00 2001 From: Destan Sarpkaya Date: Wed, 27 Feb 2013 17:16:42 +0200 Subject: [PATCH 27/58] add comment to debugging snippet, format comments --- idp/parser/parsinghelper.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/idp/parser/parsinghelper.py b/idp/parser/parsinghelper.py index 21602ff..39882e9 100644 --- a/idp/parser/parsinghelper.py +++ b/idp/parser/parsinghelper.py @@ -20,7 +20,9 @@ import traceback class ParsingHelper(object): - """ParsingHelper manages parsing order""" + """ + ParsingHelper manages parsing order + """ @staticmethod def parse_one(item, preferencesMap): @@ -51,7 +53,6 @@ def get_parser_class_for(itemName): traceback.print_exc() logging.info("Parsing finished for item: " + item) - @staticmethod def parse_all(preferencesMap): for item in settings.LISTS: @@ -59,10 +60,13 @@ def parse_all(preferencesMap): logging.info("Parsing finished.") if __name__ == "__main__": - print("hede") + """ + For debugging purposes + """ + print("Parsing only one file for debugging purposes...") preferencesMap = { "mode":"TSV", - "inputDir": "/home/xaph/imdb_lists/", - "outputDir": "/home/xaph/idp_files/" + "inputDir": "../../samples/imdb_lists/", + "outputDir": "../../samples/idp_files/" } ParsingHelper.parse_one("movies", preferencesMap) \ No newline at end of file From d791cb9f5a3901355df2983604b0fbe8ddbe8b60 Mon Sep 17 00:00:00 2001 From: Destan Sarpkaya Date: Wed, 27 Feb 2013 21:33:12 +0200 Subject: [PATCH 28/58] add comments --- idp/parser/baseparser.py | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/idp/parser/baseparser.py b/idp/parser/baseparser.py index 6fe451d..e9a8685 100644 --- a/idp/parser/baseparser.py +++ b/idp/parser/baseparser.py @@ -20,7 +20,22 @@ from ..utils.regexhelper import * class BaseParser(metaclass=ABCMeta): - """Common methods for all parser classes""" + """ + Base class for all parser classes + + This class holds common methods for all parser classes and + must be implemented by any Parser class + + Implementing classes' responsibilities are as follows: + * Implement parse_into_tsv function + * Implement parse_into_db function + * Calculate fuckedUpCount and store in self.fuckedUpCount + * Define following properties: + - baseMatcherPattern + - inputFileName + - numberOfLinesToBeSkipped + - scripts + """ seperator = "\t" #TODO: get from settings @@ -51,10 +66,11 @@ def start_processing(self): counter = 0 numberOfProcessedLines = 0 - for line in self.inputFile : + for line in self.inputFile : #assuming the file is opened in the subclass before here if(numberOfProcessedLines >= self.numberOfLinesToBeSkipped): #end of data - if("--------------" in line): + #TODO: get from subclass, assume '-----------' as default + if("--------------" in line): break matcher = RegExHelper(line) From 438c98b09260dea4e4261e53ca29720fd19f9f40 Mon Sep 17 00:00:00 2001 From: Zafer CAKMAK Date: Sun, 3 Mar 2013 23:31:12 +0000 Subject: [PATCH 29/58] partial fix #11: db class implemented - a new db class waits us. it can create new tables and inserts data - tests for db class added - readme updated. psycopg2 added as requirement --- README.md | 1 + idp/utils/dbhandler.py | 47 ++++++++++++++++++++++++++++ idp/utils/test/dbhandler_test.py | 53 ++++++++++++++++++++++++++++++++ 3 files changed, 101 insertions(+) create mode 100644 idp/utils/dbhandler.py create mode 100644 idp/utils/test/dbhandler_test.py diff --git a/README.md b/README.md index 602c879..38d88d0 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ imdb-data-parser is a free software licensed by GPLv3. Requirements ================ Python 3.x +python3-psycopg2 Configuring ================ diff --git a/idp/utils/dbhandler.py b/idp/utils/dbhandler.py new file mode 100644 index 0000000..1654770 --- /dev/null +++ b/idp/utils/dbhandler.py @@ -0,0 +1,47 @@ +""" +This file is part of imdb-data-parser. + +imdb-data-parser 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 3 of the License, or +(at your option) any later version. + +imdb-data-parser 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 imdb-data-parser. If not, see . +""" + +import psycopg2 +import logging + +class DB(object): + def __init__(self, dbsettings): + self.conn = psycopg2.connect("hostaddr="+dbsettings['DBHOST']+" user="+dbsettings['DBUSER']+" password="+dbsettings['DBPASSWORD']+" dbname="+dbsettings['DBNAME']+" connect_timeout=10") + self.cur = self.conn.cursor() + + def __del__(self): + self.cur.close() + self.conn.close() + + def create_table(self, table_name, create_query): + try: + logging.info("query is "+create_query) + self.cur.execute("DROP TABLE IF EXISTS "+table_name) + logging.info("dropped table "+table_name) + self.cur.execute(create_query) + self.conn.commit() + logging.info("committed changes to db") + except Exception as e: + logging.error("db creation error: %s", e) + + def insert(self, table_name, data_dict): + try: + query = "INSERT INTO "+table_name+"("+", ".join(data_dict.keys())+") VALUES ("+", ".join(['%s']*len(data_dict.keys()))+")" + self.cur.execute(query, list(data_dict.values())) + self.conn.commit() + except Exception as e: + logging.error("db insertion error: %s", e) diff --git a/idp/utils/test/dbhandler_test.py b/idp/utils/test/dbhandler_test.py new file mode 100644 index 0000000..efb6a56 --- /dev/null +++ b/idp/utils/test/dbhandler_test.py @@ -0,0 +1,53 @@ +""" +This file is part of imdb-data-parser. + +imdb-data-parser 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 3 of the License, or +(at your option) any later version. + +imdb-data-parser 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 imdb-data-parser. If not, see . +""" + +import unittest +import psycopg2 +from idp.utils import dbhandler +from idp import settings + +class DBTests(unittest.TestCase): + def setUp(self): + dbsettings={'DBHOST': settings.DBHOST, 'DBUSER': settings.DBUSER, 'DBPASSWORD': settings.DBPASSWORD, 'DBNAME': settings.DBNAME} + self.db = dbhandler.DB(dbsettings) + self.conn = psycopg2.connect("hostaddr="+dbsettings['DBHOST']+" user="+dbsettings['DBUSER']+" password="+dbsettings['DBPASSWORD']+" dbname="+dbsettings['DBNAME']+" connect_timeout=10") + self.cur = self.conn.cursor() + + def tearDown(self): + self.cur.close() + self.conn.close() + + def test_create_table(self): + self.cur.execute("DROP TABLE IF EXISTS test") + self.conn.commit() + self.db.create_table('test', "CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);") + self.cur.execute("SELECT * FROM pg_catalog.pg_tables where tablename='test'") + self.assertEqual(1, self.cur.rowcount) + + def test_insert_table(self): + self.cur.execute("CREATE TABLE IF NOT EXISTS unittest(id serial PRIMARY KEY, num integer, data varchar);") + self.conn.commit() + self.cur.execute("select * from unittest") + before=self.cur.rowcount + values={'num':12, 'data':'hede'} + self.db.insert("unittest", values) + self.cur.execute("select * from unittest") + after=self.cur.rowcount + self.assertEqual(before+1, after) + +if __name__ == '__main__': + unittest.main() From ca56e0517c8e0e7076fe8b05bfa0cfcec8ed8420 Mon Sep 17 00:00:00 2001 From: Yasa Akbulut Date: Tue, 5 Mar 2013 15:21:18 +0200 Subject: [PATCH 30/58] add python-google-api-python-client dependency to README --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 38d88d0..684b5c6 100644 --- a/README.md +++ b/README.md @@ -9,8 +9,9 @@ imdb-data-parser is a free software licensed by GPLv3. Requirements ================ -Python 3.x -python3-psycopg2 +* Python 3.x +* python3-psycopg2 +* python-google-api-python-client Configuring ================ From 0f3498262f8d1f187c47c39614e0432247c205dc Mon Sep 17 00:00:00 2001 From: Yasa Akbulut Date: Tue, 5 Mar 2013 15:26:14 +0200 Subject: [PATCH 31/58] fix wrong package name. doh! --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 684b5c6..8551abc 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ Requirements ================ * Python 3.x * python3-psycopg2 -* python-google-api-python-client +* google-api-python-client Configuring ================ From 48554a18fda16e0d9ef77fa4d9587f58d6865339 Mon Sep 17 00:00:00 2001 From: Yasa Akbulut Date: Tue, 5 Mar 2013 16:22:51 +0200 Subject: [PATCH 32/58] add initial version of freebaseagent. --- idp/utils/freebaseagent.py | 57 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 idp/utils/freebaseagent.py diff --git a/idp/utils/freebaseagent.py b/idp/utils/freebaseagent.py new file mode 100644 index 0000000..20ee5f6 --- /dev/null +++ b/idp/utils/freebaseagent.py @@ -0,0 +1,57 @@ +import json +import urllib + +class FreebaseAgent(object): + + def __init__(self): + super(FreebaseAgent, self).__init__() + self.API_KEY = 'YOUR-API-KEY-GOES-HERE' #TODO read these values from config + self.topic_service_url = 'https://www.googleapis.com/freebase/v1/topic' + self.search_service_url = 'https://www.googleapis.com/freebase/v1/search' + + def getImdbId(self): + mid = self.getTopicId(args.movieName) + topic = self.getTopic(mid) + return topic + + def getTopicId(self, name, entityType='/film/film'): + params = { + 'query': name, + 'type': entityType, + 'limit': 1 + } + url = self.search_service_url + '?' + urllib.urlencode(params) + response = json.loads(urllib.urlopen(url).read()) + + for result in response.get('result'): + mid = result.get('mid', None) + return mid + return None + + def getTopic(self, mid): + params = { + 'filter': '/type/object/key' + } + url = self.topic_service_url + mid + '?' + urllib.urlencode(params) + topic = json.loads(urllib.urlopen(url).read()) + + for property in topic['property']: + for value in topic['property'][property]['values']: + if value['text'].startswith('/authority/imdb/title'): + return value['text'].split('/')[-1] + + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Retrieve imdb id from freebase.") + parser.add_argument('movieName', help='The name of the movie') + args = parser.parse_args() + + agent = FreebaseAgent() + mid = agent.getTopicId(args.movieName) + print 'freebase topic id (mid) is', mid + topic = agent.getTopic(mid) + print 'imdb id is', topic, 'so the url is http://www.imdb.com/title/'+topic + print agent.getImdbId() \ No newline at end of file From b0f067bad1bbaa2d403100ffa0ee6afe3bb4cca4 Mon Sep 17 00:00:00 2001 From: Yasa Akbulut Date: Thu, 7 Mar 2013 16:54:18 +0200 Subject: [PATCH 33/58] remove unneccessary dependency --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 8551abc..50397c8 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,6 @@ Requirements ================ * Python 3.x * python3-psycopg2 -* google-api-python-client Configuring ================ From 9457f95903fb94e22d2c2e64b3e954114c05defd Mon Sep 17 00:00:00 2001 From: Yasa Akbulut Date: Thu, 7 Mar 2013 18:37:17 +0200 Subject: [PATCH 34/58] add comments, missing parameter in getImdbId() --- idp/utils/freebaseagent.py | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/idp/utils/freebaseagent.py b/idp/utils/freebaseagent.py index 20ee5f6..387e7e1 100644 --- a/idp/utils/freebaseagent.py +++ b/idp/utils/freebaseagent.py @@ -2,6 +2,11 @@ import urllib class FreebaseAgent(object): + """Helper class to retrieve IMDb ids from freebase. + + Currently only supports movies. TV series support will + hopefully be added if need arises. + """ def __init__(self): super(FreebaseAgent, self).__init__() @@ -9,12 +14,21 @@ def __init__(self): self.topic_service_url = 'https://www.googleapis.com/freebase/v1/topic' self.search_service_url = 'https://www.googleapis.com/freebase/v1/search' - def getImdbId(self): - mid = self.getTopicId(args.movieName) + def getImdbId(self, movieName): + """Returns the IMDb id of a movie, given its title. + + The returned title is the one with the highest + freebase confidence score. + + Returns None if no such movie exists in freebase. + """ + mid = self.getTopicId(movieName) topic = self.getTopic(mid) return topic def getTopicId(self, name, entityType='/film/film'): + """Gets the topic id (aka mid, freebase id) of a title. + """ params = { 'query': name, 'type': entityType, @@ -29,6 +43,9 @@ def getTopicId(self, name, entityType='/film/film'): return None def getTopic(self, mid): + """Gets the IMDb id of a freebase topic. Returns None if no + such thing exists. + """ params = { 'filter': '/type/object/key' } @@ -54,4 +71,4 @@ def getTopic(self, mid): print 'freebase topic id (mid) is', mid topic = agent.getTopic(mid) print 'imdb id is', topic, 'so the url is http://www.imdb.com/title/'+topic - print agent.getImdbId() \ No newline at end of file + print agent.getImdbId(args.movieName) \ No newline at end of file From 9cd9b4c171017db15ca657392219b11f2cea3919 Mon Sep 17 00:00:00 2001 From: Destan Sarpkaya Date: Sat, 9 Mar 2013 10:57:32 +0200 Subject: [PATCH 35/58] close #12 use decorators to measure parsing durations * removed old comments and TODOs * added a few docs --- idp/parser/baseparser.py | 18 +++++++----------- idp/parser/parsinghelper.py | 1 + idp/utils/decorators.py | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 40 insertions(+), 11 deletions(-) create mode 100644 idp/utils/decorators.py diff --git a/idp/parser/baseparser.py b/idp/parser/baseparser.py index e9a8685..968d0c0 100644 --- a/idp/parser/baseparser.py +++ b/idp/parser/baseparser.py @@ -18,6 +18,7 @@ from abc import * from ..utils.filehandler import * from ..utils.regexhelper import * +from ..utils.decorators import durationLogged class BaseParser(metaclass=ABCMeta): """ @@ -47,20 +48,16 @@ def parse_into_tsv(self, matcher): def parse_into_db(self, matcher): raise NotImplemented + @durationLogged def start_processing(self): - import time - - startTime = time.time() + ''' + Actual parsing and generation of scripts (tsv & sql) are done here. + ''' if(self.mode == "TSV"): - #self.outputFile = self.get_output_file() pass elif(self.mode == "SQL"): pass - #TODO: drop table if exists - #TODO: create table - # databaseHelper = DatabaseHelper() - # databaseHelper.execute("") self.fuckedUpCount = 0 counter = 0 @@ -99,10 +96,9 @@ def start_processing(self): databaseHelper.close() # fuckedUpCount is calculated in implementing class - logging.info("Finished with " + str(self.fuckedUpCount) + " fucked up line\n") - logging.info("Duration: " + str(round(time.time() - startTime))) + logging.info("Finished with " + str(self.fuckedUpCount) + " fucked up line") - # Below methods force associated properties to be defined in any derived class + ##### Below methods force associated properties to be defined in any derived class ##### @abstractproperty def baseMatcherPattern(self): diff --git a/idp/parser/parsinghelper.py b/idp/parser/parsinghelper.py index 39882e9..41abb8b 100644 --- a/idp/parser/parsinghelper.py +++ b/idp/parser/parsinghelper.py @@ -44,6 +44,7 @@ def get_parser_class_for(itemName): except Exception as e: logging.error("No parser found for: " + item + "\n\tException is: " + str(e)) return 1 + logging.info("___________________") logging.info("Parsing " + item + "...") parser = ParserClass(preferencesMap) try: diff --git a/idp/utils/decorators.py b/idp/utils/decorators.py new file mode 100644 index 0000000..2467237 --- /dev/null +++ b/idp/utils/decorators.py @@ -0,0 +1,32 @@ +""" +This file is part of imdb-data-parser. + +imdb-data-parser 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 3 of the License, or +(at your option) any later version. + +imdb-data-parser 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 imdb-data-parser. If not, see . +""" + +import datetime +import logging + +def durationLogged(func): + ''' + As the name suggests, calculates the execution duration of the function which is annotated by this decorator + ''' + def inner(*args, **kwargs): + startTime = datetime.datetime.now() + retVal = func(*args, **kwargs) + endTime = datetime.datetime.now() + duration = (endTime - startTime).total_seconds() #difference of 2 datetime is a timedelta + logging.info("Parsing took " + str(duration) + " seconds") + return retVal + return inner \ No newline at end of file From de75c865932713b7b2cd79a30feb380972828f6b Mon Sep 17 00:00:00 2001 From: Zafer CAKMAK Date: Sat, 9 Mar 2013 20:22:59 +0000 Subject: [PATCH 36/58] db interactions removed --- README.md | 1 - idp/settings.py.example | 7 +---- idp/utils/dbhandler.py | 47 ---------------------------- idp/utils/test/dbhandler_test.py | 53 -------------------------------- 4 files changed, 1 insertion(+), 107 deletions(-) delete mode 100644 idp/utils/dbhandler.py delete mode 100644 idp/utils/test/dbhandler_test.py diff --git a/README.md b/README.md index 50397c8..17a8c31 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,6 @@ imdb-data-parser is a free software licensed by GPLv3. Requirements ================ * Python 3.x -* python3-psycopg2 Configuring ================ diff --git a/idp/settings.py.example b/idp/settings.py.example index 7e51103..395c2b4 100644 --- a/idp/settings.py.example +++ b/idp/settings.py.example @@ -24,11 +24,6 @@ INTERFACES_DIRECTORY = "pub/misc/movies/database/" #ftp://ftp.funet.fi/pub/mirrors/ftp.imdb.com/pub/ #ftp://ftp.sunet.se/pub/tv+movies/imdb/ -DBHOST = "database_host" -DBNAME = "database_name" -DBUSER = "database_user" -DBPASSWORD = "database_password" - LISTS = [ "directors", "genres", @@ -39,4 +34,4 @@ LISTS = [ "aka-names", "aka-titles", "ratings" -] \ No newline at end of file +] diff --git a/idp/utils/dbhandler.py b/idp/utils/dbhandler.py deleted file mode 100644 index 1654770..0000000 --- a/idp/utils/dbhandler.py +++ /dev/null @@ -1,47 +0,0 @@ -""" -This file is part of imdb-data-parser. - -imdb-data-parser 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 3 of the License, or -(at your option) any later version. - -imdb-data-parser 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 imdb-data-parser. If not, see . -""" - -import psycopg2 -import logging - -class DB(object): - def __init__(self, dbsettings): - self.conn = psycopg2.connect("hostaddr="+dbsettings['DBHOST']+" user="+dbsettings['DBUSER']+" password="+dbsettings['DBPASSWORD']+" dbname="+dbsettings['DBNAME']+" connect_timeout=10") - self.cur = self.conn.cursor() - - def __del__(self): - self.cur.close() - self.conn.close() - - def create_table(self, table_name, create_query): - try: - logging.info("query is "+create_query) - self.cur.execute("DROP TABLE IF EXISTS "+table_name) - logging.info("dropped table "+table_name) - self.cur.execute(create_query) - self.conn.commit() - logging.info("committed changes to db") - except Exception as e: - logging.error("db creation error: %s", e) - - def insert(self, table_name, data_dict): - try: - query = "INSERT INTO "+table_name+"("+", ".join(data_dict.keys())+") VALUES ("+", ".join(['%s']*len(data_dict.keys()))+")" - self.cur.execute(query, list(data_dict.values())) - self.conn.commit() - except Exception as e: - logging.error("db insertion error: %s", e) diff --git a/idp/utils/test/dbhandler_test.py b/idp/utils/test/dbhandler_test.py deleted file mode 100644 index efb6a56..0000000 --- a/idp/utils/test/dbhandler_test.py +++ /dev/null @@ -1,53 +0,0 @@ -""" -This file is part of imdb-data-parser. - -imdb-data-parser 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 3 of the License, or -(at your option) any later version. - -imdb-data-parser 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 imdb-data-parser. If not, see . -""" - -import unittest -import psycopg2 -from idp.utils import dbhandler -from idp import settings - -class DBTests(unittest.TestCase): - def setUp(self): - dbsettings={'DBHOST': settings.DBHOST, 'DBUSER': settings.DBUSER, 'DBPASSWORD': settings.DBPASSWORD, 'DBNAME': settings.DBNAME} - self.db = dbhandler.DB(dbsettings) - self.conn = psycopg2.connect("hostaddr="+dbsettings['DBHOST']+" user="+dbsettings['DBUSER']+" password="+dbsettings['DBPASSWORD']+" dbname="+dbsettings['DBNAME']+" connect_timeout=10") - self.cur = self.conn.cursor() - - def tearDown(self): - self.cur.close() - self.conn.close() - - def test_create_table(self): - self.cur.execute("DROP TABLE IF EXISTS test") - self.conn.commit() - self.db.create_table('test', "CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);") - self.cur.execute("SELECT * FROM pg_catalog.pg_tables where tablename='test'") - self.assertEqual(1, self.cur.rowcount) - - def test_insert_table(self): - self.cur.execute("CREATE TABLE IF NOT EXISTS unittest(id serial PRIMARY KEY, num integer, data varchar);") - self.conn.commit() - self.cur.execute("select * from unittest") - before=self.cur.rowcount - values={'num':12, 'data':'hede'} - self.db.insert("unittest", values) - self.cur.execute("select * from unittest") - after=self.cur.rowcount - self.assertEqual(before+1, after) - -if __name__ == '__main__': - unittest.main() From ef4c6c02e72075cc8bd7f4c0e5bc88eb125904d9 Mon Sep 17 00:00:00 2001 From: Zafer CAKMAK Date: Sun, 10 Mar 2013 00:49:30 +0000 Subject: [PATCH 37/58] #26 #30 alpha stage of db output --- idp/parser/baseparser.py | 2 +- idp/parser/moviesparser.py | 26 ++++++++++++++++++-------- idp/utils/filehandler.py | 2 +- 3 files changed, 20 insertions(+), 10 deletions(-) diff --git a/idp/parser/baseparser.py b/idp/parser/baseparser.py index 968d0c0..7944d36 100644 --- a/idp/parser/baseparser.py +++ b/idp/parser/baseparser.py @@ -67,7 +67,7 @@ def start_processing(self): if(numberOfProcessedLines >= self.numberOfLinesToBeSkipped): #end of data #TODO: get from subclass, assume '-----------' as default - if("--------------" in line): + if("--------------" in line): break matcher = RegExHelper(line) diff --git a/idp/parser/moviesparser.py b/idp/parser/moviesparser.py index 66fb464..d7da12c 100644 --- a/idp/parser/moviesparser.py +++ b/idp/parser/moviesparser.py @@ -26,7 +26,7 @@ class MoviesParser(BaseParser): RegExp: /((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\t+(.*)$/gm pattern: ((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\t+(.*)$ flags: gm - 8 capturing groups: + 8 capturing groups: group 1: #TITLE (UNIQUE KEY) group 2: (.*? \(\S{4,}\)) movie name + year group 3: (\(\S+\)) type ex:(TV) @@ -36,15 +36,16 @@ class MoviesParser(BaseParser): group 7: (\{\{SUSPENDED\}\}) is suspended? group 8: (.*) year """ - + # properties baseMatcherPattern = "((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\t+(.*)$" inputFileName = "movies.list" + #FIXME: zafer: I think using a static number is critical for us. If imdb sends a new file with first 10 line fucked then we're also fucked numberOfLinesToBeSkipped = 15 - scripts = { #TODO: fill - 'drop' : '', - 'create' : '', - 'insert' : '' + scripts = { + 'drop' : 'DROP TABLE IF EXISTS movies;\n', + 'create' : 'CREATE TABLE movies( id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), name VARCHAR(255), year INT );\n', + 'insert' : 'INSERT INTO movies(name, year) VALUES\n' } def __init__(self, preferencesMap): @@ -52,6 +53,10 @@ def __init__(self, preferencesMap): self.list = IMDBList(self.inputFileName, preferencesMap) self.inputFile = self.list.get_input_file() self.outputFile = self.list.get_output_file() + self.f = open("/home/xaph/imdb.sql", "w", encoding='utf-8') + self.f.write(self.scripts['drop']) + self.f.write(self.scripts['create']) + self.f.write(self.scripts['insert']) def parse_into_tsv(self, matcher): isMatch = matcher.match(self.baseMatcherPattern) @@ -63,5 +68,10 @@ def parse_into_tsv(self, matcher): self.fuckedUpCount += 1 def parse_into_db(self, matcher): - #TODO - pass + isMatch = matcher.match(self.baseMatcherPattern) + + if(isMatch): + self.f.write("(\"" + matcher.group(1) + "\", " + matcher.group(8) + "),\n") + else: + logging.critical("This line is fucked up: " + matcher.get_last_string()) + self.fuckedUpCount += 1 diff --git a/idp/utils/filehandler.py b/idp/utils/filehandler.py index 1b513ea..4608735 100644 --- a/idp/utils/filehandler.py +++ b/idp/utils/filehandler.py @@ -118,4 +118,4 @@ def openfile(fullFilePath): if __name__ == "__main__": f = IMDBList("movies.list") print(f.full_path()) - print(f.tsv_path()) \ No newline at end of file + print(f.tsv_path()) From b191b328e160d3f2c45172cf2cf6d33705ab22f1 Mon Sep 17 00:00:00 2001 From: Zafer CAKMAK Date: Sun, 10 Mar 2013 11:31:41 +0000 Subject: [PATCH 38/58] #26 movie names escaped for sql inserts --- idp/parser/moviesparser.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/idp/parser/moviesparser.py b/idp/parser/moviesparser.py index d7da12c..17c7609 100644 --- a/idp/parser/moviesparser.py +++ b/idp/parser/moviesparser.py @@ -18,6 +18,7 @@ from .baseparser import BaseParser from ..utils.filehandler import IMDBList import logging +import re class MoviesParser(BaseParser): """ @@ -71,7 +72,7 @@ def parse_into_db(self, matcher): isMatch = matcher.match(self.baseMatcherPattern) if(isMatch): - self.f.write("(\"" + matcher.group(1) + "\", " + matcher.group(8) + "),\n") + self.f.write("(\"" + re.escape(matcher.group(1)) + "\", " + matcher.group(8) + "),\n") else: logging.critical("This line is fucked up: " + matcher.get_last_string()) self.fuckedUpCount += 1 From d9e11006f1280210559513d1f1c059639f357cf1 Mon Sep 17 00:00:00 2001 From: Zafer CAKMAK Date: Sun, 10 Mar 2013 11:43:44 +0000 Subject: [PATCH 39/58] updated output directory path. removed space character from directory name --- imdbparser.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/imdbparser.py b/imdbparser.py index fd72f5b..ce822c1 100755 --- a/imdbparser.py +++ b/imdbparser.py @@ -53,7 +53,7 @@ else: inputDir = INPUT_DIR -postfix = datetime.datetime.now().strftime("%Y-%m-%d_%H%M%S") + ' ImdbParserOutput' +postfix = datetime.datetime.now().strftime("%Y-%m-%d_%H%M%S") + '_ImdbParserOutput' if args.input_dir: outputDir = os.path.join(args.output_dir, postfix) else: @@ -63,7 +63,7 @@ os.makedirs(outputDir) preferencesMap = { - "mode":mode, + "mode":mode, "inputDir": inputDir, "outputDir": outputDir } @@ -84,4 +84,4 @@ ParsingHelper.parse_all(preferencesMap) -print ("All done, enjoy ;)") \ No newline at end of file +print ("All done, enjoy ;)") From 75cee996e62e79355536ed5cbf799998edc7dcbf Mon Sep 17 00:00:00 2001 From: Zafer CAKMAK Date: Sun, 10 Mar 2013 12:10:48 +0000 Subject: [PATCH 40/58] closes #31 file creation moved to base parser. base parser checks which file to create now --- idp/parser/actorsparser.py | 5 +---- idp/parser/actressesparser.py | 5 +---- idp/parser/baseparser.py | 12 ++++++++++++ idp/parser/directorsparser.py | 9 +++------ idp/parser/genresparser.py | 11 ++++------- idp/parser/moviesparser.py | 11 ++--------- idp/parser/parsinghelper.py | 10 +++++----- idp/parser/plotparser.py | 5 +---- idp/parser/ratingsparser.py | 5 +---- idp/parser/triviaparser.py | 11 ++++------- idp/utils/filehandler.py | 7 ++++++- 11 files changed, 40 insertions(+), 51 deletions(-) diff --git a/idp/parser/actorsparser.py b/idp/parser/actorsparser.py index 9d1389b..29d3386 100644 --- a/idp/parser/actorsparser.py +++ b/idp/parser/actorsparser.py @@ -54,10 +54,7 @@ class ActorsParser(BaseParser): surname = "" def __init__(self, preferencesMap): - self.mode = preferencesMap['mode'] - self.list = IMDBList(self.inputFileName, preferencesMap) - self.inputFile = self.list.get_input_file() - self.outputFile = self.list.get_output_file() + super(ActorsParser, self).__init__(preferencesMap) def parse_into_tsv(self, matcher): isMatch = matcher.match(self.baseMatcherPattern) diff --git a/idp/parser/actressesparser.py b/idp/parser/actressesparser.py index fdf0242..7d133a7 100644 --- a/idp/parser/actressesparser.py +++ b/idp/parser/actressesparser.py @@ -54,10 +54,7 @@ class ActressesParser(BaseParser): surname = "" def __init__(self, preferencesMap): - self.mode = preferencesMap['mode'] - self.list = IMDBList(self.inputFileName, preferencesMap) - self.inputFile = self.list.get_input_file() - self.outputFile = self.list.get_output_file() + super(ActressesParser, self).__init__(preferencesMap) def parse_into_tsv(self, matcher): isMatch = matcher.match(self.baseMatcherPattern) diff --git a/idp/parser/baseparser.py b/idp/parser/baseparser.py index 7944d36..8d3ebde 100644 --- a/idp/parser/baseparser.py +++ b/idp/parser/baseparser.py @@ -40,6 +40,18 @@ class BaseParser(metaclass=ABCMeta): seperator = "\t" #TODO: get from settings + def __init__(self, preferencesMap): + self.mode = preferencesMap['mode'] + self.list = IMDBList(self.inputFileName, preferencesMap) + self.inputFile = self.list.get_input_file() + if (self.mode == "TSV"): + self.outputFile = self.list.get_output_file() + elif (self.mode == "SQL"): + self.sqlFile = self.list.get_sql_file() + self.sqlFile.write(self.scripts['drop']) + self.sqlFile.write(self.scripts['create']) + self.sqlFile.write(self.scripts['insert']) + @abstractmethod def parse_into_tsv(self, matcher): raise NotImplemented diff --git a/idp/parser/directorsparser.py b/idp/parser/directorsparser.py index cee63e2..06f88b4 100644 --- a/idp/parser/directorsparser.py +++ b/idp/parser/directorsparser.py @@ -37,7 +37,7 @@ class DirectorsParser(BaseParser): group 9: (\(.*\)) info group 10: () """ - + # properties baseMatcherPattern = '(.*?)\t+((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\s*(\(.*\)|EDIT)?\s*(<.*>)?$' inputFileName = "directors.list" @@ -52,10 +52,7 @@ class DirectorsParser(BaseParser): surname = "" def __init__(self, preferencesMap): - self.mode = preferencesMap['mode'] - self.list = IMDBList(self.inputFileName, preferencesMap) - self.inputFile = self.list.get_input_file() - self.outputFile = self.list.get_output_file() + super(DirectorsParser, self).__init__(preferencesMap) def parse_into_tsv(self, matcher): isMatch = matcher.match(self.baseMatcherPattern) @@ -69,7 +66,7 @@ def parse_into_tsv(self, matcher): else: self.name = namelist[0] self.surname = "" - + self.outputFile.write(self.name + self.seperator + self.surname + self.seperator + matcher.group(2) + self.seperator + matcher.group(3) + self.seperator + matcher.group(4) + self.seperator + matcher.group(6) + self.seperator + matcher.group(7) + self.seperator + matcher.group(8) + self.seperator + matcher.group(9) + "\n") elif(len(matcher.get_last_string()) == 1): pass diff --git a/idp/parser/genresparser.py b/idp/parser/genresparser.py index 8327b9c..b616967 100644 --- a/idp/parser/genresparser.py +++ b/idp/parser/genresparser.py @@ -25,7 +25,7 @@ class GenresParser(BaseParser): RegExp: /((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\t+(.*)$/gm pattern: ((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\t+(.*)$ flags: gm - 8 capturing groups: + 8 capturing groups: group 1: #TITLE (UNIQUE KEY) group 2: (.*? \(\S{4,}\)) movie name + year group 3: (\(\S+\)) type ex:(TV) @@ -34,8 +34,8 @@ class GenresParser(BaseParser): group 6: ((\(\S+?\)) episode number ex: (#3.1) group 7: (\{\{SUSPENDED\}\}) is suspended? group 8: (.*) genre - """ - + """ + # properties baseMatcherPattern = "((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\t+(.*)$" inputFileName = "genres.list" @@ -47,10 +47,7 @@ class GenresParser(BaseParser): } def __init__(self, preferencesMap): - self.mode = preferencesMap['mode'] - self.list = IMDBList(self.inputFileName, preferencesMap) - self.inputFile = self.list.get_input_file() - self.outputFile = self.list.get_output_file() + super(GenresParser, self).__init__(preferencesMap) def parse_into_tsv(self, matcher): isMatch = matcher.match(self.baseMatcherPattern) diff --git a/idp/parser/moviesparser.py b/idp/parser/moviesparser.py index 17c7609..9b5f693 100644 --- a/idp/parser/moviesparser.py +++ b/idp/parser/moviesparser.py @@ -50,14 +50,7 @@ class MoviesParser(BaseParser): } def __init__(self, preferencesMap): - self.mode = preferencesMap['mode'] - self.list = IMDBList(self.inputFileName, preferencesMap) - self.inputFile = self.list.get_input_file() - self.outputFile = self.list.get_output_file() - self.f = open("/home/xaph/imdb.sql", "w", encoding='utf-8') - self.f.write(self.scripts['drop']) - self.f.write(self.scripts['create']) - self.f.write(self.scripts['insert']) + super(MoviesParser, self).__init__(preferencesMap) def parse_into_tsv(self, matcher): isMatch = matcher.match(self.baseMatcherPattern) @@ -72,7 +65,7 @@ def parse_into_db(self, matcher): isMatch = matcher.match(self.baseMatcherPattern) if(isMatch): - self.f.write("(\"" + re.escape(matcher.group(1)) + "\", " + matcher.group(8) + "),\n") + self.sqlFile.write("(\"" + re.escape(matcher.group(1)) + "\", " + matcher.group(8) + "),\n") else: logging.critical("This line is fucked up: " + matcher.get_last_string()) self.fuckedUpCount += 1 diff --git a/idp/parser/parsinghelper.py b/idp/parser/parsinghelper.py index 41abb8b..c2ebf26 100644 --- a/idp/parser/parsinghelper.py +++ b/idp/parser/parsinghelper.py @@ -36,9 +36,9 @@ def get_parser_class_for(itemName): module = ".".join(parts[:-1]) m = __import__( module ) for comp in parts[1:]: - m = getattr(m, comp) + m = getattr(m, comp) return m - + try: ParserClass = get_parser_class_for(item) except Exception as e: @@ -53,7 +53,7 @@ def get_parser_class_for(itemName): logging.error("Exception occured while parsing item: " + item + "\n\tException is: " + str(e)) traceback.print_exc() logging.info("Parsing finished for item: " + item) - + @staticmethod def parse_all(preferencesMap): for item in settings.LISTS: @@ -66,8 +66,8 @@ def parse_all(preferencesMap): """ print("Parsing only one file for debugging purposes...") preferencesMap = { - "mode":"TSV", + "mode":"TSV", "inputDir": "../../samples/imdb_lists/", "outputDir": "../../samples/idp_files/" } - ParsingHelper.parse_one("movies", preferencesMap) \ No newline at end of file + ParsingHelper.parse_one("movies", preferencesMap) diff --git a/idp/parser/plotparser.py b/idp/parser/plotparser.py index 506ee8e..7fa631e 100644 --- a/idp/parser/plotparser.py +++ b/idp/parser/plotparser.py @@ -42,10 +42,7 @@ class PlotParser(BaseParser): } def __init__(self, preferencesMap): - self.mode = preferencesMap['mode'] - self.list = IMDBList(self.inputFileName, preferencesMap) - self.inputFile = self.list.get_input_file() - self.outputFile = self.list.get_output_file() + super(PlotParser, self).__init__(preferencesMap) # specific to this class self.title = "" diff --git a/idp/parser/ratingsparser.py b/idp/parser/ratingsparser.py index 29f68ba..d94359f 100644 --- a/idp/parser/ratingsparser.py +++ b/idp/parser/ratingsparser.py @@ -49,10 +49,7 @@ class RatingsParser(BaseParser): } def __init__(self, preferencesMap): - self.mode = preferencesMap['mode'] - self.list = IMDBList(self.inputFileName, preferencesMap) - self.inputFile = self.list.get_input_file() - self.outputFile = self.list.get_output_file() + super(RatingsParser, self).__init__(preferencesMap) def parse_into_tsv(self, matcher): isMatch = matcher.match(self.baseMatcherPattern) diff --git a/idp/parser/triviaparser.py b/idp/parser/triviaparser.py index 94f80d1..d02c6c8 100644 --- a/idp/parser/triviaparser.py +++ b/idp/parser/triviaparser.py @@ -25,12 +25,12 @@ class TriviaParser(BaseParser): RegExp: /((.+?) (.*))|\n/g pattern: ((.+?) (.*))|\n flags: g - 2 capturing groups: + 2 capturing groups: group 1: (.+?) type of the line group 2: (.*) if the line-type is - then this line is plot, not the whole but one line of it if the line-type is # then this line is movie """ - + # properties baseMatcherPattern = "((.+?) (.*))|\n" inputFileName = "trivia.list" @@ -40,15 +40,12 @@ class TriviaParser(BaseParser): 'create' : '', 'insert' : '' } - + title = "" trivia = "" def __init__(self, preferencesMap): - self.mode = preferencesMap['mode'] - self.list = IMDBList(self.inputFileName, preferencesMap) - self.inputFile = self.list.get_input_file() - self.outputFile = self.list.get_output_file() + super(TriviaParser, self).__init__(preferencesMap) def parse_into_tsv(self, matcher): isMatch = matcher.match(self.baseMatcherPattern) diff --git a/idp/utils/filehandler.py b/idp/utils/filehandler.py index 4608735..51ab884 100644 --- a/idp/utils/filehandler.py +++ b/idp/utils/filehandler.py @@ -34,6 +34,9 @@ def full_path(self): def tsv_path(self): return os.path.join(self.preferencesMap['outputDir'], self.listname) + ".tsv" + def sql_path(self): + return os.path.join(self.preferencesMap['outputDir'], self.listname) + ".sql" + def get_input_file(self): fullFilePath = self.full_path() logging.info("Trying to find file: %s", fullFilePath) @@ -55,8 +58,10 @@ def get_input_file(self): raise RuntimeError("FileNotFoundError: " + fullFilePath) def get_output_file(self): - return open(self.tsv_path(), "w", encoding='iso-8859-1') + return open(self.tsv_path(), "w", encoding='utf-8') + def get_sql_file(self): + return open(self.sql_path(), "w", encoding='utf-8') def get_full_path(filename, isCompressed = False): From 91d9d363ad4e860c7a567b31cb77aaf773ef9d10 Mon Sep 17 00:00:00 2001 From: Destan Sarpkaya Date: Sun, 10 Mar 2013 18:08:21 +0200 Subject: [PATCH 41/58] fix args logs make use of processed versions of parameters where available instead of raw versions directly from argument list --- imdbparser.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/imdbparser.py b/imdbparser.py index ce822c1..fcf0d33 100755 --- a/imdbparser.py +++ b/imdbparser.py @@ -70,9 +70,9 @@ initialize_logger(preferencesMap) -logging.info("mode:%s", args.mode) -logging.info("input_dir:%s", args.input_dir) -logging.info("output_dir:%s", args.output_dir) +logging.info("mode:%s", mode) +logging.info("input_dir:%s", inputDir) +logging.info("output_dir:%s", outputDir) logging.info("update_lists:%s", args.update_lists) if args.update_lists: From 1d65cb114f755487c4f4ee47eb9174e6695e616c Mon Sep 17 00:00:00 2001 From: Destan Sarpkaya Date: Sun, 10 Mar 2013 21:02:08 +0200 Subject: [PATCH 42/58] edit 'finish log' to be more informative --- idp/parser/parsinghelper.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/idp/parser/parsinghelper.py b/idp/parser/parsinghelper.py index c2ebf26..44e282a 100644 --- a/idp/parser/parsinghelper.py +++ b/idp/parser/parsinghelper.py @@ -58,7 +58,7 @@ def get_parser_class_for(itemName): def parse_all(preferencesMap): for item in settings.LISTS: ParsingHelper.parse_one(item, preferencesMap) - logging.info("Parsing finished.") + logging.info("All parsing finished.") if __name__ == "__main__": """ From bba3d310a2d19bad8a855f7ce277077c1c9e201d Mon Sep 17 00:00:00 2001 From: Destan Sarpkaya Date: Sun, 10 Mar 2013 21:02:30 +0200 Subject: [PATCH 43/58] add log to print outputfolder at the end --- imdbparser.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/imdbparser.py b/imdbparser.py index fcf0d33..bd6088c 100755 --- a/imdbparser.py +++ b/imdbparser.py @@ -84,4 +84,5 @@ ParsingHelper.parse_all(preferencesMap) -print ("All done, enjoy ;)") +logging.info("Check out output folder: %s", outputDir) +print ("All done, enjoy ;)") #don't print this via logger, this is part of the program From 989c6c354022fa14d3b84e28bb6b8d6d691ebef8 Mon Sep 17 00:00:00 2001 From: Destan Sarpkaya Date: Sun, 10 Mar 2013 21:34:56 +0200 Subject: [PATCH 44/58] fix #35 plot parser produces 0 byte in tsv mode * added endOfDumpDelimiter abstract property to BaseParser - Some dump files has comments at the end of the dump as well as at the start. Comments at the start are avoided by numberOfLinesToBeSkipped property and comments at the end are avoided by endOfDumpDelimiter property. - endOfDumpDelimiter property is used for stoppping parsing of associated file when encountered. Hence indicates end of the dump. For each file this may be different or non-exist at all. --- idp/parser/actorsparser.py | 1 + idp/parser/actressesparser.py | 1 + idp/parser/baseparser.py | 7 +++++-- idp/parser/directorsparser.py | 1 + idp/parser/genresparser.py | 1 + idp/parser/moviesparser.py | 1 + idp/parser/plotparser.py | 1 + idp/parser/ratingsparser.py | 1 + idp/parser/triviaparser.py | 1 + 9 files changed, 13 insertions(+), 2 deletions(-) diff --git a/idp/parser/actorsparser.py b/idp/parser/actorsparser.py index 29d3386..4eeba6e 100644 --- a/idp/parser/actorsparser.py +++ b/idp/parser/actorsparser.py @@ -49,6 +49,7 @@ class ActorsParser(BaseParser): 'create' : '', 'insert' : '' } + endOfDumpDelimiter = "" name = "" surname = "" diff --git a/idp/parser/actressesparser.py b/idp/parser/actressesparser.py index 7d133a7..b1f0b50 100644 --- a/idp/parser/actressesparser.py +++ b/idp/parser/actressesparser.py @@ -49,6 +49,7 @@ class ActressesParser(BaseParser): 'create' : '', 'insert' : '' } + endOfDumpDelimiter = "" name = "" surname = "" diff --git a/idp/parser/baseparser.py b/idp/parser/baseparser.py index 8d3ebde..08d1b38 100644 --- a/idp/parser/baseparser.py +++ b/idp/parser/baseparser.py @@ -78,8 +78,7 @@ def start_processing(self): for line in self.inputFile : #assuming the file is opened in the subclass before here if(numberOfProcessedLines >= self.numberOfLinesToBeSkipped): #end of data - #TODO: get from subclass, assume '-----------' as default - if("--------------" in line): + if( self.endOfDumpDelimiter != "" and self.endOfDumpDelimiter in line): break matcher = RegExHelper(line) @@ -127,3 +126,7 @@ def numberOfLinesToBeSkipped(self): @abstractproperty def scripts(self): raise NotImplemented + + @abstractproperty + def endOfDumpDelimiter(self): + raise NotImplemented \ No newline at end of file diff --git a/idp/parser/directorsparser.py b/idp/parser/directorsparser.py index 06f88b4..24d93bd 100644 --- a/idp/parser/directorsparser.py +++ b/idp/parser/directorsparser.py @@ -47,6 +47,7 @@ class DirectorsParser(BaseParser): 'create' : '', 'insert' : '' } + endOfDumpDelimiter = "" name = "" surname = "" diff --git a/idp/parser/genresparser.py b/idp/parser/genresparser.py index b616967..af3e36c 100644 --- a/idp/parser/genresparser.py +++ b/idp/parser/genresparser.py @@ -45,6 +45,7 @@ class GenresParser(BaseParser): 'create' : '', 'insert' : '' } + endOfDumpDelimiter = "" def __init__(self, preferencesMap): super(GenresParser, self).__init__(preferencesMap) diff --git a/idp/parser/moviesparser.py b/idp/parser/moviesparser.py index 9b5f693..d004f4d 100644 --- a/idp/parser/moviesparser.py +++ b/idp/parser/moviesparser.py @@ -48,6 +48,7 @@ class MoviesParser(BaseParser): 'create' : 'CREATE TABLE movies( id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), name VARCHAR(255), year INT );\n', 'insert' : 'INSERT INTO movies(name, year) VALUES\n' } + endOfDumpDelimiter = "" def __init__(self, preferencesMap): super(MoviesParser, self).__init__(preferencesMap) diff --git a/idp/parser/plotparser.py b/idp/parser/plotparser.py index 7fa631e..5391818 100644 --- a/idp/parser/plotparser.py +++ b/idp/parser/plotparser.py @@ -40,6 +40,7 @@ class PlotParser(BaseParser): 'create' : '', 'insert' : '' } + endOfDumpDelimiter = "" def __init__(self, preferencesMap): super(PlotParser, self).__init__(preferencesMap) diff --git a/idp/parser/ratingsparser.py b/idp/parser/ratingsparser.py index d94359f..6385a09 100644 --- a/idp/parser/ratingsparser.py +++ b/idp/parser/ratingsparser.py @@ -47,6 +47,7 @@ class RatingsParser(BaseParser): 'create' : '', 'insert' : '' } + endOfDumpDelimiter = "" def __init__(self, preferencesMap): super(RatingsParser, self).__init__(preferencesMap) diff --git a/idp/parser/triviaparser.py b/idp/parser/triviaparser.py index d02c6c8..9b7d44f 100644 --- a/idp/parser/triviaparser.py +++ b/idp/parser/triviaparser.py @@ -40,6 +40,7 @@ class TriviaParser(BaseParser): 'create' : '', 'insert' : '' } + endOfDumpDelimiter = "" title = "" trivia = "" From d9bb0833a4d252ad30ec1910e6dd359883b53d14 Mon Sep 17 00:00:00 2001 From: Destan Sarpkaya Date: Sun, 10 Mar 2013 21:51:36 +0200 Subject: [PATCH 45/58] add -u option and smth about dump files to README --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index 17a8c31..87603f4 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,12 @@ You need to copy this file as `settings.py` and edit this file before running th cp settings.py.example settings.py your_favourite_editor settings.py +You also need to have dump files at `INPUT_DIR` and you can download dump files from one of the FTP addresses on http://www.imdb.com/interfaces. + +Besides that you can make `imdb-data-parser` dowload dumps for you by giving `-u` argument: + + ~/imdb-data-parser$ ./imdbparser.py -u + Executing --------- From d4149d1b71b2d08c3786f88769e54a373965711c Mon Sep 17 00:00:00 2001 From: Destan Sarpkaya Date: Sun, 10 Mar 2013 22:51:17 +0200 Subject: [PATCH 46/58] fix typo in -h help text --- imdbparser.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imdbparser.py b/imdbparser.py index bd6088c..44ae721 100755 --- a/imdbparser.py +++ b/imdbparser.py @@ -35,7 +35,7 @@ sys.exit("Error: wrong version! You need to install python3 to run this application properly.") parser = argparse.ArgumentParser(description="an IMDB data parser") -parser.add_argument('-m', '--mode', help='Parsing mode, defines output of parsing process. Default: CSV', choices=['TSV', 'SQL', 'DB']) +parser.add_argument('-m', '--mode', help='Parsing mode, defines output of parsing process. Default: TSV', choices=['TSV', 'SQL', 'DB']) parser.add_argument('-i', '--input_dir', help='source directory of interface lists') parser.add_argument('-o', '--output_dir', help='destination directory for outputs') parser.add_argument('-u', '--update_lists', action='store_true', help='downloads lists from server') From e1f1d96d2add08f76de8b760a4cfc6878e5efea4 Mon Sep 17 00:00:00 2001 From: Zafer CAKMAK Date: Sun, 10 Mar 2013 21:56:00 +0000 Subject: [PATCH 47/58] closes #26 sql dumps for movies added. - readme updated - sql dump for movies finished - db removed from modes. we're just creating sql or tsv files --- README.md | 16 ++++++++++++++++ idp/parser/baseparser.py | 8 ++++++-- idp/parser/moviesparser.py | 11 ++++++++--- imdbparser.py | 2 +- 4 files changed, 31 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 87603f4..5caf80b 100644 --- a/README.md +++ b/README.md @@ -35,3 +35,19 @@ Executing You can use -h parameter to see list of optional arguments ~/imdb-data-parser$ ./imdbparser.py -h + +SQL Dumps +--------- +You can use mode parameter to create SQL dumps + + ~/imdb-data-parser$ ./imdbparser.py -h + +Default configuration of MySQL doesn't allow insert data more than 16MB. You need to change your mysql max_allowed_packet size to insert sql dumps. + + max_allowed_packet = 256M + +Our movies data includes series, videos, tv shows for now. You can exclude them by this command: + + grep -v '("\\"' movies.list.sql | grep -v '\\(VG\\)' | grep -v "\\(TV\\)" | grep -v "{" | grep -v "????" | grep -v "(V\\\)" > movies.sql + +Note: SQL dumps tested with only mysql. diff --git a/idp/parser/baseparser.py b/idp/parser/baseparser.py index 08d1b38..09e0a25 100644 --- a/idp/parser/baseparser.py +++ b/idp/parser/baseparser.py @@ -96,7 +96,11 @@ def start_processing(self): numberOfProcessedLines += 1 - self.inputFile.close() + if(self.mode == "TSV"): + self.inputFile.close() + elif(self.mode == "SQL"): + self.sqlFile.write(";") + self.sqlFile.close() if 'outputFile' in locals(): self.outputFile.flush() @@ -129,4 +133,4 @@ def scripts(self): @abstractproperty def endOfDumpDelimiter(self): - raise NotImplemented \ No newline at end of file + raise NotImplemented diff --git a/idp/parser/moviesparser.py b/idp/parser/moviesparser.py index d004f4d..6863e44 100644 --- a/idp/parser/moviesparser.py +++ b/idp/parser/moviesparser.py @@ -45,13 +45,14 @@ class MoviesParser(BaseParser): numberOfLinesToBeSkipped = 15 scripts = { 'drop' : 'DROP TABLE IF EXISTS movies;\n', - 'create' : 'CREATE TABLE movies( id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), name VARCHAR(255), year INT );\n', - 'insert' : 'INSERT INTO movies(name, year) VALUES\n' + 'create' : 'CREATE TABLE movies(title VARCHAR(255) NOT NULL, year INT, PRIMARY KEY(title)) CHARACTER SET utf8 COLLATE utf8_bin;\n', + 'insert' : 'INSERT INTO movies(title, year) VALUES\n' } endOfDumpDelimiter = "" def __init__(self, preferencesMap): super(MoviesParser, self).__init__(preferencesMap) + self.first_one=True def parse_into_tsv(self, matcher): isMatch = matcher.match(self.baseMatcherPattern) @@ -66,7 +67,11 @@ def parse_into_db(self, matcher): isMatch = matcher.match(self.baseMatcherPattern) if(isMatch): - self.sqlFile.write("(\"" + re.escape(matcher.group(1)) + "\", " + matcher.group(8) + "),\n") + if(self.first_one): + self.sqlFile.write("(\"" + re.escape(matcher.group(1)) + "\", " + matcher.group(8) + ")") + self.first_one=False; + else: + self.sqlFile.write(",\n(\"" + re.escape(matcher.group(1)) + "\", " + matcher.group(8) + ")") else: logging.critical("This line is fucked up: " + matcher.get_last_string()) self.fuckedUpCount += 1 diff --git a/imdbparser.py b/imdbparser.py index 44ae721..b3d7176 100755 --- a/imdbparser.py +++ b/imdbparser.py @@ -35,7 +35,7 @@ sys.exit("Error: wrong version! You need to install python3 to run this application properly.") parser = argparse.ArgumentParser(description="an IMDB data parser") -parser.add_argument('-m', '--mode', help='Parsing mode, defines output of parsing process. Default: TSV', choices=['TSV', 'SQL', 'DB']) +parser.add_argument('-m', '--mode', help='Parsing mode, defines output of parsing process. Default: TSV', choices=['TSV', 'SQL']) parser.add_argument('-i', '--input_dir', help='source directory of interface lists') parser.add_argument('-o', '--output_dir', help='destination directory for outputs') parser.add_argument('-u', '--update_lists', action='store_true', help='downloads lists from server') From 7afe94b7a9d520f16cb056b5fa63f8617249caf5 Mon Sep 17 00:00:00 2001 From: Zafer CAKMAK Date: Sun, 10 Mar 2013 22:53:26 +0000 Subject: [PATCH 48/58] #25 genres SQL added. --- idp/parser/genresparser.py | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/idp/parser/genresparser.py b/idp/parser/genresparser.py index af3e36c..3f8a7ff 100644 --- a/idp/parser/genresparser.py +++ b/idp/parser/genresparser.py @@ -40,15 +40,16 @@ class GenresParser(BaseParser): baseMatcherPattern = "((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\t+(.*)$" inputFileName = "genres.list" numberOfLinesToBeSkipped = 378 - scripts = { #TODO: fill - 'drop' : '', - 'create' : '', - 'insert' : '' + scripts = { + 'drop' : 'DROP TABLE IF EXISTS movies_genres;\n', + 'create' : 'CREATE TABLE movies_genres(movie_title VARCHAR(255) NOT NULL, genre VARCHAR(255)) CHARACTER SET utf8 COLLATE utf8_bin;\n', + 'insert' : 'INSERT INTO movies_genres(movie_title, genre) VALUES\n' } endOfDumpDelimiter = "" def __init__(self, preferencesMap): super(GenresParser, self).__init__(preferencesMap) + self.first_one=True def parse_into_tsv(self, matcher): isMatch = matcher.match(self.baseMatcherPattern) @@ -60,5 +61,14 @@ def parse_into_tsv(self, matcher): self.fuckedUpCount += 1 def parse_into_db(self, matcher): - #TODO - pass + isMatch = matcher.match(self.baseMatcherPattern) + + if(isMatch): + if(self.first_one): + self.sqlFile.write("(\"" + re.escape(matcher.group(1)) + "\", \"" + matcher.group(8) + "\")") + self.first_one=False; + else: + self.sqlFile.write(",\n(\"" + re.escape(matcher.group(1)) + "\", \"" + matcher.group(8) + "\")") + else: + logging.critical("This line is fucked up: " + matcher.get_last_string()) + self.fuckedUpCount += 1 From 81d5c98ad78528e873f11b55cdc0b7d08e888406 Mon Sep 17 00:00:00 2001 From: aykut Date: Sat, 16 Mar 2013 17:55:26 +0200 Subject: [PATCH 49/58] adds more parametric db operations --- idp/parser/baseparser.py | 29 +++++++++++------------------ idp/parser/moviesparser.py | 18 ++++++++++++++---- 2 files changed, 25 insertions(+), 22 deletions(-) diff --git a/idp/parser/baseparser.py b/idp/parser/baseparser.py index 09e0a25..4867fb1 100644 --- a/idp/parser/baseparser.py +++ b/idp/parser/baseparser.py @@ -19,6 +19,7 @@ from ..utils.filehandler import * from ..utils.regexhelper import * from ..utils.decorators import durationLogged +from ..utils.dbscripthelper import DbScriptHelper class BaseParser(metaclass=ABCMeta): """ @@ -48,9 +49,10 @@ def __init__(self, preferencesMap): self.outputFile = self.list.get_output_file() elif (self.mode == "SQL"): self.sqlFile = self.list.get_sql_file() - self.sqlFile.write(self.scripts['drop']) - self.sqlFile.write(self.scripts['create']) - self.sqlFile.write(self.scripts['insert']) + self.scripthelper = DbScriptHelper(self.dbtableinfo) + self.sqlFile.write(self.scripthelper.scripts['drop']) + self.sqlFile.write(self.scripthelper.scripts['create']) + self.sqlFile.write(self.scripthelper.scripts['insert']) @abstractmethod def parse_into_tsv(self, matcher): @@ -66,11 +68,6 @@ def start_processing(self): Actual parsing and generation of scripts (tsv & sql) are done here. ''' - if(self.mode == "TSV"): - pass - elif(self.mode == "SQL"): - pass - self.fuckedUpCount = 0 counter = 0 numberOfProcessedLines = 0 @@ -78,7 +75,7 @@ def start_processing(self): for line in self.inputFile : #assuming the file is opened in the subclass before here if(numberOfProcessedLines >= self.numberOfLinesToBeSkipped): #end of data - if( self.endOfDumpDelimiter != "" and self.endOfDumpDelimiter in line): + if(self.endOfDumpDelimiter != "" and self.endOfDumpDelimiter in line): break matcher = RegExHelper(line) @@ -96,9 +93,9 @@ def start_processing(self): numberOfProcessedLines += 1 - if(self.mode == "TSV"): - self.inputFile.close() - elif(self.mode == "SQL"): + self.inputFile.close() + + if(self.mode == "SQL"): self.sqlFile.write(";") self.sqlFile.close() @@ -106,10 +103,6 @@ def start_processing(self): self.outputFile.flush() self.outputFile.close() - if 'databaseHelper' in locals(): - databaseHelper.commit() - databaseHelper.close() - # fuckedUpCount is calculated in implementing class logging.info("Finished with " + str(self.fuckedUpCount) + " fucked up line") @@ -128,9 +121,9 @@ def numberOfLinesToBeSkipped(self): raise NotImplemented @abstractproperty - def scripts(self): + def dbtableinfo(self): raise NotImplemented @abstractproperty def endOfDumpDelimiter(self): - raise NotImplemented + raise NotImplemented diff --git a/idp/parser/moviesparser.py b/idp/parser/moviesparser.py index 6863e44..5f8239c 100644 --- a/idp/parser/moviesparser.py +++ b/idp/parser/moviesparser.py @@ -17,6 +17,7 @@ from .baseparser import BaseParser from ..utils.filehandler import IMDBList +from ..utils.dbscripthelper import DbScriptHelper import logging import re @@ -43,10 +44,19 @@ class MoviesParser(BaseParser): inputFileName = "movies.list" #FIXME: zafer: I think using a static number is critical for us. If imdb sends a new file with first 10 line fucked then we're also fucked numberOfLinesToBeSkipped = 15 - scripts = { - 'drop' : 'DROP TABLE IF EXISTS movies;\n', - 'create' : 'CREATE TABLE movies(title VARCHAR(255) NOT NULL, year INT, PRIMARY KEY(title)) CHARACTER SET utf8 COLLATE utf8_bin;\n', - 'insert' : 'INSERT INTO movies(title, year) VALUES\n' + dbtableinfo = { + 'tablename' : 'movies', + 'columns' : [ + { + 'colname' : 'title', + 'colinfo' : DbScriptHelper.keywords['string'] + '(255) NOT NULL' + }, + { + 'colname' : 'year', + 'colinfo' : DbScriptHelper.keywords['number'] + } + ], + 'constraints' : 'PRIMARY KEY(title)' } endOfDumpDelimiter = "" From 6807407254227eec0a907183967a0e7469a685ac Mon Sep 17 00:00:00 2001 From: aykut Date: Sat, 16 Mar 2013 17:57:39 +0200 Subject: [PATCH 50/58] adds more parametric db operations --- idp/utils/dbscripthelper.py | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 idp/utils/dbscripthelper.py diff --git a/idp/utils/dbscripthelper.py b/idp/utils/dbscripthelper.py new file mode 100644 index 0000000..2d3a539 --- /dev/null +++ b/idp/utils/dbscripthelper.py @@ -0,0 +1,36 @@ +""" +This file is part of imdb-data-parser. + +imdb-data-parser 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 3 of the License, or +(at your option) any later version. + +imdb-data-parser 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 imdb-data-parser. If not, see . +""" + +import os + +class DbScriptHelper(object): + keywords = { + 'string' : 'VARCHAR2', + 'number' : 'NUMBER', + 'date' : 'DATE' + } + + scripts = { + 'drop' : 'DROP TABLE ', + 'create' : 'CREATE TABLE ', + 'insert' : 'INSERT INTO ' + } + + def __init__(self, dbtableinfo): + self.scripts['drop'] += dbtableinfo['tablename'] + ';' + os.linesep + self.scripts['create'] += dbtableinfo['tablename'] + '(' + ', '.join(filter(None, (', '.join('%s %s' % (col['colname'], col['colinfo']) for col in dbtableinfo['columns']), dbtableinfo['constraints']))) + ') CHARACTER SET utf8 COLLATE utf8_bin;' + os.linesep + self.scripts['insert'] += dbtableinfo['tablename'] + '(' + ', '.join(col['colname'] for col in dbtableinfo['columns']) + ') VALUES' + os.linesep \ No newline at end of file From 19a285963532e8dcc0a1e0df84e5805b62c0f63c Mon Sep 17 00:00:00 2001 From: Aykut Akin Date: Mon, 18 Mar 2013 22:44:22 +0200 Subject: [PATCH 51/58] tries to implement naming convention --- idp/parser/actorsparser.py | 26 +++--- idp/parser/actressesparser.py | 39 +++++---- idp/parser/baseparser.py | 68 ++++++++------- idp/parser/directorsparser.py | 39 +++++---- idp/parser/genresparser.py | 49 ++++++----- idp/parser/moviesparser.py | 39 ++++----- idp/parser/parsinghelper.py | 19 +++-- idp/parser/plotparser.py | 35 ++++---- idp/parser/ratingsparser.py | 37 ++++---- idp/parser/triviaparser.py | 39 +++++---- idp/utils/dbscripthelper.py | 21 ++--- idp/utils/decorators.py | 25 +++--- idp/utils/filehandler.py | 135 +++++++++++------------------ idp/utils/freebaseagent.py | 149 ++++++++++++++++++--------------- idp/utils/listdownloader.py | 28 ++++--- idp/utils/loggerinitializer.py | 7 +- idp/utils/regexhelper.py | 3 +- imdbparser.py | 32 +++---- 18 files changed, 396 insertions(+), 394 deletions(-) diff --git a/idp/parser/actorsparser.py b/idp/parser/actorsparser.py index 4eeba6e..f419753 100644 --- a/idp/parser/actorsparser.py +++ b/idp/parser/actorsparser.py @@ -15,10 +15,8 @@ along with imdb-data-parser. If not, see . """ -from .baseparser import BaseParser -from ..utils.regexhelper import * -from ..utils.filehandler import IMDBList -import logging +from .baseparser import * + class ActorsParser(BaseParser): """ @@ -41,26 +39,26 @@ class ActorsParser(BaseParser): """ # properties - baseMatcherPattern = '(.*?)\t+((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\s*(\(.*?\))?\s*(\(.*\))?\s*(\[.*\])?\s*(<.*>)?$' - inputFileName = "actors.list" - numberOfLinesToBeSkipped = 239 + base_matcher_pattern = '(.*?)\t+((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\s*(\(.*?\))?\s*(\(.*\))?\s*(\[.*\])?\s*(<.*>)?$' + input_file_name = "actors.list" + number_of_lines_to_be_skipped = 239 scripts = { #TODO: fill 'drop' : '', 'create' : '', 'insert' : '' } - endOfDumpDelimiter = "" + end_of_dump_delimiter = "" name = "" surname = "" - def __init__(self, preferencesMap): - super(ActorsParser, self).__init__(preferencesMap) + def __init__(self, preferences_map): + super(ActorsParser, self).__init__(preferences_map) def parse_into_tsv(self, matcher): - isMatch = matcher.match(self.baseMatcherPattern) + is_match = matcher.match(self.baseMatcherPattern) - if(isMatch): + if(is_match): if(len(matcher.group(1).strip()) > 0): namelist = matcher.group(1).split(', ') if(len(namelist) == 2): @@ -70,12 +68,12 @@ def parse_into_tsv(self, matcher): self.name = namelist[0] self.surname = "" - self.outputFile.write(self.name + self.seperator + self.surname + self.seperator + matcher.group(2) + self.seperator + matcher.group(3) + self.seperator + matcher.group(4) + self.seperator + matcher.group(6) + self.seperator + matcher.group(7) + self.seperator + matcher.group(8) + self.seperator + matcher.group(9) + self.seperator + matcher.group(10) + self.seperator + matcher.group(11) + "\n") + self.tsv_file.write(self.name + self.seperator + self.surname + self.seperator + matcher.group(2) + self.seperator + matcher.group(3) + self.seperator + matcher.group(4) + self.seperator + matcher.group(6) + self.seperator + matcher.group(7) + self.seperator + matcher.group(8) + self.seperator + matcher.group(9) + self.seperator + matcher.group(10) + self.seperator + matcher.group(11) + "\n") elif(len(matcher.get_last_string()) == 1): pass else: logging.critical("This line is fucked up: " + matcher.get_last_string()) - self.fuckedUpCount += 1 + self.fucked_up_count += 1 def parse_into_db(self, matcher): #TODO diff --git a/idp/parser/actressesparser.py b/idp/parser/actressesparser.py index b1f0b50..a71796c 100644 --- a/idp/parser/actressesparser.py +++ b/idp/parser/actressesparser.py @@ -15,10 +15,8 @@ along with imdb-data-parser. If not, see . """ -from .baseparser import BaseParser -from ..utils.regexhelper import * -from ..utils.filehandler import IMDBList -import logging +from .baseparser import * + class ActressesParser(BaseParser): """ @@ -41,26 +39,31 @@ class ActressesParser(BaseParser): """ # properties - baseMatcherPattern = '(.*?)\t+((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\s*(\(.*?\))?\s*(\(.*\))?\s*(\[.*\])?\s*(<.*>)?$' - inputFileName = "actresses.list" - numberOfLinesToBeSkipped = 241 - scripts = { #TODO: fill - 'drop' : '', - 'create' : '', - 'insert' : '' + base_matcher_pattern = '(.*?)\t+((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\s*(\(.*?\))?\s*(\(.*\))?\s*(\[.*\])?\s*(<.*>)?$' + input_file_name = "actresses.list" + number_of_lines_to_be_skipped = 241 + db_table_info = { + 'tablename' : 'actresses', + 'columns' : [ + { + 'colname' : '', + 'colinfo' : DbScriptHelper.keywords['string'] + '(255) NOT NULL' + } + ], + 'constraints' : '' } - endOfDumpDelimiter = "" + end_of_dump_delimiter = "" name = "" surname = "" - def __init__(self, preferencesMap): - super(ActressesParser, self).__init__(preferencesMap) + def __init__(self, preferences_map): + super(ActressesParser, self).__init__(preferences_map) def parse_into_tsv(self, matcher): - isMatch = matcher.match(self.baseMatcherPattern) + is_match = matcher.match(self.base_matcher_pattern) - if(isMatch): + if(is_match): if(len(matcher.group(1).strip()) > 0): namelist = matcher.group(1).split(', ') if(len(namelist) == 2): @@ -70,12 +73,12 @@ def parse_into_tsv(self, matcher): self.name = namelist[0] self.surname = "" - self.outputFile.write(self.name + self.seperator + self.surname + self.seperator + matcher.group(2) + self.seperator + matcher.group(3) + self.seperator + matcher.group(4) + self.seperator + matcher.group(6) + self.seperator + matcher.group(7) + self.seperator + matcher.group(8) + self.seperator + matcher.group(9) + self.seperator + matcher.group(10) + self.seperator + matcher.group(11) + "\n") + self.tsv_file.write(self.name + self.seperator + self.surname + self.seperator + matcher.group(2) + self.seperator + matcher.group(3) + self.seperator + matcher.group(4) + self.seperator + matcher.group(6) + self.seperator + matcher.group(7) + self.seperator + matcher.group(8) + self.seperator + matcher.group(9) + self.seperator + matcher.group(10) + self.seperator + matcher.group(11) + "\n") elif(len(matcher.get_last_string()) == 1): pass else: logging.critical("This line is fucked up: " + matcher.get_last_string()) - self.fuckedUpCount += 1 + self.fucked_up_count += 1 def parse_into_db(self, matcher): #TODO diff --git a/idp/parser/baseparser.py b/idp/parser/baseparser.py index 4867fb1..415f9b6 100644 --- a/idp/parser/baseparser.py +++ b/idp/parser/baseparser.py @@ -15,12 +15,15 @@ along with imdb-data-parser. If not, see . """ +import re +import logging from abc import * -from ..utils.filehandler import * -from ..utils.regexhelper import * -from ..utils.decorators import durationLogged +from ..utils.filehandler import FileHandler +from ..utils.regexhelper import RegExHelper +from ..utils.decorators import duration_logged from ..utils.dbscripthelper import DbScriptHelper + class BaseParser(metaclass=ABCMeta): """ Base class for all parser classes @@ -41,18 +44,19 @@ class BaseParser(metaclass=ABCMeta): seperator = "\t" #TODO: get from settings - def __init__(self, preferencesMap): - self.mode = preferencesMap['mode'] - self.list = IMDBList(self.inputFileName, preferencesMap) - self.inputFile = self.list.get_input_file() + def __init__(self, preferences_map): + self.mode = preferences_map['mode'] + self.filehandler = FileHandler(self.input_file_name, preferences_map) + self.input_file = self.filehandler.get_input_file() + if (self.mode == "TSV"): - self.outputFile = self.list.get_output_file() + self.tsv_file = self.filehandler.get_tsv_file() elif (self.mode == "SQL"): - self.sqlFile = self.list.get_sql_file() - self.scripthelper = DbScriptHelper(self.dbtableinfo) - self.sqlFile.write(self.scripthelper.scripts['drop']) - self.sqlFile.write(self.scripthelper.scripts['create']) - self.sqlFile.write(self.scripthelper.scripts['insert']) + self.sql_file = self.filehandler.get_sql_file() + self.scripthelper = DbScriptHelper(self.db_table_info) + self.sql_file.write(self.scripthelper.scripts['drop']) + self.sql_file.write(self.scripthelper.scripts['create']) + self.sql_file.write(self.scripthelper.scripts['insert']) @abstractmethod def parse_into_tsv(self, matcher): @@ -62,20 +66,20 @@ def parse_into_tsv(self, matcher): def parse_into_db(self, matcher): raise NotImplemented - @durationLogged + @duration_logged def start_processing(self): ''' Actual parsing and generation of scripts (tsv & sql) are done here. ''' - self.fuckedUpCount = 0 + self.fucked_up_count = 0 counter = 0 - numberOfProcessedLines = 0 + number_of_processed_lines = 0 - for line in self.inputFile : #assuming the file is opened in the subclass before here - if(numberOfProcessedLines >= self.numberOfLinesToBeSkipped): + for line in self.input_file : #assuming the file is opened in the subclass before here + if(number_of_processed_lines >= self.number_of_lines_to_be_skipped): #end of data - if(self.endOfDumpDelimiter != "" and self.endOfDumpDelimiter in line): + if(self.end_of_dump_delimiter != "" and self.end_of_dump_delimiter in line): break matcher = RegExHelper(line) @@ -91,39 +95,39 @@ def start_processing(self): else: raise NotImplemented("Mode: " + self.mode) - numberOfProcessedLines += 1 + number_of_processed_lines += 1 - self.inputFile.close() + self.input_file.close() if(self.mode == "SQL"): - self.sqlFile.write(";") - self.sqlFile.close() + self.sql_file.write(";") + self.sql_file.close() if 'outputFile' in locals(): - self.outputFile.flush() - self.outputFile.close() + self.output_file.flush() + self.output_file.close() # fuckedUpCount is calculated in implementing class - logging.info("Finished with " + str(self.fuckedUpCount) + " fucked up line") + logging.info("Finished with " + str(self.fucked_up_count) + " fucked up line") ##### Below methods force associated properties to be defined in any derived class ##### @abstractproperty - def baseMatcherPattern(self): + def base_matcher_pattern(self): raise NotImplemented @abstractproperty - def inputFileName(self): + def input_file_name(self): raise NotImplemented @abstractproperty - def numberOfLinesToBeSkipped(self): + def number_of_lines_to_be_skipped(self): raise NotImplemented @abstractproperty - def dbtableinfo(self): + def db_table_info(self): raise NotImplemented @abstractproperty - def endOfDumpDelimiter(self): - raise NotImplemented + def end_of_dump_delimiter(self): + raise NotImplemented \ No newline at end of file diff --git a/idp/parser/directorsparser.py b/idp/parser/directorsparser.py index 24d93bd..e374d59 100644 --- a/idp/parser/directorsparser.py +++ b/idp/parser/directorsparser.py @@ -15,10 +15,8 @@ along with imdb-data-parser. If not, see . """ -from .baseparser import BaseParser -from ..utils.regexhelper import * -from ..utils.filehandler import IMDBList -import logging +from .baseparser import * + class DirectorsParser(BaseParser): """ @@ -39,26 +37,31 @@ class DirectorsParser(BaseParser): """ # properties - baseMatcherPattern = '(.*?)\t+((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\s*(\(.*\)|EDIT)?\s*(<.*>)?$' - inputFileName = "directors.list" - numberOfLinesToBeSkipped = 235 - scripts = { #TODO: fill - 'drop' : '', - 'create' : '', - 'insert' : '' + base_matcher_pattern = '(.*?)\t+((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\s*(\(.*\)|EDIT)?\s*(<.*>)?$' + input_file_name = "directors.list" + number_of_lines_to_be_skipped = 235 + db_table_info = { + 'tablename' : 'directors', + 'columns' : [ + { + 'colname' : '', + 'colinfo' : DbScriptHelper.keywords['string'] + '(255) NOT NULL' + } + ], + 'constraints' : '' } - endOfDumpDelimiter = "" + end_of_dump_delimiter = "" name = "" surname = "" - def __init__(self, preferencesMap): - super(DirectorsParser, self).__init__(preferencesMap) + def __init__(self, preferences_map): + super(DirectorsParser, self).__init__(preferences_map) def parse_into_tsv(self, matcher): - isMatch = matcher.match(self.baseMatcherPattern) + is_match = matcher.match(self.base_matcher_pattern) - if(isMatch): + if(is_match): if(len(matcher.group(1).strip()) > 0): namelist = matcher.group(1).split(', ') if(len(namelist) == 2): @@ -68,12 +71,12 @@ def parse_into_tsv(self, matcher): self.name = namelist[0] self.surname = "" - self.outputFile.write(self.name + self.seperator + self.surname + self.seperator + matcher.group(2) + self.seperator + matcher.group(3) + self.seperator + matcher.group(4) + self.seperator + matcher.group(6) + self.seperator + matcher.group(7) + self.seperator + matcher.group(8) + self.seperator + matcher.group(9) + "\n") + self.tsv_file.write(self.name + self.seperator + self.surname + self.seperator + matcher.group(2) + self.seperator + matcher.group(3) + self.seperator + matcher.group(4) + self.seperator + matcher.group(6) + self.seperator + matcher.group(7) + self.seperator + matcher.group(8) + self.seperator + matcher.group(9) + "\n") elif(len(matcher.get_last_string()) == 1): pass else: logging.critical("This line is fucked up: " + matcher.get_last_string()) - self.fuckedUpCount += 1 + self.fucked_up_count += 1 def parse_into_db(self, matcher): #TODO diff --git a/idp/parser/genresparser.py b/idp/parser/genresparser.py index 3f8a7ff..592805b 100644 --- a/idp/parser/genresparser.py +++ b/idp/parser/genresparser.py @@ -15,10 +15,8 @@ along with imdb-data-parser. If not, see . """ -from .baseparser import BaseParser -from ..utils.regexhelper import * -from ..utils.filehandler import IMDBList -import logging +from .baseparser import * + class GenresParser(BaseParser): """ @@ -37,38 +35,43 @@ class GenresParser(BaseParser): """ # properties - baseMatcherPattern = "((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\t+(.*)$" - inputFileName = "genres.list" - numberOfLinesToBeSkipped = 378 - scripts = { - 'drop' : 'DROP TABLE IF EXISTS movies_genres;\n', - 'create' : 'CREATE TABLE movies_genres(movie_title VARCHAR(255) NOT NULL, genre VARCHAR(255)) CHARACTER SET utf8 COLLATE utf8_bin;\n', - 'insert' : 'INSERT INTO movies_genres(movie_title, genre) VALUES\n' + base_matcher_pattern = "((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\t+(.*)$" + input_file_name = "genres.list" + number_of_lines_to_be_skipped = 378 + db_table_info = { + 'tablename' : 'genres', + 'columns' : [ + { + 'colname' : '', + 'colinfo' : DbScriptHelper.keywords['string'] + '(255) NOT NULL' + } + ], + 'constraints' : '' } - endOfDumpDelimiter = "" + end_of_dump_delimiter = "" - def __init__(self, preferencesMap): - super(GenresParser, self).__init__(preferencesMap) + def __init__(self, preferences_map): + super(GenresParser, self).__init__(preferences_map) self.first_one=True def parse_into_tsv(self, matcher): - isMatch = matcher.match(self.baseMatcherPattern) + is_match = matcher.match(self.base_matcher_pattern) - if(isMatch): - self.outputFile.write(matcher.group(1) + self.seperator + matcher.group(2) + self.seperator + matcher.group(3) + self.seperator + matcher.group(5) + self.seperator + matcher.group(6) + self.seperator + matcher.group(7) + self.seperator + matcher.group(8) + "\n") + if(is_match): + self.tsv_file.write(matcher.group(1) + self.seperator + matcher.group(2) + self.seperator + matcher.group(3) + self.seperator + matcher.group(5) + self.seperator + matcher.group(6) + self.seperator + matcher.group(7) + self.seperator + matcher.group(8) + "\n") else: logging.critical("This line is fucked up: " + matcher.get_last_string()) - self.fuckedUpCount += 1 + self.fucked_up_count += 1 def parse_into_db(self, matcher): - isMatch = matcher.match(self.baseMatcherPattern) + is_match = matcher.match(self.base_matcher_pattern) - if(isMatch): + if(is_match): if(self.first_one): - self.sqlFile.write("(\"" + re.escape(matcher.group(1)) + "\", \"" + matcher.group(8) + "\")") + self.sql_file.write("(\"" + re.escape(matcher.group(1)) + "\", \"" + matcher.group(8) + "\")") self.first_one=False; else: - self.sqlFile.write(",\n(\"" + re.escape(matcher.group(1)) + "\", \"" + matcher.group(8) + "\")") + self.sql_file.write(",\n(\"" + re.escape(matcher.group(1)) + "\", \"" + matcher.group(8) + "\")") else: logging.critical("This line is fucked up: " + matcher.get_last_string()) - self.fuckedUpCount += 1 + self.fucked_up_count += 1 diff --git a/idp/parser/moviesparser.py b/idp/parser/moviesparser.py index 5f8239c..82d74db 100644 --- a/idp/parser/moviesparser.py +++ b/idp/parser/moviesparser.py @@ -15,11 +15,8 @@ along with imdb-data-parser. If not, see . """ -from .baseparser import BaseParser -from ..utils.filehandler import IMDBList -from ..utils.dbscripthelper import DbScriptHelper -import logging -import re +from .baseparser import * + class MoviesParser(BaseParser): """ @@ -40,11 +37,11 @@ class MoviesParser(BaseParser): """ # properties - baseMatcherPattern = "((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\t+(.*)$" - inputFileName = "movies.list" + base_matcher_pattern = "((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\t+(.*)$" + input_file_name = "movies.list" #FIXME: zafer: I think using a static number is critical for us. If imdb sends a new file with first 10 line fucked then we're also fucked - numberOfLinesToBeSkipped = 15 - dbtableinfo = { + number_of_lines_to_be_skipped = 15 + db_table_info = { 'tablename' : 'movies', 'columns' : [ { @@ -58,30 +55,30 @@ class MoviesParser(BaseParser): ], 'constraints' : 'PRIMARY KEY(title)' } - endOfDumpDelimiter = "" + end_of_dump_delimiter = "" - def __init__(self, preferencesMap): - super(MoviesParser, self).__init__(preferencesMap) + def __init__(self, preferences_map): + super(MoviesParser, self).__init__(preferences_map) self.first_one=True def parse_into_tsv(self, matcher): - isMatch = matcher.match(self.baseMatcherPattern) + is_match = matcher.match(self.base_matcher_pattern) - if(isMatch): - self.outputFile.write(matcher.group(1) + self.seperator + matcher.group(2) + self.seperator + matcher.group(3) + self.seperator + matcher.group(5) + self.seperator + matcher.group(6) + self.seperator + matcher.group(7) + self.seperator + matcher.group(8) + "\n") + if(is_match): + self.tsv_file.write(matcher.group(1) + self.seperator + matcher.group(2) + self.seperator + matcher.group(3) + self.seperator + matcher.group(5) + self.seperator + matcher.group(6) + self.seperator + matcher.group(7) + self.seperator + matcher.group(8) + "\n") else: logging.critical("This line is fucked up: " + matcher.get_last_string()) - self.fuckedUpCount += 1 + self.fucked_up_count += 1 def parse_into_db(self, matcher): - isMatch = matcher.match(self.baseMatcherPattern) + is_match = matcher.match(self.base_matcher_pattern) - if(isMatch): + if(is_match): if(self.first_one): - self.sqlFile.write("(\"" + re.escape(matcher.group(1)) + "\", " + matcher.group(8) + ")") + self.sql_file.write("(\"" + re.escape(matcher.group(1)) + "\", " + matcher.group(8) + ")") self.first_one=False; else: - self.sqlFile.write(",\n(\"" + re.escape(matcher.group(1)) + "\", " + matcher.group(8) + ")") + self.sql_file.write(",\n(\"" + re.escape(matcher.group(1)) + "\", " + matcher.group(8) + ")") else: logging.critical("This line is fucked up: " + matcher.get_last_string()) - self.fuckedUpCount += 1 + self.fucked_up_count += 1 diff --git a/idp/parser/parsinghelper.py b/idp/parser/parsinghelper.py index 44e282a..6a480b0 100644 --- a/idp/parser/parsinghelper.py +++ b/idp/parser/parsinghelper.py @@ -15,9 +15,10 @@ along with imdb-data-parser. If not, see . """ -from idp import settings import logging import traceback +from idp import settings + class ParsingHelper(object): """ @@ -25,13 +26,13 @@ class ParsingHelper(object): """ @staticmethod - def parse_one(item, preferencesMap): + def parse_one(item, preferences_map): - def get_parser_class_for(itemName): + def get_parser_class_for(item_name): """ Thanks to http://stackoverflow.com/a/452981 """ - kls = "idp.parser." + itemName + "parser." + itemName.title() + "Parser" + kls = "idp.parser." + item_name + "parser." + item_name.title() + "Parser" parts = kls.split('.') module = ".".join(parts[:-1]) m = __import__( module ) @@ -46,7 +47,7 @@ def get_parser_class_for(itemName): return 1 logging.info("___________________") logging.info("Parsing " + item + "...") - parser = ParserClass(preferencesMap) + parser = ParserClass(preferences_map) try: parser.start_processing() except Exception as e: @@ -55,9 +56,9 @@ def get_parser_class_for(itemName): logging.info("Parsing finished for item: " + item) @staticmethod - def parse_all(preferencesMap): + def parse_all(preferences_map): for item in settings.LISTS: - ParsingHelper.parse_one(item, preferencesMap) + ParsingHelper.parse_one(item, preferences_map) logging.info("All parsing finished.") if __name__ == "__main__": @@ -65,9 +66,9 @@ def parse_all(preferencesMap): For debugging purposes """ print("Parsing only one file for debugging purposes...") - preferencesMap = { + preferences_map = { "mode":"TSV", "inputDir": "../../samples/imdb_lists/", "outputDir": "../../samples/idp_files/" } - ParsingHelper.parse_one("movies", preferencesMap) + ParsingHelper.parse_one("movies", preferences_map) diff --git a/idp/parser/plotparser.py b/idp/parser/plotparser.py index 5391818..17217e2 100644 --- a/idp/parser/plotparser.py +++ b/idp/parser/plotparser.py @@ -15,10 +15,8 @@ along with imdb-data-parser. If not, see . """ -from .baseparser import BaseParser -from ..utils.regexhelper import * -from ..utils.filehandler import IMDBList -import logging +from .baseparser import * + class PlotParser(BaseParser): """ @@ -32,27 +30,32 @@ class PlotParser(BaseParser): """ # properties - baseMatcherPattern = "(.+?): (.*)" - inputFileName = "plot.list" - numberOfLinesToBeSkipped = 15 - scripts = { #TODO: fill - 'drop' : '', - 'create' : '', - 'insert' : '' + base_matcher_pattern = "(.+?): (.*)" + input_file_name = "plot.list" + number_of_lines_to_be_skipped = 15 + db_table_info = { + 'tablename' : 'plot', + 'columns' : [ + { + 'colname' : '', + 'colinfo' : DbScriptHelper.keywords['string'] + '(255) NOT NULL' + } + ], + 'constraints' : '' } - endOfDumpDelimiter = "" + end_of_dump_delimiter = "" - def __init__(self, preferencesMap): - super(PlotParser, self).__init__(preferencesMap) + def __init__(self, preferences_map): + super(PlotParser, self).__init__(preferences_map) # specific to this class self.title = "" self.plot = "" def parse_into_tsv(self, matcher): - isMatch = matcher.match(self.baseMatcherPattern) + is_match = matcher.match(self.base_matcher_pattern) - if(isMatch): + if(is_match): if(matcher.group(1) == "MV"): #Title if(self.title != ""): self.outputFile.write(self.title + self.seperator + self.plot + "\n") diff --git a/idp/parser/ratingsparser.py b/idp/parser/ratingsparser.py index 6385a09..80907e7 100644 --- a/idp/parser/ratingsparser.py +++ b/idp/parser/ratingsparser.py @@ -15,10 +15,8 @@ along with imdb-data-parser. If not, see . """ -from .baseparser import BaseParser -from ..utils.regexhelper import * -from ..utils.filehandler import IMDBList -import logging +from .baseparser import * + class RatingsParser(BaseParser): """ @@ -39,24 +37,29 @@ class RatingsParser(BaseParser): """ # properties - baseMatcherPattern = "\s*(\S*)\s*(\S*)\s*(\S*)\s*((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)$" - inputFileName = "ratings.list" - numberOfLinesToBeSkipped = 28 - scripts = { #TODO: fill - 'drop' : '', - 'create' : '', - 'insert' : '' + base_matcher_pattern = "\s*(\S*)\s*(\S*)\s*(\S*)\s*((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)$" + input_file_name = "ratings.list" + number_of_lines_to_be_skipped = 28 + db_table_info = { + 'tablename' : 'ratings', + 'columns' : [ + { + 'colname' : '', + 'colinfo' : DbScriptHelper.keywords['string'] + '(255) NOT NULL' + } + ], + 'constraints' : '' } - endOfDumpDelimiter = "" + end_of_dump_delimiter = "" - def __init__(self, preferencesMap): - super(RatingsParser, self).__init__(preferencesMap) + def __init__(self, preferences_map): + super(RatingsParser, self).__init__(preferences_map) def parse_into_tsv(self, matcher): - isMatch = matcher.match(self.baseMatcherPattern) + is_match = matcher.match(self.base_matcher_pattern) - if(isMatch): - self.outputFile.write(matcher.group(1) + self.seperator + matcher.group(2) + self.seperator + matcher.group(3) + self.seperator + matcher.group(4) + self.seperator + matcher.group(5) + self.seperator + matcher.group(6) + self.seperator + matcher.group(8) + self.seperator + matcher.group(8) + self.seperator + matcher.group(9) + self.seperator + matcher.group(10) + "\n") + if(is_match): + self.tsv_file.write(matcher.group(1) + self.seperator + matcher.group(2) + self.seperator + matcher.group(3) + self.seperator + matcher.group(4) + self.seperator + matcher.group(5) + self.seperator + matcher.group(6) + self.seperator + matcher.group(8) + self.seperator + matcher.group(8) + self.seperator + matcher.group(9) + self.seperator + matcher.group(10) + "\n") else: logging.critical("This line is fucked up: " + matcher.get_last_string()) self.fuckedUpCount += 1 diff --git a/idp/parser/triviaparser.py b/idp/parser/triviaparser.py index 9b7d44f..dced4b7 100644 --- a/idp/parser/triviaparser.py +++ b/idp/parser/triviaparser.py @@ -15,10 +15,8 @@ along with imdb-data-parser. If not, see . """ -from .baseparser import BaseParser -from ..utils.regexhelper import * -from ..utils.filehandler import IMDBList -import logging +from .baseparser import * + class TriviaParser(BaseParser): """ @@ -32,26 +30,31 @@ class TriviaParser(BaseParser): """ # properties - baseMatcherPattern = "((.+?) (.*))|\n" - inputFileName = "trivia.list" - numberOfLinesToBeSkipped = 15 - scripts = { #TODO: fill - 'drop' : '', - 'create' : '', - 'insert' : '' + base_matcher_pattern = "((.+?) (.*))|\n" + input_file_name = "trivia.list" + number_of_lines_to_be_skipped = 15 + db_table_info = { + 'tablename' : 'trivia', + 'columns' : [ + { + 'colname' : '', + 'colinfo' : DbScriptHelper.keywords['string'] + '(255) NOT NULL' + } + ], + 'constraints' : '' } - endOfDumpDelimiter = "" + end_of_dump_delimiter = "" title = "" trivia = "" - def __init__(self, preferencesMap): - super(TriviaParser, self).__init__(preferencesMap) + def __init__(self, preferences_map): + super(TriviaParser, self).__init__(preferences_map) def parse_into_tsv(self, matcher): - isMatch = matcher.match(self.baseMatcherPattern) + is_match = matcher.match(self.base_matcher_pattern) - if(isMatch): + if(is_match): if(matcher.group(2) == "#"): #Title self.title = matcher.group(3) elif(matcher.group(2) == "-"): #Descriptive text @@ -59,10 +62,10 @@ def parse_into_tsv(self, matcher): elif(matcher.group(2) == " "): self.trivia += ' ' + matcher.group(3) else: - self.outputFile.write(self.title + self.seperator + self.trivia + "\n") + self.tsv_file.write(self.title + self.seperator + self.trivia + "\n") else: logging.critical("This line is fucked up: " + matcher.get_last_string()) - self.fuckedUpCount += 1 + self.fucked_up_count += 1 def parse_into_db(self, matcher): #TODO diff --git a/idp/utils/dbscripthelper.py b/idp/utils/dbscripthelper.py index 2d3a539..cf14f44 100644 --- a/idp/utils/dbscripthelper.py +++ b/idp/utils/dbscripthelper.py @@ -17,20 +17,21 @@ import os + class DbScriptHelper(object): keywords = { - 'string' : 'VARCHAR2', - 'number' : 'NUMBER', - 'date' : 'DATE' + 'string': "VARCHAR", + 'number': "NUMERIC", + 'date': "DATE" } scripts = { - 'drop' : 'DROP TABLE ', - 'create' : 'CREATE TABLE ', - 'insert' : 'INSERT INTO ' + 'drop': "DROP TABLE ", + 'create': "CREATE TABLE ", + 'insert': "INSERT INTO " } - def __init__(self, dbtableinfo): - self.scripts['drop'] += dbtableinfo['tablename'] + ';' + os.linesep - self.scripts['create'] += dbtableinfo['tablename'] + '(' + ', '.join(filter(None, (', '.join('%s %s' % (col['colname'], col['colinfo']) for col in dbtableinfo['columns']), dbtableinfo['constraints']))) + ') CHARACTER SET utf8 COLLATE utf8_bin;' + os.linesep - self.scripts['insert'] += dbtableinfo['tablename'] + '(' + ', '.join(col['colname'] for col in dbtableinfo['columns']) + ') VALUES' + os.linesep \ No newline at end of file + def __init__(self, db_table_info): + self.scripts['drop'] += db_table_info['tablename'] + ";" + os.linesep + self.scripts['create'] += db_table_info['tablename'] + "(" + ', '.join(filter(None, (', '.join('%s %s' % (col['colname'], col['colinfo']) for col in db_table_info['columns']), db_table_info['constraints']))) + ") CHARACTER SET utf8 COLLATE utf8_bin;" + os.linesep + self.scripts['insert'] += db_table_info['tablename'] + "(" + ', '.join(col['colname'] for col in db_table_info['columns']) + ") VALUES" + os.linesep \ No newline at end of file diff --git a/idp/utils/decorators.py b/idp/utils/decorators.py index 2467237..46f9561 100644 --- a/idp/utils/decorators.py +++ b/idp/utils/decorators.py @@ -18,15 +18,16 @@ import datetime import logging -def durationLogged(func): - ''' - As the name suggests, calculates the execution duration of the function which is annotated by this decorator - ''' - def inner(*args, **kwargs): - startTime = datetime.datetime.now() - retVal = func(*args, **kwargs) - endTime = datetime.datetime.now() - duration = (endTime - startTime).total_seconds() #difference of 2 datetime is a timedelta - logging.info("Parsing took " + str(duration) + " seconds") - return retVal - return inner \ No newline at end of file + +def duration_logged(func): + ''' + As the name suggests, calculates the execution duration of the function which is annotated by this decorator + ''' + def inner(*args, **kwargs): + start_time = datetime.datetime.now() + ret_val = func(*args, **kwargs) + end_time = datetime.datetime.now() + duration = (end_time - start_time).total_seconds() #difference of 2 datetime is a timedelta + logging.info("Parsing took " + str(duration) + " seconds") + return ret_val + return inner \ No newline at end of file diff --git a/idp/utils/filehandler.py b/idp/utils/filehandler.py index 51ab884..5b5bac8 100644 --- a/idp/utils/filehandler.py +++ b/idp/utils/filehandler.py @@ -17,110 +17,69 @@ import gzip import os.path -from ..settings import * import logging +from ..settings import * + -class IMDBList(object): - def __init__(self, listname, preferencesMap): - #TODO: check listname finishes with .list - self.listname = listname - self.preferencesMap = preferencesMap +class FileHandler(object): + def __init__(self, list_name, preferences_map): + self.list_name = list_name + self.preferences_map = preferences_map def full_path(self): - if self.listname.lower().endswith(".gz"): - return os.path.join(self.preferencesMap['inputDir'], self.listname) + ".gz" - return os.path.join(self.preferencesMap['inputDir'], self.listname) + return os.path.join(self.preferences_map['input_dir'], self.list_name) def tsv_path(self): - return os.path.join(self.preferencesMap['outputDir'], self.listname) + ".tsv" + return os.path.join(self.preferences_map['output_dir'], self.list_name) + ".tsv" def sql_path(self): - return os.path.join(self.preferencesMap['outputDir'], self.listname) + ".sql" + return os.path.join(self.preferences_map['output_dir'], self.list_name) + ".sql" def get_input_file(self): - fullFilePath = self.full_path() - logging.info("Trying to find file: %s", fullFilePath) - if os.path.isfile(fullFilePath): - logging.info("File found: %s", fullFilePath) - return open(fullFilePath, "r", encoding='iso-8859-1') - - logging.error("File cannot be found: %s", fullFilePath) - - logging.info("Trying to find file: %s", fullFilePath + ".gz") - if os.path.isfile(fullFilePath + ".gz"): - logging.info("File found: %s", fullFilePath + ".gz") - if extract(fullFilePath + ".gz") == 0: - return open(fullFilePath, "r", encoding='iso-8859-1') + full_file_path = self.full_path() + logging.info("Trying to find file: %s", full_file_path) + if os.path.isfile(full_file_path): + logging.info("File found: %s", full_file_path) + return open(full_file_path, "r", encoding='utf-8') + + logging.error("File cannot be found: %s", full_file_path) + + logging.info("Trying to find file: %s", full_file_path + ".gz") + if os.path.isfile(full_file_path + ".gz"): + logging.info("File found: %s", full_file_path + ".gz") + if extract(full_file_path + ".gz") == 0: + return open(full_file_path, "r", encoding='utf-8') else: raise RuntimeError("Unknown error occured") - logging.error("File cannot be found: %s", fullFilePath + ".gz") - raise RuntimeError("FileNotFoundError: " + fullFilePath) + logging.error("File cannot be found: %s", full_file_path + ".gz") + + raise RuntimeError("FileNotFoundError: %s", full_file_path) + +#this part removed until python 3.3 becomes available for ubuntu LTS and debian +# +# print("Trying to find file:", full_file_path) +# if os.path.isfile(full_file_path): +# print("File found:", full_file_path) +# return gzip.open(full_file_path, 'rt') +# print("File cannot be found:", full_file_path) - def get_output_file(self): + def get_tsv_file(self): return open(self.tsv_path(), "w", encoding='utf-8') def get_sql_file(self): return open(self.sql_path(), "w", encoding='utf-8') - -def get_full_path(filename, isCompressed = False): - """ - constructs a full path for a dump file in the INPUT_DIR - filename should be without '.list' - """ - if(isCompressed): - return os.path.join(INPUT_DIR, filename) + ".gz" - else: - return os.path.join(INPUT_DIR, filename) - -def get_decompressed_file_name(fullpath): - return fullpath[:-3] - -def extract(fullpath): - try: - logging.info('started to extract list: %s', fullpath) - with gzip.open(fullpath, 'rb') as f: - file_content = f.read() - listfile = open(get_decompressed_file_name(fullpath), 'wb') - listfile.write(file_content) - listfile.close() - logging.info(fullpath + ' list extracted successfully') - except Exception as e: - logging.error('error when extracting list: ' + fullpath + "\n\t" + str(e)) - return 1 - return 0 - -def openfile(fullFilePath): - - logging.info("Trying to find file: %s", fullFilePath) - if os.path.isfile(fullFilePath): - logging.info("File found: %s", fullFilePath) - return open(fullFilePath, "r", encoding='iso-8859-1') - - logging.error("File cannot be found: %s", fullFilePath) - -# -#this part removed until python 3.3 becomes available for ubuntu LTS and debian -# -# print("Trying to find file:", fullFilePath) -# if os.path.isfile(fullFilePath): -# print("File found:", fullFilePath) -# return gzip.open(fullFilePath, 'rt') -# print("File cannot be found:", fullFilePath) - - logging.info("Trying to find file: %s", fullFilePath + ".gz") - if os.path.isfile(fullFilePath + ".gz"): - logging.info("File found: %s", fullFilePath + ".gz") - if extract(fullFilePath + ".gz") == 0: - return open(fullFilePath, "r", encoding='iso-8859-1') - else: - raise RuntimeError("Unknown error occured") - logging.error("File cannot be found: %s", fullFilePath + ".gz") - - raise RuntimeError("FileNotFoundError: " + fullFilePath) - -if __name__ == "__main__": - f = IMDBList("movies.list") - print(f.full_path()) - print(f.tsv_path()) + def extract(gzip_path): + try: + logging.info("Started to extract list: %s", gzip_path) + with gzip.open(gzip_path, "rb") as f: + file_content = f.read() + list_file = open(gzip_path[:-3], "wb") + list_file.write(file_content) + list_file.close() + logging.info(gzip_path + " list extracted successfully") + except Exception as e: + logging.error("Error when extracting list: " + gzip_path + "\n\t" + str(e)) + return 1 + return 0 \ No newline at end of file diff --git a/idp/utils/freebaseagent.py b/idp/utils/freebaseagent.py index 387e7e1..012a34e 100644 --- a/idp/utils/freebaseagent.py +++ b/idp/utils/freebaseagent.py @@ -1,74 +1,91 @@ +""" +This file is part of imdb-data-parser. + +imdb-data-parser 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 3 of the License, or +(at your option) any later version. + +imdb-data-parser 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 imdb-data-parser. If not, see . +""" + import json import urllib + class FreebaseAgent(object): - """Helper class to retrieve IMDb ids from freebase. - - Currently only supports movies. TV series support will - hopefully be added if need arises. - """ - - def __init__(self): - super(FreebaseAgent, self).__init__() - self.API_KEY = 'YOUR-API-KEY-GOES-HERE' #TODO read these values from config - self.topic_service_url = 'https://www.googleapis.com/freebase/v1/topic' - self.search_service_url = 'https://www.googleapis.com/freebase/v1/search' - - def getImdbId(self, movieName): - """Returns the IMDb id of a movie, given its title. - - The returned title is the one with the highest - freebase confidence score. - - Returns None if no such movie exists in freebase. - """ - mid = self.getTopicId(movieName) - topic = self.getTopic(mid) - return topic - - def getTopicId(self, name, entityType='/film/film'): - """Gets the topic id (aka mid, freebase id) of a title. - """ - params = { - 'query': name, - 'type': entityType, - 'limit': 1 - } - url = self.search_service_url + '?' + urllib.urlencode(params) - response = json.loads(urllib.urlopen(url).read()) - - for result in response.get('result'): - mid = result.get('mid', None) - return mid - return None - - def getTopic(self, mid): - """Gets the IMDb id of a freebase topic. Returns None if no - such thing exists. - """ - params = { - 'filter': '/type/object/key' - } - url = self.topic_service_url + mid + '?' + urllib.urlencode(params) - topic = json.loads(urllib.urlopen(url).read()) - - for property in topic['property']: - for value in topic['property'][property]['values']: - if value['text'].startswith('/authority/imdb/title'): - return value['text'].split('/')[-1] + """Helper class to retrieve IMDb ids from freebase. + + Currently only supports movies. TV series support will + hopefully be added if need arises. + """ + + def __init__(self): + super(FreebaseAgent, self).__init__() + self.API_KEY = 'YOUR-API-KEY-GOES-HERE' #TODO read these values from config + self.topic_service_url = 'https://www.googleapis.com/freebase/v1/topic' + self.search_service_url = 'https://www.googleapis.com/freebase/v1/search' + + def get_imdb_id(self, movie_name): + """Returns the IMDb id of a movie, given its title. + The returned title is the one with the highest + freebase confidence score. + + Returns None if no such movie exists in freebase. + """ + mid = self.get_topic_id(movie_name) + topic = self.get_topic(mid) + return topic + + def get_topic_id(self, name, entity_type='/film/film'): + """Gets the topic id (aka mid, freebase id) of a title. + """ + params = { + 'query': name, + 'type': entity_type, + 'limit': 1 + } + url = self.search_service_url + '?' + urllib.urlencode(params) + response = json.loads(urllib.urlopen(url).read()) + + for result in response.get('result'): + mid = result.get('mid', None) + return mid + return None + + def get_topic(self, mid): + """Gets the IMDb id of a freebase topic. Returns None if no + such thing exists. + """ + params = { + 'filter': '/type/object/key' + } + url = self.topic_service_url + mid + '?' + urllib.urlencode(params) + topic = json.loads(urllib.urlopen(url).read()) + + for property in topic['property']: + for value in topic['property'][property]['values']: + if value['text'].startswith('/authority/imdb/title'): + return value['text'].split('/')[-1] if __name__ == "__main__": - import argparse - - parser = argparse.ArgumentParser(description="Retrieve imdb id from freebase.") - parser.add_argument('movieName', help='The name of the movie') - args = parser.parse_args() - - agent = FreebaseAgent() - mid = agent.getTopicId(args.movieName) - print 'freebase topic id (mid) is', mid - topic = agent.getTopic(mid) - print 'imdb id is', topic, 'so the url is http://www.imdb.com/title/'+topic - print agent.getImdbId(args.movieName) \ No newline at end of file + import argparse + + parser = argparse.ArgumentParser(description="Retrieve imdb id from freebase.") + parser.add_argument('movieName', help='The name of the movie') + args = parser.parse_args() + + agent = FreebaseAgent() + mid = agent.getTopicId(args.movieName) + print 'freebase topic id (mid) is', mid + topic = agent.getTopic(mid) + print 'imdb id is', topic, 'so the url is http://www.imdb.com/title/'+topic + print agent.getImdbId(args.movieName) \ No newline at end of file diff --git a/idp/utils/listdownloader.py b/idp/utils/listdownloader.py index 5243485..fd21982 100644 --- a/idp/utils/listdownloader.py +++ b/idp/utils/listdownloader.py @@ -15,27 +15,31 @@ along with imdb-data-parser. If not, see . """ -from ..settings import * -from ftplib import FTP import gzip -from .filehandler import * import logging +import os +from ftplib import FTP +from .filehandler import FileHandler +from ..settings import * + def download(): - logging.info("lists will downloaded from server:" + INTERFACES_SERVER) + logging.info("Lists will downloaded from server:" + INTERFACES_SERVER) ftp = FTP(INTERFACES_SERVER) ftp.login() + download_count = 0 - for list in LISTS: + + for list_item in LISTS: try: - logging.info("started to download list:" + list) - r = ftp.retrbinary('RETR '+INTERFACES_DIRECTORY+list+'.list.gz', - open(INPUT_DIR+list+'.list.gz', 'wb').write) - logging.info(list + "list downloaded successfully") - download_count = download_count+1 - extract(get_full_path(list+".list", True)) + logging.info("Started to download list:" + list_item) + r = ftp.retrbinary("RETR " + INTERFACES_DIRECTORY + list_item + ".list.gz", open(INPUT_DIR + list_item + ".list.gz", "wb").write) + logging.info(list_item + "list downloaded successfully") + download_count = download_count + 1 + FileHandler.extract(FileHandler.get_full_path(list_item + ".list", True)) except Exception as e: - print("ERROR: there is a problem when downloading list " + list + "\n\t" + str(e)) + logging.error("There is a problem when downloading list " + list_item + "\n\t" + str(e)) + logging.info(str(download_count) + " lists are downloaded") ftp.quit() \ No newline at end of file diff --git a/idp/utils/loggerinitializer.py b/idp/utils/loggerinitializer.py index 250cad4..beaa747 100644 --- a/idp/utils/loggerinitializer.py +++ b/idp/utils/loggerinitializer.py @@ -18,7 +18,8 @@ import logging import os.path -def initialize_logger(preferencesMap): + +def initialize_logger(preferences_map): logger = logging.getLogger() logger.setLevel(logging.INFO) @@ -30,14 +31,14 @@ def initialize_logger(preferencesMap): logger.addHandler(ch) # create error file handler and set level to error - ch = logging.FileHandler(os.path.join(preferencesMap['outputDir'], 'imdbparserError.log'),'w', encoding=None, delay="true") + ch = logging.FileHandler(os.path.join(preferences_map['output_dir'], "imdbparserError.log"),"w", encoding=None, delay="true") ch.setLevel(logging.ERROR) formatter = logging.Formatter("%(levelname)s - %(message)s") ch.setFormatter(formatter) logger.addHandler(ch) # create info file handler and set level to info - ch = logging.FileHandler(os.path.join(preferencesMap['outputDir'], 'imdbparserAll.log'),'w') + ch = logging.FileHandler(os.path.join(preferences_map['output_dir'], "imdbparserAll.log"),"w") ch.setLevel(logging.INFO) formatter = logging.Formatter("%(levelname)s - %(message)s") ch.setFormatter(formatter) diff --git a/idp/utils/regexhelper.py b/idp/utils/regexhelper.py index e7d9d75..a402731 100644 --- a/idp/utils/regexhelper.py +++ b/idp/utils/regexhelper.py @@ -17,6 +17,7 @@ import re + class RegExHelper(object): def __init__(self, matchstring): self.matchstring = matchstring @@ -26,7 +27,7 @@ def match(self,regexp): return bool(self.rematch) def group(self,i): - if self.rematch.group(i) is None : + if self.rematch.group(i) is None: return "" else: return self.rematch.group(i) diff --git a/imdbparser.py b/imdbparser.py index b3d7176..6f1d9b6 100755 --- a/imdbparser.py +++ b/imdbparser.py @@ -24,11 +24,11 @@ import sys import argparse -import logging +import datetime from idp.utils.loggerinitializer import * from idp.parser.parsinghelper import ParsingHelper from idp.settings import * -import datetime + # check python version if sys.version_info.major != 3: @@ -49,30 +49,30 @@ mode = "TSV" if args.input_dir: - inputDir = args.input_dir + input_dir = args.input_dir else: - inputDir = INPUT_DIR + input_dir = INPUT_DIR postfix = datetime.datetime.now().strftime("%Y-%m-%d_%H%M%S") + '_ImdbParserOutput' if args.input_dir: - outputDir = os.path.join(args.output_dir, postfix) + output_dir = os.path.join(args.output_dir, postfix) else: - outputDir = os.path.join(OUTPUT_DIR, postfix) + output_dir = os.path.join(OUTPUT_DIR, postfix) -if not os.path.exists(outputDir): - os.makedirs(outputDir) +if not os.path.exists(output_dir): + os.makedirs(output_dir) -preferencesMap = { +preferences_map = { "mode":mode, - "inputDir": inputDir, - "outputDir": outputDir + "input_dir": input_dir, + "output_dir": output_dir } -initialize_logger(preferencesMap) +initialize_logger(preferences_map) logging.info("mode:%s", mode) -logging.info("input_dir:%s", inputDir) -logging.info("output_dir:%s", outputDir) +logging.info("input_dir:%s", input_dir) +logging.info("output_dir:%s", output_dir) logging.info("update_lists:%s", args.update_lists) if args.update_lists: @@ -82,7 +82,7 @@ logging.info("Parsing, please wait. This may take very long time...") -ParsingHelper.parse_all(preferencesMap) +ParsingHelper.parse_all(preferences_map) -logging.info("Check out output folder: %s", outputDir) +logging.info("Check out output folder: %s", output_dir) print ("All done, enjoy ;)") #don't print this via logger, this is part of the program From 15988302cbf282c393c917d430b08220de30bcc9 Mon Sep 17 00:00:00 2001 From: aykutakin Date: Fri, 22 Mar 2013 21:48:14 +0200 Subject: [PATCH 52/58] Adds sql scripts --- idp/parser/actorsparser.py | 45 ++++++++++++++++++++++++++++------- idp/parser/actressesparser.py | 40 ++++++++++++++++++++++++------- idp/parser/baseparser.py | 15 +++++++++++- idp/parser/directorsparser.py | 38 ++++++++++++++++++++++------- idp/parser/genresparser.py | 18 +++++++------- idp/parser/moviesparser.py | 25 ++++++++++--------- idp/parser/plotparser.py | 33 ++++++++++++++++++------- idp/parser/ratingsparser.py | 28 +++++++++++++++------- idp/parser/triviaparser.py | 1 + 9 files changed, 178 insertions(+), 65 deletions(-) diff --git a/idp/parser/actorsparser.py b/idp/parser/actorsparser.py index f419753..abf343f 100644 --- a/idp/parser/actorsparser.py +++ b/idp/parser/actorsparser.py @@ -42,10 +42,17 @@ class ActorsParser(BaseParser): base_matcher_pattern = '(.*?)\t+((.*? \(\S{4,}\)) ?(\(\S+\))? ?(?!\{\{SUSPENDED\}\})(\{(.*?) ?(\(\S+?\))?\})? ?(\{\{SUSPENDED\}\})?)\s*(\(.*?\))?\s*(\(.*\))?\s*(\[.*\])?\s*(<.*>)?$' input_file_name = "actors.list" number_of_lines_to_be_skipped = 239 - scripts = { #TODO: fill - 'drop' : '', - 'create' : '', - 'insert' : '' + db_table_info = { + 'tablename' : 'actors', + 'columns' : [ + {'colname' : 'name', 'colinfo' : DbScriptHelper.keywords['string'] + '(127)'}, + {'colname' : 'surname', 'colinfo' : DbScriptHelper.keywords['string'] + '(127)'}, + {'colname' : 'title', 'colinfo' : DbScriptHelper.keywords['string'] + '(255) NOT NULL'}, + {'colname' : 'info_1', 'colinfo' : DbScriptHelper.keywords['string'] + '(127)'}, + {'colname' : 'info_2', 'colinfo' : DbScriptHelper.keywords['string'] + '(127)'}, + {'colname' : 'role', 'colinfo' : DbScriptHelper.keywords['string'] + '(127)'} + ], + 'constraints' : 'PRIMARY KEY(title)' } end_of_dump_delimiter = "" @@ -54,9 +61,10 @@ class ActorsParser(BaseParser): def __init__(self, preferences_map): super(ActorsParser, self).__init__(preferences_map) + self.first_one = True def parse_into_tsv(self, matcher): - is_match = matcher.match(self.baseMatcherPattern) + is_match = matcher.match(self.base_matcher_pattern) if(is_match): if(len(matcher.group(1).strip()) > 0): @@ -68,7 +76,7 @@ def parse_into_tsv(self, matcher): self.name = namelist[0] self.surname = "" - self.tsv_file.write(self.name + self.seperator + self.surname + self.seperator + matcher.group(2) + self.seperator + matcher.group(3) + self.seperator + matcher.group(4) + self.seperator + matcher.group(6) + self.seperator + matcher.group(7) + self.seperator + matcher.group(8) + self.seperator + matcher.group(9) + self.seperator + matcher.group(10) + self.seperator + matcher.group(11) + "\n") + self.tsv_file.write(self.name + self.seperator + self.surname + self.seperator + self.concat_regex_groups([2,9,10,11], None, matcher) + "\n") elif(len(matcher.get_last_string()) == 1): pass else: @@ -76,5 +84,26 @@ def parse_into_tsv(self, matcher): self.fucked_up_count += 1 def parse_into_db(self, matcher): - #TODO - pass + is_match = matcher.match(self.base_matcher_pattern) + + if(is_match): + if(len(matcher.group(1).strip()) > 0): + namelist = matcher.group(1).split(', ') + if(len(namelist) == 2): + self.name = namelist[1] + self.surname = namelist[0] + else: + self.name = namelist[0] + self.surname = "" + + if(self.first_one): + self.sql_file.write("(\"" + self.name + "\", \"" + self.surname + "\", " + self.concat_regex_groups([2,9,10,11], [2,3,4,5], matcher) + ")") + self.first_one = False; + else: + self.sql_file.write(",\n(\"" + self.name + "\", \"" + self.surname + "\", " + self.concat_regex_groups([2,9,10,11], [2,3,4,5], matcher) + ")") + + elif(len(matcher.get_last_string()) == 1): + pass + else: + logging.critical("This line is fucked up: " + matcher.get_last_string()) + self.fucked_up_count += 1 diff --git a/idp/parser/actressesparser.py b/idp/parser/actressesparser.py index a71796c..3cdb6b4 100644 --- a/idp/parser/actressesparser.py +++ b/idp/parser/actressesparser.py @@ -45,12 +45,14 @@ class ActressesParser(BaseParser): db_table_info = { 'tablename' : 'actresses', 'columns' : [ - { - 'colname' : '', - 'colinfo' : DbScriptHelper.keywords['string'] + '(255) NOT NULL' - } + {'colname' : 'name', 'colinfo' : DbScriptHelper.keywords['string'] + '(127)'}, + {'colname' : 'surname', 'colinfo' : DbScriptHelper.keywords['string'] + '(127)'}, + {'colname' : 'title', 'colinfo' : DbScriptHelper.keywords['string'] + '(255) NOT NULL'}, + {'colname' : 'info_1', 'colinfo' : DbScriptHelper.keywords['string'] + '(127)'}, + {'colname' : 'info_2', 'colinfo' : DbScriptHelper.keywords['string'] + '(127)'}, + {'colname' : 'role', 'colinfo' : DbScriptHelper.keywords['string'] + '(127)'} ], - 'constraints' : '' + 'constraints' : 'PRIMARY KEY(title)' } end_of_dump_delimiter = "" @@ -59,6 +61,7 @@ class ActressesParser(BaseParser): def __init__(self, preferences_map): super(ActressesParser, self).__init__(preferences_map) + self.first_one = True def parse_into_tsv(self, matcher): is_match = matcher.match(self.base_matcher_pattern) @@ -73,7 +76,7 @@ def parse_into_tsv(self, matcher): self.name = namelist[0] self.surname = "" - self.tsv_file.write(self.name + self.seperator + self.surname + self.seperator + matcher.group(2) + self.seperator + matcher.group(3) + self.seperator + matcher.group(4) + self.seperator + matcher.group(6) + self.seperator + matcher.group(7) + self.seperator + matcher.group(8) + self.seperator + matcher.group(9) + self.seperator + matcher.group(10) + self.seperator + matcher.group(11) + "\n") + self.tsv_file.write(self.name + self.seperator + self.surname + self.seperator + self.concat_regex_groups([2,9,10,11], None, matcher) + "\n") elif(len(matcher.get_last_string()) == 1): pass else: @@ -81,5 +84,26 @@ def parse_into_tsv(self, matcher): self.fucked_up_count += 1 def parse_into_db(self, matcher): - #TODO - pass + is_match = matcher.match(self.base_matcher_pattern) + + if(is_match): + if(len(matcher.group(1).strip()) > 0): + namelist = matcher.group(1).split(', ') + if(len(namelist) == 2): + self.name = namelist[1] + self.surname = namelist[0] + else: + self.name = namelist[0] + self.surname = "" + + if(self.first_one): + self.sql_file.write("(\"" + self.name + "\", \"" + self.surname + "\", " + self.concat_regex_groups([2,9,10,11], [2,3,4,5], matcher) + ")") + self.first_one = False; + else: + self.sql_file.write(",\n(\"" + self.name + "\", \"" + self.surname + "\", " + self.concat_regex_groups([2,9,10,11], [2,3,4,5], matcher) + ")") + + elif(len(matcher.get_last_string()) == 1): + pass + else: + logging.critical("This line is fucked up: " + matcher.get_last_string()) + self.fucked_up_count += 1 diff --git a/idp/parser/baseparser.py b/idp/parser/baseparser.py index 415f9b6..6b83189 100644 --- a/idp/parser/baseparser.py +++ b/idp/parser/baseparser.py @@ -110,6 +110,19 @@ def start_processing(self): # fuckedUpCount is calculated in implementing class logging.info("Finished with " + str(self.fucked_up_count) + " fucked up line") + def concat_regex_groups(self, group_list, col_list, matcher): + ret_val = "" + if col_list == None: + ret_val = self.seperator.join('%s' % (matcher.group(i)) for i in group_list) + else: + for i in range(len(group_list)): + if DbScriptHelper.keywords['string'] in self.db_table_info['columns'][col_list[i]]['colinfo']: + ret_val += "\"" + re.escape(matcher.group(group_list[i])) + "\", " + else: + ret_val += matcher.group(group_list[i]) + ", " + ret_val = ret_val[:-2] + return ret_val + ##### Below methods force associated properties to be defined in any derived class ##### @abstractproperty @@ -130,4 +143,4 @@ def db_table_info(self): @abstractproperty def end_of_dump_delimiter(self): - raise NotImplemented \ No newline at end of file + raise NotImplemented diff --git a/idp/parser/directorsparser.py b/idp/parser/directorsparser.py index e374d59..cc94531 100644 --- a/idp/parser/directorsparser.py +++ b/idp/parser/directorsparser.py @@ -43,12 +43,12 @@ class DirectorsParser(BaseParser): db_table_info = { 'tablename' : 'directors', 'columns' : [ - { - 'colname' : '', - 'colinfo' : DbScriptHelper.keywords['string'] + '(255) NOT NULL' - } + {'colname' : 'name', 'colinfo' : DbScriptHelper.keywords['string'] + '(127)'}, + {'colname' : 'surname', 'colinfo' : DbScriptHelper.keywords['string'] + '(127)'}, + {'colname' : 'title', 'colinfo' : DbScriptHelper.keywords['string'] + '(255) NOT NULL'}, + {'colname' : 'info', 'colinfo' : DbScriptHelper.keywords['string'] + '(127)'} ], - 'constraints' : '' + 'constraints' : 'PRIMARY KEY(title)' } end_of_dump_delimiter = "" @@ -57,6 +57,7 @@ class DirectorsParser(BaseParser): def __init__(self, preferences_map): super(DirectorsParser, self).__init__(preferences_map) + self.first_one = True def parse_into_tsv(self, matcher): is_match = matcher.match(self.base_matcher_pattern) @@ -71,7 +72,7 @@ def parse_into_tsv(self, matcher): self.name = namelist[0] self.surname = "" - self.tsv_file.write(self.name + self.seperator + self.surname + self.seperator + matcher.group(2) + self.seperator + matcher.group(3) + self.seperator + matcher.group(4) + self.seperator + matcher.group(6) + self.seperator + matcher.group(7) + self.seperator + matcher.group(8) + self.seperator + matcher.group(9) + "\n") + self.tsv_file.write(self.name + self.seperator + self.surname + self.seperator + self.concat_regex_groups([10,11], None, matcher) + "\n") elif(len(matcher.get_last_string()) == 1): pass else: @@ -79,5 +80,26 @@ def parse_into_tsv(self, matcher): self.fucked_up_count += 1 def parse_into_db(self, matcher): - #TODO - pass + is_match = matcher.match(self.base_matcher_pattern) + + if(is_match): + if(len(matcher.group(1).strip()) > 0): + namelist = matcher.group(1).split(', ') + if(len(namelist) == 2): + self.name = namelist[1] + self.surname = namelist[0] + else: + self.name = namelist[0] + self.surname = "" + + if(self.first_one): + self.sql_file.write("(\"" + self.name + "\", \"" + self.surname + "\", " + self.concat_regex_groups([2,9], [2,3], matcher) + ")") + self.first_one = False; + else: + self.sql_file.write(",\n(\"" + self.name + "\", \"" + self.surname + "\", " + self.concat_regex_groups([2,9], [2,3], matcher) + ")") + + elif(len(matcher.get_last_string()) == 1): + pass + else: + logging.critical("This line is fucked up: " + matcher.get_last_string()) + self.fucked_up_count += 1 diff --git a/idp/parser/genresparser.py b/idp/parser/genresparser.py index 592805b..cdbe049 100644 --- a/idp/parser/genresparser.py +++ b/idp/parser/genresparser.py @@ -41,24 +41,22 @@ class GenresParser(BaseParser): db_table_info = { 'tablename' : 'genres', 'columns' : [ - { - 'colname' : '', - 'colinfo' : DbScriptHelper.keywords['string'] + '(255) NOT NULL' - } + {'colname' : 'title', 'colinfo' : DbScriptHelper.keywords['string'] + '(255) NOT NULL'}, + {'colname' : 'genre', 'colinfo' : DbScriptHelper.keywords['string'] + '(127)'} ], - 'constraints' : '' + 'constraints' : 'PRIMARY KEY(title)' } end_of_dump_delimiter = "" def __init__(self, preferences_map): super(GenresParser, self).__init__(preferences_map) - self.first_one=True + self.first_one = True def parse_into_tsv(self, matcher): is_match = matcher.match(self.base_matcher_pattern) if(is_match): - self.tsv_file.write(matcher.group(1) + self.seperator + matcher.group(2) + self.seperator + matcher.group(3) + self.seperator + matcher.group(5) + self.seperator + matcher.group(6) + self.seperator + matcher.group(7) + self.seperator + matcher.group(8) + "\n") + self.tsv_file.write(self.concat_regex_groups([1,8], None, matcher) + "\n") else: logging.critical("This line is fucked up: " + matcher.get_last_string()) self.fucked_up_count += 1 @@ -68,10 +66,10 @@ def parse_into_db(self, matcher): if(is_match): if(self.first_one): - self.sql_file.write("(\"" + re.escape(matcher.group(1)) + "\", \"" + matcher.group(8) + "\")") - self.first_one=False; + self.sql_file.write("(" + self.concat_regex_groups([1,8], [0,1], matcher) + ")") + self.first_one = False; else: - self.sql_file.write(",\n(\"" + re.escape(matcher.group(1)) + "\", \"" + matcher.group(8) + "\")") + self.sql_file.write(",\n(" + self.concat_regex_groups([1,8], [0,1], matcher) + ")") else: logging.critical("This line is fucked up: " + matcher.get_last_string()) self.fucked_up_count += 1 diff --git a/idp/parser/moviesparser.py b/idp/parser/moviesparser.py index 82d74db..eda6433 100644 --- a/idp/parser/moviesparser.py +++ b/idp/parser/moviesparser.py @@ -44,14 +44,13 @@ class MoviesParser(BaseParser): db_table_info = { 'tablename' : 'movies', 'columns' : [ - { - 'colname' : 'title', - 'colinfo' : DbScriptHelper.keywords['string'] + '(255) NOT NULL' - }, - { - 'colname' : 'year', - 'colinfo' : DbScriptHelper.keywords['number'] - } + {'colname' : 'title', 'colinfo' : DbScriptHelper.keywords['string'] + '(255) NOT NULL'}, + {'colname' : 'full_name', 'colinfo' : DbScriptHelper.keywords['string'] + '(127)'}, + {'colname' : 'type', 'colinfo' : DbScriptHelper.keywords['string'] + '(20)'}, + {'colname' : 'ep_name', 'colinfo' : DbScriptHelper.keywords['string'] + '(127)'}, + {'colname' : 'ep_num', 'colinfo' : DbScriptHelper.keywords['string'] + '(20)'}, + {'colname' : 'suspended', 'colinfo' : DbScriptHelper.keywords['string'] + '(20)'}, + {'colname' : 'year', 'colinfo' : DbScriptHelper.keywords['string'] + '(20)'} ], 'constraints' : 'PRIMARY KEY(title)' } @@ -59,13 +58,13 @@ class MoviesParser(BaseParser): def __init__(self, preferences_map): super(MoviesParser, self).__init__(preferences_map) - self.first_one=True + self.first_one = True def parse_into_tsv(self, matcher): is_match = matcher.match(self.base_matcher_pattern) if(is_match): - self.tsv_file.write(matcher.group(1) + self.seperator + matcher.group(2) + self.seperator + matcher.group(3) + self.seperator + matcher.group(5) + self.seperator + matcher.group(6) + self.seperator + matcher.group(7) + self.seperator + matcher.group(8) + "\n") + self.tsv_file.write(self.concat_regex_groups([1,2,3,5,6,7,8], None, matcher) + "\n") else: logging.critical("This line is fucked up: " + matcher.get_last_string()) self.fucked_up_count += 1 @@ -75,10 +74,10 @@ def parse_into_db(self, matcher): if(is_match): if(self.first_one): - self.sql_file.write("(\"" + re.escape(matcher.group(1)) + "\", " + matcher.group(8) + ")") - self.first_one=False; + self.sql_file.write("(" + self.concat_regex_groups([1,2,3,5,6,7,8], [0,1,2,3,4,5,6], matcher) + ")") + self.first_one = False; else: - self.sql_file.write(",\n(\"" + re.escape(matcher.group(1)) + "\", " + matcher.group(8) + ")") + self.sql_file.write(",\n(" + self.concat_regex_groups([1,2,3,5,6,7,8], [0,1,2,3,4,5,6], matcher) + ")") else: logging.critical("This line is fucked up: " + matcher.get_last_string()) self.fucked_up_count += 1 diff --git a/idp/parser/plotparser.py b/idp/parser/plotparser.py index 17217e2..066c20c 100644 --- a/idp/parser/plotparser.py +++ b/idp/parser/plotparser.py @@ -36,17 +36,16 @@ class PlotParser(BaseParser): db_table_info = { 'tablename' : 'plot', 'columns' : [ - { - 'colname' : '', - 'colinfo' : DbScriptHelper.keywords['string'] + '(255) NOT NULL' - } + {'colname' : 'title', 'colinfo' : DbScriptHelper.keywords['string'] + '(255) NOT NULL'}, + {'colname' : 'plot', 'colinfo' : DbScriptHelper.keywords['string'] + '(4000)'} ], - 'constraints' : '' + 'constraints' : 'PRIMARY KEY(title)' } end_of_dump_delimiter = "" def __init__(self, preferences_map): super(PlotParser, self).__init__(preferences_map) + self.first_one = True # specific to this class self.title = "" @@ -58,7 +57,7 @@ def parse_into_tsv(self, matcher): if(is_match): if(matcher.group(1) == "MV"): #Title if(self.title != ""): - self.outputFile.write(self.title + self.seperator + self.plot + "\n") + self.tsv_file.write(self.title + self.seperator + self.plot + "\n") self.plot = "" self.title = matcher.group(2) @@ -82,5 +81,23 @@ def parse_into_tsv(self, matcher): """ def parse_into_db(self, matcher): - #TODO - pass + is_match = matcher.match(self.base_matcher_pattern) + + if(is_match): + if(matcher.group(1) == "MV"): #Title + if(self.title != ""): + if(self.first_one): + self.sql_file.write("(\"" + self.title + "\", \"" + self.plot + "\")") + self.first_one = False; + else: + self.sql_file.write(",\n(\"" + self.title + "\", \"" + self.plot + "\")") + + self.plot = "" + self.title = matcher.group(2) + + elif(matcher.group(1) == "PL"): #Descriptive text + self.plot += matcher.group(2) + elif(matcher.group(1) == "BY"): + pass + else: + logging.critical("Unhandled abbreviation: " + matcher.group(1) + " in " + line) diff --git a/idp/parser/ratingsparser.py b/idp/parser/ratingsparser.py index 80907e7..90e4fff 100644 --- a/idp/parser/ratingsparser.py +++ b/idp/parser/ratingsparser.py @@ -43,27 +43,37 @@ class RatingsParser(BaseParser): db_table_info = { 'tablename' : 'ratings', 'columns' : [ - { - 'colname' : '', - 'colinfo' : DbScriptHelper.keywords['string'] + '(255) NOT NULL' - } + {'colname' : 'distribution', 'colinfo' : DbScriptHelper.keywords['string'] + '(127) NOT NULL'}, + {'colname' : 'votes', 'colinfo' : DbScriptHelper.keywords['string'] + '(127)'}, + {'colname' : 'rank', 'colinfo' : DbScriptHelper.keywords['string'] + '(127)'}, + {'colname' : 'title', 'colinfo' : DbScriptHelper.keywords['string'] + '(255) NOT NULL'} ], - 'constraints' : '' + 'constraints' : 'PRIMARY KEY(title)' } end_of_dump_delimiter = "" def __init__(self, preferences_map): super(RatingsParser, self).__init__(preferences_map) + self.first_one = True def parse_into_tsv(self, matcher): is_match = matcher.match(self.base_matcher_pattern) if(is_match): - self.tsv_file.write(matcher.group(1) + self.seperator + matcher.group(2) + self.seperator + matcher.group(3) + self.seperator + matcher.group(4) + self.seperator + matcher.group(5) + self.seperator + matcher.group(6) + self.seperator + matcher.group(8) + self.seperator + matcher.group(8) + self.seperator + matcher.group(9) + self.seperator + matcher.group(10) + "\n") + self.tsv_file.write(self.concat_regex_groups([1,2,3,4], None, matcher) + "\n") else: logging.critical("This line is fucked up: " + matcher.get_last_string()) - self.fuckedUpCount += 1 + self.fucked_up_count += 1 def parse_into_db(self, matcher): - #TODO - pass + is_match = matcher.match(self.base_matcher_pattern) + + if(is_match): + if(self.first_one): + self.sql_file.write("(" + self.concat_regex_groups([1,2,3,4], [0,1,2,3], matcher) + ")") + self.first_one = False; + else: + self.sql_file.write(",\n(" + self.concat_regex_groups([1,2,3,4], [0,1,2,3], matcher) + ")") + else: + logging.critical("This line is fucked up: " + matcher.get_last_string()) + self.fucked_up_count += 1 diff --git a/idp/parser/triviaparser.py b/idp/parser/triviaparser.py index dced4b7..a0e8af2 100644 --- a/idp/parser/triviaparser.py +++ b/idp/parser/triviaparser.py @@ -50,6 +50,7 @@ class TriviaParser(BaseParser): def __init__(self, preferences_map): super(TriviaParser, self).__init__(preferences_map) + self.first_one = True def parse_into_tsv(self, matcher): is_match = matcher.match(self.base_matcher_pattern) From c88242877aeb2cda303d2301fb4a48d4c6c45fe5 Mon Sep 17 00:00:00 2001 From: aykutakin Date: Mon, 25 Mar 2013 22:36:56 +0200 Subject: [PATCH 53/58] Adds commit to sql files --- idp/parser/baseparser.py | 7 ++----- idp/parser/directorsparser.py | 2 +- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/idp/parser/baseparser.py b/idp/parser/baseparser.py index 6b83189..2374fd9 100644 --- a/idp/parser/baseparser.py +++ b/idp/parser/baseparser.py @@ -53,10 +53,7 @@ def __init__(self, preferences_map): self.tsv_file = self.filehandler.get_tsv_file() elif (self.mode == "SQL"): self.sql_file = self.filehandler.get_sql_file() - self.scripthelper = DbScriptHelper(self.db_table_info) - self.sql_file.write(self.scripthelper.scripts['drop']) - self.sql_file.write(self.scripthelper.scripts['create']) - self.sql_file.write(self.scripthelper.scripts['insert']) + self.sql_file.write(DbScriptHelper.initial_sql_script(self.db_table_info)) @abstractmethod def parse_into_tsv(self, matcher): @@ -100,7 +97,7 @@ def start_processing(self): self.input_file.close() if(self.mode == "SQL"): - self.sql_file.write(";") + self.sql_file.write(";\n COMMIT;") self.sql_file.close() if 'outputFile' in locals(): diff --git a/idp/parser/directorsparser.py b/idp/parser/directorsparser.py index cc94531..6f77ca7 100644 --- a/idp/parser/directorsparser.py +++ b/idp/parser/directorsparser.py @@ -72,7 +72,7 @@ def parse_into_tsv(self, matcher): self.name = namelist[0] self.surname = "" - self.tsv_file.write(self.name + self.seperator + self.surname + self.seperator + self.concat_regex_groups([10,11], None, matcher) + "\n") + self.tsv_file.write(self.name + self.seperator + self.surname + self.seperator + self.concat_regex_groups([2,9], None, matcher) + "\n") elif(len(matcher.get_last_string()) == 1): pass else: From 7aa48a7c167252de02b88ae1e577213d16ce1c99 Mon Sep 17 00:00:00 2001 From: aykutakin Date: Sun, 14 Apr 2013 10:56:08 +0300 Subject: [PATCH 54/58] Fix sql file bug --- idp/parser/baseparser.py | 5 ++++- idp/utils/dbscripthelper.py | 5 +++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/idp/parser/baseparser.py b/idp/parser/baseparser.py index 2374fd9..b9dfeb7 100644 --- a/idp/parser/baseparser.py +++ b/idp/parser/baseparser.py @@ -53,7 +53,10 @@ def __init__(self, preferences_map): self.tsv_file = self.filehandler.get_tsv_file() elif (self.mode == "SQL"): self.sql_file = self.filehandler.get_sql_file() - self.sql_file.write(DbScriptHelper.initial_sql_script(self.db_table_info)) + self.scripthelper = DbScriptHelper(self.db_table_info) + self.sql_file.write(self.scripthelper.scripts['drop']) + self.sql_file.write(self.scripthelper.scripts['create']) + self.sql_file.write(self.scripthelper.scripts['insert']) @abstractmethod def parse_into_tsv(self, matcher): diff --git a/idp/utils/dbscripthelper.py b/idp/utils/dbscripthelper.py index cf14f44..8cfa4e5 100644 --- a/idp/utils/dbscripthelper.py +++ b/idp/utils/dbscripthelper.py @@ -32,6 +32,11 @@ class DbScriptHelper(object): } def __init__(self, db_table_info): + self.scripts = { + 'drop': "DROP TABLE ", + 'create': "CREATE TABLE ", + 'insert': "INSERT INTO " + } self.scripts['drop'] += db_table_info['tablename'] + ";" + os.linesep self.scripts['create'] += db_table_info['tablename'] + "(" + ', '.join(filter(None, (', '.join('%s %s' % (col['colname'], col['colinfo']) for col in db_table_info['columns']), db_table_info['constraints']))) + ") CHARACTER SET utf8 COLLATE utf8_bin;" + os.linesep self.scripts['insert'] += db_table_info['tablename'] + "(" + ', '.join(col['colname'] for col in db_table_info['columns']) + ") VALUES" + os.linesep \ No newline at end of file From 67c094cb1daa5e7e7f90d4a5514bf0ccaf44b913 Mon Sep 17 00:00:00 2001 From: aykutakin Date: Sun, 12 May 2013 17:59:26 +0300 Subject: [PATCH 55/58] Some files cannot be opened with utf-8 --- idp/utils/filehandler.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/idp/utils/filehandler.py b/idp/utils/filehandler.py index 5b5bac8..17263dd 100644 --- a/idp/utils/filehandler.py +++ b/idp/utils/filehandler.py @@ -40,7 +40,7 @@ def get_input_file(self): logging.info("Trying to find file: %s", full_file_path) if os.path.isfile(full_file_path): logging.info("File found: %s", full_file_path) - return open(full_file_path, "r", encoding='utf-8') + return open(full_file_path, "r", encoding='iso-8859-1') logging.error("File cannot be found: %s", full_file_path) @@ -48,7 +48,7 @@ def get_input_file(self): if os.path.isfile(full_file_path + ".gz"): logging.info("File found: %s", full_file_path + ".gz") if extract(full_file_path + ".gz") == 0: - return open(full_file_path, "r", encoding='utf-8') + return open(full_file_path, "r", encoding='iso-8859-1') else: raise RuntimeError("Unknown error occured") From f9e1bcd4d82223496e489f7b2d027cb41a58fad4 Mon Sep 17 00:00:00 2001 From: Mehmet Beydogan Date: Sun, 30 Jun 2013 00:15:47 +0300 Subject: [PATCH 56/58] 'FileHandler' has no attribute 'get_full_path' error fixed. --- idp/utils/filehandler.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/idp/utils/filehandler.py b/idp/utils/filehandler.py index 17263dd..d1c5227 100644 --- a/idp/utils/filehandler.py +++ b/idp/utils/filehandler.py @@ -82,4 +82,14 @@ def extract(gzip_path): except Exception as e: logging.error("Error when extracting list: " + gzip_path + "\n\t" + str(e)) return 1 - return 0 \ No newline at end of file + return 0 + + def get_full_path(filename, isCompressed = False): + """ + constructs a full path for a dump file in the INPUT_DIR + filename should be without '.list' + """ + if(isCompressed): + return os.path.join(INPUT_DIR, filename) + ".gz" + else: + return os.path.join(INPUT_DIR, filename) \ No newline at end of file From 179b941ece621c7e3436962b6a76be61a6484a98 Mon Sep 17 00:00:00 2001 From: Mairbek Khadikov Date: Fri, 26 Jul 2013 14:08:18 +0300 Subject: [PATCH 57/58] Fixed path string building --- idp/utils/listdownloader.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/idp/utils/listdownloader.py b/idp/utils/listdownloader.py index fd21982..a2133f5 100644 --- a/idp/utils/listdownloader.py +++ b/idp/utils/listdownloader.py @@ -34,7 +34,7 @@ def download(): for list_item in LISTS: try: logging.info("Started to download list:" + list_item) - r = ftp.retrbinary("RETR " + INTERFACES_DIRECTORY + list_item + ".list.gz", open(INPUT_DIR + list_item + ".list.gz", "wb").write) + r = ftp.retrbinary("RETR " + INTERFACES_DIRECTORY + list_item + ".list.gz", open(os.path.join(INPUT_DIR, list_item + ".list.gz"), "wb").write) logging.info(list_item + "list downloaded successfully") download_count = download_count + 1 FileHandler.extract(FileHandler.get_full_path(list_item + ".list", True)) @@ -42,4 +42,4 @@ def download(): logging.error("There is a problem when downloading list " + list_item + "\n\t" + str(e)) logging.info(str(download_count) + " lists are downloaded") - ftp.quit() \ No newline at end of file + ftp.quit() From 20671ab98e2065bbe0a32aef0402776934a2863b Mon Sep 17 00:00:00 2001 From: aykutakin Date: Sat, 3 Aug 2013 14:50:09 +0300 Subject: [PATCH 58/58] closes #7 writing processed lines to console increases time too much Necessary line is still inside the baseparser.py file. If you want to see process of parsing, you can uncomment out that line --- idp/parser/baseparser.py | 2 ++ idp/parser/moviesparser.py | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/idp/parser/baseparser.py b/idp/parser/baseparser.py index b9dfeb7..4ea8614 100644 --- a/idp/parser/baseparser.py +++ b/idp/parser/baseparser.py @@ -97,6 +97,8 @@ def start_processing(self): number_of_processed_lines += 1 + #print("Processed lines: %d\r" % (number_of_processed_lines), end="") + self.input_file.close() if(self.mode == "SQL"): diff --git a/idp/parser/moviesparser.py b/idp/parser/moviesparser.py index eda6433..bc488d4 100644 --- a/idp/parser/moviesparser.py +++ b/idp/parser/moviesparser.py @@ -54,7 +54,7 @@ class MoviesParser(BaseParser): ], 'constraints' : 'PRIMARY KEY(title)' } - end_of_dump_delimiter = "" + end_of_dump_delimiter = "--------------------------------------------------------------------------------" def __init__(self, preferences_map): super(MoviesParser, self).__init__(preferences_map)