Mercurial > ift6266
annotate data_generation/transformations/pycaptcha/Captcha/File.py @ 195:92c9a6c48ce9
Add option for test.py to test modules specified on the command-line.
author | Arnaud Bergeron <abergeron@gmail.com> |
---|---|
date | Tue, 02 Mar 2010 18:01:22 -0500 |
parents | 81f8466dc121 |
children | 7800be7bce66 |
rev | line source |
---|---|
87 | 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: | |
184
81f8466dc121
Transient exception handling in captchas (ie. lorsque le NFS est temporairement inaccessible)
boulanni <nicolas_boulanger@hotmail.com>
parents:
167
diff
changeset
|
39 if name[0] == '/': |
81f8466dc121
Transient exception handling in captchas (ie. lorsque le NFS est temporairement inaccessible)
boulanni <nicolas_boulanger@hotmail.com>
parents:
167
diff
changeset
|
40 path = name |
81f8466dc121
Transient exception handling in captchas (ie. lorsque le NFS est temporairement inaccessible)
boulanni <nicolas_boulanger@hotmail.com>
parents:
167
diff
changeset
|
41 else: |
81f8466dc121
Transient exception handling in captchas (ie. lorsque le NFS est temporairement inaccessible)
boulanni <nicolas_boulanger@hotmail.com>
parents:
167
diff
changeset
|
42 path = os.path.join(dataDir, self.basePath, name) |
87 | 43 if os.path.isdir(path): |
44 for content in os.listdir(path): | |
45 if self._checkExtension(content): | |
46 paths.append(os.path.join(path, content)) | |
47 else: | |
48 paths.append(path) | |
49 return paths | |
50 | |
51 def pick(self): | |
52 if self._fullPaths is None: | |
53 self._fullPaths = self._findFullPaths() | |
54 return random.choice(self._fullPaths) | |
55 | |
56 ### The End ### |