Child: [48f3e9] (diff)

Download this file

uprcltags.py    319 lines (282 with data), 10.4 kB

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
from __future__ import print_function
import sys
import sqlite3
from timeit import default_timer as timer
from uprclutils import *
sqconn = sqlite3.connect(':memory:')
#sqconn = sqlite3.connect('/tmp/tracks.sqlite')
# TBD All Artists, Orchestra, Group
#
# Maybe we'd actually need a 3rd value for the recoll field name, but
# it can be the same for the currently relevant fields.
tables = {'Artist' : 'artist',
'Date' : 'date',
'Genre' : 'genre',
'All Artists' : 'allartists',
'Composer' : 'composer',
'Conductor' : 'conductor',
'Orchestra' : 'orchestra',
'Group' : 'grouptb',
'Comment' : 'comment'
}
def createsqdb(conn):
c = conn.cursor()
try:
c.execute('''DROP TABLE albums''')
c.execute('''DROP TABLE tracks''')
except:
pass
c.execute(
'''CREATE TABLE albums
(albid INTEGER PRIMARY KEY, albtitle TEXT, albfolder TEXT)''')
tracksstmt = '''CREATE TABLE tracks
(docidx INT, albid INT, trackno INT, title TEXT'''
for tt,tb in tables.iteritems():
try:
c.execute('DROP TABLE ' + tb)
except:
pass
stmt = 'CREATE TABLE ' + tb + \
' (' + tb + '_id' + ' INTEGER PRIMARY KEY, value TEXT)'
c.execute(stmt)
tracksstmt += ',' + tb + '_id INT'
tracksstmt += ')'
c.execute(tracksstmt)
def auxtableinsert(sqconn, tb, value):
c = sqconn.cursor()
col = tb + '_id'
stmt = 'SELECT ' + col + ' FROM ' + tb + ' WHERE value = ?'
c.execute(stmt, (value,))
r = c.fetchone()
if r:
rowid = r[0]
else:
stmt = 'INSERT INTO ' + tb + '(value) VALUES(?)'
c.execute(stmt, (value,))
rowid = c.lastrowid
return rowid
g_alldocs = []
def recolltosql(docs):
global g_alldocs
g_alldocs = docs
createsqdb(sqconn)
c = sqconn.cursor()
maxcnt = 0
totcnt = 0
for docidx in range(len(docs)):
doc = docs[docidx]
totcnt += 1
album = getattr(doc, 'album', None)
if not album:
if doc.mtype != 'inode/directory' and \
doc.mtype != 'image/jpeg':
pass
#uplog("No album: mtype %s title %s" % (doc.mtype, doc.url))
continue
folder = docfolder(doc).decode('utf-8', errors = 'replace')
try:
l= doc.tracknumber.split('/')
trackno = int(l[0])
except:
trackno = 0
# Create album record if needed. There is probably a
# single-statement syntax for this
c.execute('''SELECT albid FROM albums
WHERE albtitle = ? AND albfolder = ?''', (album, folder))
r = c.fetchone()
if r:
albid = r[0]
else:
c.execute('''INSERT INTO albums(albtitle, albfolder)
VALUES (?,?)''', (album, folder))
albid = c.lastrowid
columns = 'docidx,albid,trackno,title'
values = [docidx, albid, trackno, doc.title]
placehold = '?,?,?,?'
for tt,tb in tables.iteritems():
value = getattr(doc, tb, None)
if not value:
continue
rowid = auxtableinsert(sqconn, tb, value)
columns += ',' + tb + '_id'
values.append(rowid)
placehold += ',?'
stmt = 'INSERT INTO tracks(' + columns + ') VALUES(' + placehold + ')'
c.execute(stmt, values)
#uplog(doc.title)
sqconn.commit()
uplog("recolltosql: processed %d docs" % totcnt)
def rootentries(pid):
entries = [rcldirentry(pid + 'albums', pid, 'albums'),
rcldirentry(pid + 'items', pid, 'items')]
for tt,tb in tables.iteritems():
entries.append(rcldirentry(pid + '=' + tt , pid, tt))
return entries
g_myprefix = '0$uprcl$'
def colid(col):
return col + '_id'
def analyzesubtree(sqconn, recs):
docids = ','.join([str(r[0]) for r in recs])
uplog("analyzesubtree, docids %s" % docids)
c1 = sqconn.cursor()
tags = []
for tt,tb in tables.iteritems():
stmt = 'SELECT COUNT(DISTINCT ' + colid(tb) + \
') FROM tracks WHERE docidx IN (' + docids + ')'
uplog("analyzesubtree: executing: <%s>" % stmt)
c1.execute(stmt)
for r in c1:
cnt = r[0]
uplog("Found %d distinct values for %s" % (cnt, tb))
if cnt > 1:
tags.append(tt)
return tags
def seltagsbrowse(pid, qpath, flag, httphp, pathprefix):
uplog("seltagsbrowse. qpath %s" % qpath)
qlen = len(qpath)
selwhat = ''
selwhere = ''
values = []
i = 0
while i < qlen:
elt = qpath[i]
if elt.startswith('='):
col = tables[elt[1:]]
selwhere = selwhere + ' AND ' if selwhere else ' WHERE '
if i == qlen - 1:
# We want to display all unique values for the column
# artist.artist_id, artist.value
selwhat = col + '.' + col + '_id, ' + col + '.value'
# tracks.artist_id = artist.artist_id
selwhere += 'tracks.'+ col + '_id = ' + col + '.' + col + '_id'
else:
# Look at the value specified for the =xx column
selwhat = 'tracks.docidx'
selwhere += 'tracks.' + col + '_id = ?'
i += 1
values.append(int(qpath[i]))
i += 1
c = sqconn.cursor()
#for r in c:
# uplog("selres: %s" % r)
entries = []
if selwhat == 'tracks.docidx':
# SELECT docidx FROM tracks
# WHERE col1_id = ? AND col2_id = ?
stmt = "SELECT docidx FROM tracks %s" % selwhere
uplog("seltagsbrowse: executing <%s> values %s" % (stmt, values))
c.execute(stmt, values)
recs = c.fetchall()
subqs = analyzesubtree(sqconn, recs)
if not subqs:
for r in recs:
docidx = r[0]
id = pid + '$*i' + str(docidx)
entries.append(rcldoctoentry(id, pid, httphp, pathprefix,
g_alldocs[docidx]))
else:
for tt in subqs:
id = pid + '$=' + tt
entries.append(rcldirentry(id, pid, tt))
else:
# SELECT col.value FROM tracks, col
# WHERE tracks.col_id = col.col_id
# GROUP BY tracks.col_id
# ORDER BY col.value
stmt = "SELECT " + selwhat + " FROM tracks, " + col + \
selwhere + \
" GROUP BY tracks." + col + '_id' + \
" ORDER BY value"
uplog("seltagsbrowse: executing <%s> values %s" % (stmt, values))
c.execute(stmt, values)
for r in c:
id = pid + '$' + str(r[0])
entries.append(rcldirentry(id, pid, r[1]))
return entries
def browse(pid, flag, httphp, pathprefix):
idpath = pid.replace(g_myprefix, '', 1)
entries = []
uplog('tags:browse: idpath <%s>' % idpath)
qpath = idpath.split('$')
c = sqconn.cursor()
if idpath.startswith('items'):
c.execute('''SELECT docidx FROM tracks ORDER BY title''')
for r in c:
docidx = r[0]
id = pid + '$*i' + str(docidx)
entries.append(rcldoctoentry(id, pid, httphp, pathprefix,
g_alldocs[docidx]))
elif idpath.startswith('albums'):
if len(qpath) == 1:
c.execute('''SELECT albid, albtitle FROM albums
ORDER BY albtitle''')
for r in c:
id = pid + '$*' + str(r[0])
entries.append(rcldirentry(id, pid, r[1]))
elif len(qpath) == 2:
e1 = qpath[1]
if not e1.startswith("*"):
raise Exception("Bad album id in albums tree. Pth: %s" %idpath)
albid = int(e1[1:])
c.execute('''SELECT docidx FROM tracks WHERE albid = ? ORDER BY
trackno''', (albid,))
for r in c:
docidx = r[0]
id = pid + '$*i' + str(docidx)
entries.append(rcldoctoentry(id, pid, httphp, pathprefix,
g_alldocs[docidx]))
else:
raise Exception("Bad path in album tree (too deep): <%s>"%idpath)
elif idpath.startswith('='):
entries = seltagsbrowse(pid, qpath, flag, httphp, pathprefix)
else:
raise Exception('Bad path in tags tree (start>):<%s>'%idpath)
return entries
def misctries():
c = sqconn.cursor()
c.execute('''SELECT COUNT(*) FROM tracks''')
uplog("Count(*) %d" % (c.fetchone()[0],))
#for row in c.execute('''SELECT album
# FROM tracks where artist LIKE "%Gould%"
# GROUP BY album'''):
# uplog("%s" % (row,))
# For some strange reason it appears that GROUP BY is faster than SELECT
# DISTINCT
stmt = '''SELECT album FROM tracks GROUP BY album ORDER BY album'''
start = timer()
for row in c.execute(stmt):
#uplog("%s" % (row[0].encode('UTF-8')))
pass
end = timer()
uplog("Select took %.2f Seconds" % (end - start))
for row in c.execute('''SELECT COUNT(DISTINCT album) from tracks'''):
uplog("Album count %d" % row[0])
if __name__ == '__main__':
confdir = "/home/dockes/.recoll-mp3"
from recoll import recoll
def fetchalldocs(confdir):
allthedocs = []
rcldb = recoll.connect(confdir=confdir)
rclq = rcldb.query()
rclq.execute("mime:*", stemming=0)
uplog("Estimated alldocs query results: %d" % (rclq.rowcount))
maxcnt = 1000
totcnt = 0
while True:
docs = rclq.fetchmany()
for doc in docs:
allthedocs.append(doc)
totcnt += 1
if (maxcnt > 0 and totcnt >= maxcnt) or \
len(docs) != rclq.arraysize:
break
uplog("Retrieved %d docs" % (totcnt,))
return allthedocs
start = timer()
docs = fetchalldocs(confdir)
end = timer()
uplog("Recoll extract took %.2f Seconds" % (end - start))
start = timer()
recolltosql(docs)
end = timer()
uplog("SQL db create took %.2f Seconds" % (end - start))