comparison data_generation/transformations/pycaptcha/Captcha/File.py @ 167:1f5937e9e530

More moves - transformations into data_generation, added "deep" folder
author Dumitru Erhan <dumitru.erhan@gmail.com>
date Fri, 26 Feb 2010 14:15:38 -0500
parents pycaptcha/Captcha/File.py@4775b4195b4b
children 81f8466dc121
comparison
equal deleted inserted replaced
166:17ae5a1a4dd1 167:1f5937e9e530
1 """ Captcha.File
2
3 Utilities for finding and picking random files from our 'data' directory
4 """
5 #
6 # PyCAPTCHA Package
7 # Copyright (C) 2004 Micah Dowty <micah@navi.cx>
8 #
9
10 import os, random
11
12 # Determine the data directory. This can be overridden after import-time if needed.
13 dataDir = os.path.join(os.path.split(os.path.abspath(__file__))[0], "data")
14
15
16 class RandomFileFactory(object):
17 """Given a list of files and/or directories, this picks a random file.
18 Directories are searched for files matching any of a list of extensions.
19 Files are relative to our data directory plus a subclass-specified base path.
20 """
21 extensions = []
22 basePath = "."
23
24 def __init__(self, *fileList):
25 self.fileList = fileList
26 self._fullPaths = None
27
28 def _checkExtension(self, name):
29 """Check the file against our given list of extensions"""
30 for ext in self.extensions:
31 if name.endswith(ext):
32 return True
33 return False
34
35 def _findFullPaths(self):
36 """From our given file list, find a list of full paths to files"""
37 paths = []
38 for name in self.fileList:
39 path = os.path.join(dataDir, self.basePath, name)
40 if os.path.isdir(path):
41 for content in os.listdir(path):
42 if self._checkExtension(content):
43 paths.append(os.path.join(path, content))
44 else:
45 paths.append(path)
46 return paths
47
48 def pick(self):
49 if self._fullPaths is None:
50 self._fullPaths = self._findFullPaths()
51 return random.choice(self._fullPaths)
52
53 ### The End ###