PyLucene 3.4.0-1 import
[pylucene.git] / samples / LuceneInAction / lia / handlingtypes / framework / FileIndexer.py
1 # ====================================================================
2 #   Licensed under the Apache License, Version 2.0 (the "License");
3 #   you may not use this file except in compliance with the License.
4 #   You may obtain a copy of the License at
5 #
6 #       http://www.apache.org/licenses/LICENSE-2.0
7 #
8 #   Unless required by applicable law or agreed to in writing, software
9 #   distributed under the License is distributed on an "AS IS" BASIS,
10 #   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 #   See the License for the specific language governing permissions and
12 #   limitations under the License.
13 # ====================================================================
14
15 import os
16 import lia.handlingtypes as handlingtypes
17
18 from time import time
19 from datetime import timedelta
20 from lucene import IndexWriter, StandardAnalyzer
21
22 from lia.util.ClassLoader import ClassLoader
23
24  #
25  # A File Indexer capable of recursively indexing a directory tree.
26  # Based on lia.meetlucene.Indexer, but handling more than plaintext.
27  #
28
29 class FileIndexer(object):
30
31     def main(cls, argv):
32
33         if len(argv) != 3:
34             print "Usage: python FileIndexer.py <index dir> <data dir>"
35             return
36
37         indexDir = argv[1]
38         dataDir = argv[2]
39
40         propsFile = os.path.join(os.path.dirname(handlingtypes.__file__),
41                                  'framework', 'handler.properties')
42         input = file(propsFile)
43         props = {}
44         while True:
45             line = input.readline().strip()
46             if not line:
47                 break
48             if line.startswith('#'):
49                 continue
50             name, value = line.split('=')
51             props[name.strip()] = value.strip()
52         input.close()
53         cls.handlerProps = props
54
55         start = time()
56         numIndexed = cls.index(indexDir, dataDir)
57         duration = timedelta(seconds=time() - start)
58
59         print "Indexing %s files took %s" %(numIndexed, duration)
60
61     def index(cls, indexDir, dataDir):
62
63         if not (os.path.exists(dataDir) and os.path.isdir(dataDir)):
64             raise IOError, "%s does not exist or is not a directory" %(dataDir)
65
66         writer = IndexWriter(indexDir, StandardAnalyzer(), True,
67                              IndexWriter.MaxFieldLength.UNLIMITED)
68         writer.setUseCompoundFile(False)
69
70         numIndexed = cls.indexDirectory(writer, dataDir)
71         writer.optimize()
72         writer.close()
73
74         return numIndexed
75
76     def indexDirectory(cls, writer, dir):
77
78         count = 0
79         dirs = []
80
81         for name in os.listdir(dir):
82             path = os.path.join(dir, name)
83             if os.path.isfile(path):
84                 doc = cls.indexFile(writer, path)
85                 if doc is not None:
86                     count += 1
87             elif os.path.isdir(path) and not name.startswith('.'):
88                 dirs.append(path)
89
90         for dir in dirs:
91             count += cls.indexDirectory(writer, dir)
92
93         return count
94
95     def indexFile(cls, writer, path):
96
97         name, ext = os.path.splitext(path)
98         if ext.startswith(os.path.extsep):
99             ext = ext[len(os.path.extsep):]
100
101         if ext:
102             handlerClassName = cls.handlerProps.get(ext, None)
103             if handlerClassName is None:
104                 print "error indexing %s: no handler for %s files" %(path, ext)
105                 return None
106
107             try:
108                 handlerClass = ClassLoader.loadClass(handlerClassName)
109                 handler = handlerClass()
110
111                 doc = handler.indexFile(writer, path)
112                 if doc is not None:
113                     print 'indexed', path
114
115                 return doc
116             except SyntaxError:
117                 raise
118             except Exception, e:
119                 print 'error indexing %s: %s' %(path, e)
120                 return None
121
122     main = classmethod(main)
123     index = classmethod(index)
124     indexDirectory = classmethod(indexDirectory)
125     indexFile = classmethod(indexFile)