root/trunk/djedna/catalog/util.py

Revision 418, 6.7 kB (checked in by thomas, 9 months ago)

code cleanup

Line 
1 # (c) Copyright 2008 Thomas Bohmbach, Jr.
2 #
3 # This file is part of DJ Edna.
4 #
5 # DJ Edna is free software: you can redistribute it and/or modify it under the
6 # terms of the GNU General Public License as published by the Free
7 # Software Foundation, either version 3 of the License, or (at your option)
8 # any later version.
9 #
10 # DJ Edna is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 # or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
13 # more details.
14 #
15 # You should have received a copy of the GNU General Public License along with
16 # DJ Edna.  If not, see <http://www.gnu.org/licenses/>.
17
18 import os, math, md5, operator, pickle, sys
19 import logging as log
20
21 from django.conf import settings
22 from django.utils.encoding import smart_str, smart_unicode
23
24
25 def is_music_file(filename):
26     root, ext = os.path.splitext(filename)
27     # if we have a valid root and ext is an audio file ext, we'll assume this is a music file
28     if len(root) > 0 and root[0] != '.' and ext[1:] in settings.AUDIO_FILE_EXTENSIONS:
29         return True
30     return False
31
32 def is_same_image(first_image, second_image, tolerance=settings.IMAGE_MATCH_TOLERANCE):
33     return get_images_rms(first_image, second_image) < tolerance
34
35 def get_images_rms(first_image, second_image):
36     h1 = first_image.histogram()
37     h2 = second_image.histogram()
38     rms = math.sqrt(reduce(operator.add, map(lambda a,b: (a-b)**2, h1, h2))/len(h1))
39     return rms
40    
41 ####
42 #   Display names
43 ####
44 display_name_saved_dict = None   
45
46 def find_display_name(name):
47     # first, see if we have a previously saved display name
48     display_name = display_name_from_saved(name)
49    
50     # otherwise, try to calculate it
51     if not display_name:
52         display_name = display_name_from_name(name)
53        
54     return display_name
55
56 def set_display_name(name, display_name):
57     global display_name_saved_dict
58     is_dict_modified = False
59  
60     ensure_display_name_saved_dict_loaded()
61
62     # first let's see what we'd get if we calculated this display name
63     calc_display_name = display_name_from_name(name)
64    
65     # if the calculated name is the same as the passed display name, we don't need to save it
66     if calc_display_name == display_name:
67         # we should remove it from the dict if it's there
68         if name in display_name_saved_dict:
69             del display_name_saved_dict[name]
70             is_dict_modified = True
71     else:
72         # if this doesn't match what we already have in the dict, then let's save it
73         if name not in display_name_saved_dict or display_name != display_name_saved_dict[name]:
74             display_name_saved_dict[name] = display_name
75             is_dict_modified = True
76            
77     if is_dict_modified:
78         try:
79             display_name_file = open(settings.DISPLAY_NAME_DICTIONARY_FILE, mode='w')
80             pickle.dump(display_name_saved_dict, display_name_file, pickle.HIGHEST_PROTOCOL)
81             display_name_file.close()
82         except Exception, e:
83             log.error(u'Error pickling display name dictionary: %s' % smart_unicode(e, errors='replace'))
84    
85 display_name_english_articles = ['the', 'a', 'an']
86 display_name_spanish_articles = ['el', 'la', 'los', 'las', 'un', 'una', 'unos', 'unas']
87 display_name_articles = display_name_english_articles + display_name_spanish_articles
88 def display_name_from_name(name):
89     display_name = ''
90     remaining = name
91    
92     # look for commas in name
93     comma_list = remaining.split(',', 1)
94     while len(comma_list) > 1:
95         # if post comma portion is an article, move it to the front and we're done (no more commas)
96         if comma_list[1].strip().lower() in display_name_articles:
97             if display_name:
98                 display_name = ' '.join((comma_list[1].strip(), display_name.strip(), comma_list[0].strip())).strip()
99             else:
100                 display_name = ' '.join((comma_list[1].strip(), comma_list[0].strip())).strip()
101             return display_name
102         else:
103             # otherwise, we swap the words before and after the comma and then continue checking the rest
104             pre_comma_list = comma_list[0].strip().split(' ')
105             post_comma_list = comma_list[1].strip().split(' ')
106            
107             display_name_list = [display_name.strip()]     
108             display_name_list.extend(pre_comma_list[:-1])   # add all but word before comma
109             display_name_list.append(post_comma_list[0])    # add word after comma
110             display_name_list.extend(pre_comma_list[-1:])   # add word before comma
111             display_name = ' '.join(display_name_list).strip()
112            
113             remaining = ' '.join(post_comma_list[1:]).strip()   # remain is all after comma except first word
114                         
115         comma_list = remaining.split(',', 1)
116        
117     display_name = ' '.join((display_name, comma_list[0].strip())).strip()
118    
119     return display_name
120
121 def display_name_from_saved(name):
122     global display_name_saved_dict
123    
124     ensure_display_name_saved_dict_loaded()
125            
126     # if this name has a previously saved display name, return it
127     if name in display_name_saved_dict:
128         return display_name_saved_dict[name]
129    
130     # nope, return empty string
131     return ''
132
133 def ensure_display_name_saved_dict_loaded():
134     global display_name_saved_dict
135    
136     # if this is our first time through, load dict
137     if display_name_saved_dict == None:
138         try:
139             display_name_file = open(settings.DISPLAY_NAME_DICTIONARY_FILE)
140             display_name_saved_dict = pickle.load(display_name_file)
141             display_name_file.close()
142         except Exception, e:
143             log.error(u'Error unpickling display name dictionary: %s' % smart_unicode(e, errors='replace'))
144             if display_name_saved_dict == None:
145                 display_name_saved_dict = {}
146
147 def make_secret_key():
148     from random import choice
149     secret_key = ''.join([choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)])
150     return secret_key
151
152 ####
153 # security token
154 ####
155 def get_usertoken(user, object_id):
156     usertoken = md5.new()
157     usertoken.update(settings.SECRET_KEY)
158     usertoken.update(smart_str(user.id, errors='ignore'))
159     usertoken.update(user.password)
160     usertoken.update(smart_str(object_id, errors='ignore'))
161     return usertoken.hexdigest()
162 def check_usertoken(user, object_id, usertoken):
163     return usertoken == get_usertoken(user, object_id)
164
165 def splitall(path):
166     allparts = []
167     while 1:
168         parts = os.path.split(path)
169         if parts[0] == path:
170             allparts.insert(0, parts[0])
171             break
172         elif parts[1] == path:
173             allparts.insert(0, parts[1])
174             break
175         else:
176             path = parts[0]
177             allparts.insert(0, parts[1])
178     return allparts
Note: See TracBrowser for help on using the browser.