OSDN Git Service

auto suggest keyword implemented.
[rec10/rec10-git.git] / rec10 / trunk / src / dbMySQL.py
1 #!/usr/bin/python
2 # coding: UTF-8
3 # Rec10 TS Recording Tools
4 # Copyright (C) 2009 Yukikaze
5 import MySQLdb
6 from decimal import Decimal
7 class DB_MySQL:
8     dbname = ""
9     dbhost = ""
10     dbusr = ""
11     dbpasswd = ""
12     dbport = 0
13     def __init__(self, dbname, user, passwd, host="localhost", port=3306):
14         self.dbname = dbname
15         self.dbhost = host
16         self.dbusr = user
17         self.dbpasswd = passwd
18         self.dbport = port
19         try:
20             con = MySQLdb.connect(user=user, passwd=passwd)
21             cur = con.cursor()
22             cur.execute('CREATE DATABASE ' + dbname + " DEFAULT CHARACTER SET utf8")
23             cur.close()
24             con.close()
25         except:
26             ""
27         db = self.connect_db()
28         try:
29             db[1].execute('\
30             CREATE TABLE rectime \
31             (\
32             id INT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY,\
33             type VARCHAR(20),\
34             chtxt VARCHAR(20),\
35             title VARCHAR(100),\
36             btime DATETIME,\
37             etime DATETIME,\
38             deltatime VARCHAR(5),\
39             deltaday VARCHAR(5),\
40             opt VARCHAR(20),\
41             UNIQUE uni (type,chtxt,title,btime,deltaday)\
42             )')
43         except:
44             ""
45         self.close_db(db)
46         self.new_tv("")
47         self.new_ch("")
48         self.new_reclog()
49         self.new_bayeskey()
50     def connect_db(self):
51         """
52         dbへの接続
53         """
54         con = MySQLdb.connect(db=self.dbname, host=self.dbhost, port=self.dbport, user=self.dbusr, passwd=self.dbpasswd, charset="utf8")
55         cur = con.cursor()
56         cur.execute('set names utf8;')
57         return [con, cur]
58     def close_db(self, db):
59         db[1].close()
60         db[0].close()
61     def new_chdata(self):
62         db = self.connect_db()
63         try:
64             db[1].execute('drop table chdata')
65         except:
66             ""
67         try:
68             db[1].execute('\
69             CREATE TABLE chdata \
70             (\
71             bctype VARCHAR(15),\
72             ontv VARCHAR(30) PRIMARY KEY,\
73             chtxt VARCHAR(15),\
74             ch VARCHAR(20),\
75             csch VARCHAR(20),\
76             updatetime DATETIME,\
77             status TINYINT\
78             )')
79         except:
80             ""
81         self.close_db(db)
82     def add_chdata(self, bctype, ontv, chtxt, ch, csch, updatetime):
83         db = self.connect_db()
84         db[1].execute('\
85         INSERT INTO chdata \
86         VALUES (%s,%s,%s,%s,%s,%s,%s)', \
87                       (bctype, ontv, chtxt, ch, csch, updatetime, "1"))
88         self.close_db(db)
89     def select_by_ontv_chdata(self, ontv):
90         db = self.connect_db()
91         dbexe = db[1].execute("\
92         SELECT bctype,ontv,chtxt,ch,csch,updatetime \
93         FROM chdata \
94         WHERE ontv = %s", \
95                               (ontv,))
96         ret = []
97         dls = []
98         if dbexe > 0:
99             dls = db[1].fetchall()
100         self.close_db(db)
101         for dl in dls:
102             r = list(dl)
103             r[5] = r[5].strftime("%Y-%m-%d %H:%M:%S")
104             ret.append(r)
105         return ret
106     def select_by_chtxt_chdata(self, chtxt):
107         db = self.connect_db()
108         dbexe = db[1].execute("\
109         SELECT bctype,ontv,chtxt,ch,csch,updatetime \
110         FROM chdata \
111         WHERE chtxt = %s", \
112                               (chtxt,))
113         ret = []
114         dls = []
115         if dbexe > 0:
116             dls = db[1].fetchall()
117         self.close_db(db)
118         for dl in dls:
119             r = list(dl)
120             r[5] = r[5].strftime("%Y-%m-%d %H:%M:%S")
121             ret.append(r)
122         return ret
123     def select_by_bctype_chdata(self, bctype):
124         db = self.connect_db()
125         dbexe = db[1].execute("\
126         SELECT bctype,ontv,chtxt,ch,csch,updatetime,status \
127         FROM chdata \
128         WHERE bctype = %s", \
129                               (bctype,))
130         ret = []
131         dls = []
132         if dbexe > 0:
133             dls = db[1].fetchall()
134         self.close_db(db)
135         for dl in dls:
136             #print dl
137             r = list(dl)
138             r[5] = r[5].strftime("%Y-%m-%d %H:%M:%S")
139             r[6] = str(r[6])
140             ret.append(r)
141         return ret
142     def select_by_ch_chdata(self, ch):
143         db = self.connect_db()
144         dbexe = db[1].execute("\
145         SELECT \
146         bctype,ontv,chtxt,ch,csch,updatetime \
147         FROM chdata \
148         WHERE ch = %s", \
149                               (ch,))
150         ret = []
151         dls = []
152         if dbexe > 0:
153             dls = db[1].fetchall()
154         self.close_db(db)
155         for dl in dls:
156             r = list(dl)
157             r[5] = r[5].strftime("%Y-%m-%d %H:%M:%S")
158             ret.append(r)
159         return ret
160     def select_all_chdata(self):
161         db = self.connect_db()
162         dbexe = db[1].execute("\
163         SELECT bctype,ontv,chtxt,ch,csch,updatetime \
164         FROM chdata \
165         ")
166         ret = []
167         dls = []
168         if dbexe > 0:
169             dls = db[1].fetchall()
170         self.close_db(db)
171         for dl in dls:
172             r = list(dl)
173             r[5] = r[5].strftime("%Y-%m-%d %H:%M:%S")
174             ret.append(r)
175         return ret
176     def select_get_update_chdata(self, dhour):
177         db = self.connect_db()
178         dbexe = db[1].execute("SELECT bctype,chtxt,status FROM chdata \
179         WHERE \
180         ( \
181         updatetime < DATE_SUB(now(),INTERVAL " + dhour + " HOUR) \
182         AND \
183         status = 1 \
184         ) \
185         OR \
186         status > 1 \
187         ORDER BY status DESC")
188         ret = []
189         #print dbexe
190         if dbexe > 0:
191             ret = db[1].fetchall()
192         self.close_db(db)
193         return ret
194     def update_by_bctype_chdata(self, bctype):
195         db = self.connect_db()
196         db[1].execute("\
197         UPDATE chdata \
198         SET \
199         updatetime=now() , \
200         status = 1 \
201         WHERE bctype = %s", (bctype,))
202         self.close_db(db)
203     def update_by_bctype_and_chtxt_chdata(self, bctype, chtxt):
204         db = self.connect_db()
205         db[1].execute("\
206         UPDATE chdata \
207         SET \
208         updatetime=now() , \
209         status = 1\
210         WHERE bctype = %s AND chtxt = %s", (bctype, chtxt))
211         self.close_db(db)
212     def update_status_by_bctype_chdata(self, bctype, status):
213         db = self.connect_db()
214         db[1].execute("\
215         UPDATE chdata \
216         SET \
217         status=%s \
218         WHERE bctype = %s", \
219                       (status, bctype)\
220                       )
221         self.close_db(db)
222     def add_reclog(self , chtxt="", title="", btime="", etime="", opt="", exp="", longexp="", category=""):
223         db = self.connect_db()
224         db[1].execute('\
225         INSERT IGNORE into reclog \
226         (chtxt,title,btime,etime,opt,exp,longexp,category) \
227         values (%s,%s,%s,%s,%s,%s,%s,%s)', \
228                       ( chtxt, title, btime, etime, opt,exp,longexp,category))
229         ##db.commit()
230         self.close_db(db)
231     def del_reclog(self, title="", chtxt="", btime=""):
232         """
233
234         """
235         db = self.connect_db()
236         db[1].execute("\
237         DELETE FROM reclog \
238         WHERE title = %s AND chtxt = %s AND btime = %s", \
239                       (title, chtxt, btime))
240         #db.commit()
241         self.close_db(db)
242     def new_reclog(self):
243         db = self.connect_db()
244         try:
245             db[1].execute('\
246             CREATE TABLE reclog \
247             (\
248             id INT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY,\
249             chtxt VARCHAR(20),\
250             title VARCHAR(100),\
251             btime DATETIME,\
252             etime DATETIME,\
253             opt VARCHAR(20),\
254             exp VARCHAR(200),\
255             longexp TEXT,\
256             category VARCHAR(100),\
257             UNIQUE uni (chtxt,title,btime,category)\
258             )')
259         except:
260             ""
261         self.close_db(db)
262     def add_rectime(self, type="", chtxt="", title="", btime="", etime="", deltatime="", deltaday="", opt=""):
263         db = self.connect_db()
264         db[1].execute('\
265         INSERT IGNORE into rectime \
266         (type,chtxt,title,btime,etime,deltatime,deltaday,opt) \
267         values (%s,%s,%s,%s,%s,%s,%s,%s)', \
268                       (type, chtxt, title, btime, etime, deltatime, deltaday, opt))
269         ##db.commit()
270         self.close_db(db)
271     def del_rectime(self, type="", title="", chtxt="", btime=""):
272         """
273
274         """
275         db = self.connect_db()
276         db[1].execute("\
277         DELETE FROM rectime \
278         WHERE type = %s AND title = %s AND chtxt = %s AND btime = %s", \
279                       (type, title, chtxt, btime))
280         #db.commit()
281         self.close_db(db)
282     def select_all_rectime(self):
283         db = self.connect_db()
284         recdata = []
285         dbr = db[1].execute("\
286         SELECT type, chtxt, title, btime, etime, deltatime ,deltaday ,opt \
287         FROM rectime")
288         dbl = db[1].fetchall()
289         self.close_db(db)
290         if dbr > 0:
291             for typet, chtxt, title, btime, etime, deltatime, deltaday, opt in dbl:
292                 ret = {}
293                 ret['type'] = typet
294                 ret['chtxt'] = chtxt
295                 ret['title'] = title.encode('utf-8')
296                 btime = btime.strftime("%Y-%m-%d %H:%M:%S")
297                 etime = etime.strftime("%Y-%m-%d %H:%M:%S")
298                 ret['btime'] = btime
299                 ret['etime'] = etime
300                 ret['opt'] = opt
301                 ret['deltatime'] = ""
302                 ret['deltaday'] = ""
303                 if deltatime == None:
304                     deltatime = "3"
305                 if deltaday == None:
306                     deltaday = "7"
307                 if typet == 'key':
308                     ret['deltatime'] = deltatime
309                 elif typet == 'keyevery':
310                     ret['deltatime'] = deltatime
311                     ret['deltaday'] = deltaday
312                 recdata.append(ret)
313         self.close_db(db)
314         return recdata
315     def select_bytime_rectime(self, dminutes):
316         db = self.connect_db()
317         recdatum = []
318         #dbr=db[1].execute("SELECT type, chtxt, title, btime, etime, deltatime ,deltaday ,opt FROM rectime WHERE btime < DATE_SUB(now(),INTERVAL "+dminutes+" MINUTE ) AND btime > DATE_ADD(now(),INTERVAL "+dminutes+" MINUTE )")
319         dbr = db[1].execute("SELECT \
320         type, chtxt, title, btime, etime, deltatime ,deltaday ,opt \
321         FROM rectime \
322         WHERE btime BETWEEN DATE_SUB(now(),INTERVAL " + dminutes + " MINUTE ) AND \
323         DATE_ADD(now(),INTERVAL " + dminutes + " MINUTE )")
324         dbl = db[1].fetchall()
325         self.close_db(db)
326         #print dbl
327         if dbr > 0:
328             for typet, chtxt, title, btime, etime, deltatime, deltaday, opt in dbl:
329                 ret = {}
330                 ret['type'] = typet
331                 ret['chtxt'] = chtxt
332                 ret['title'] = title.encode('utf-8')
333                 btime = btime.strftime("%Y-%m-%d %H:%M:%S")
334                 etime = etime.strftime("%Y-%m-%d %H:%M:%S")
335                 ret['btime'] = btime
336                 ret['etime'] = etime
337                 ret['opt'] = opt
338                 if deltatime == None or deltatime == "":
339                     deltatime = "3"
340                 if deltaday == None or deltaday == "":
341                     deltaday = "7"
342                 if typet == 'key':
343                     ret['deltatime'] = deltatime
344                 elif typet == 'keyevery':
345                     ret['deltatime'] = deltatime
346                     ret['deltaday'] = deltaday
347                 recdatum.append(ret)
348         return recdatum
349     def delete_old_rectime(self, dhour):
350         db = self.connect_db()
351         db[1].execute("\
352         DELETE FROM rectime \
353         WHERE \
354         btime < DATE_SUB(now(),INTERVAL " + dhour + " HOUR )")
355         #db.commit()
356         self.close_db(db)
357     def new_status(self):
358         db = self.connect_db()
359         try:
360             db[1].execute("\
361             CREATE TABLE status \
362             (\
363             ts2avi TINYINT DEFAULT 0,\
364             terec TINYINT DEFAULT 0,\
365             bscsrec TINYINT DEFAULT 0,\
366             b252ts TINYINT DEFAULT 0\
367             )")
368             db[1].execute("INSERT IGNORE into status VALUE (0,0,0,0)")
369         except:
370             ""
371
372         self.close_db(db)
373     def select_all_status(self):
374         db = self.connect_db()
375         dbexe = db[1].execute("\
376         SELECT ts2avi,terec,bscsrec,b252ts \
377         FROM status \
378         ")
379         ret = []
380         dls = []
381         if dbexe > 0:
382             dls = db[1].fetchall()
383         self.close_db(db)
384         for dl in dls:
385             r = list(dl)
386             r[0]=str(r[0])
387             r[1]=str(r[1])
388             r[2]=str(r[2])
389             r[3]=str(r[3])
390             ret.append(r)
391         return ret
392         self.close_db(db)
393     def change_ts2avi_status(self,i):
394         """
395         statuをiだけ増減する
396         iはint
397         """
398         db = self.connect_db()
399         db[1].execute("\
400         UPDATE status SET ts2avi=ts2avi+%s",i)
401         self.close_db(db)
402     def change_terec_status(self,i):
403         """
404         statuをiだけ増減する
405         iはint
406         """
407         db = self.connect_db()
408         db[1].execute("\
409         UPDATE status SET terec=terec+%s",i)
410         self.close_db(db)
411     def change_bscsrec_status(self,i):
412         """
413         statuをiだけ増減する
414         iはint
415         """
416         db = self.connect_db()
417         db[1].execute("\
418         UPDATE status SET bscsrec=bscsrec+%s",i)
419         self.close_db(db)
420     def change_b252ts_status(self,i):
421         """
422         statuをiだけ増減する
423         iはint
424         """
425         db = self.connect_db()
426         db[1].execute("\
427         UPDATE status SET b252ts=b252ts+%s",i)
428         self.close_db(db)
429     def new_tv(self, bctype):
430         db = self.connect_db()
431         try:
432             db[1].execute("\
433             DELETE FROM tv \
434             WHERE bctype = %s", \
435                           (bctype,))
436         except:
437             ""
438         try:
439             db[1].execute("\
440             CREATE TABLE tv \
441             (\
442             bctype VARCHAR(20),\
443             channel VARCHAR(100) NOT NULL,\
444             start VARCHAR(30),\
445             stop  VARCHAR(30),\
446             title VARCHAR(100),\
447             exp VARCHAR(200),\
448             longexp TEXT,\
449             category VARCHAR(100),\
450             UNIQUE unitv(bctype,channel,start,stop,title)\
451             )")
452         except:
453             ""
454         #db.commit()
455         self.close_db(db)
456     def add_tv(self, bctype, channel, start, stop, title, desc,longdesc, category):
457         db = self.connect_db()
458         db[1].execute('\
459         INSERT IGNORE INTO tv \
460         VALUES (%s,%s,%s,%s,%s,%s,%s,%s)', \
461                       (bctype, channel, start, stop, title, desc,longdesc,category))
462         #db.commit()
463         self.close_db(db)
464     def add_multi_tv(self, tvlists):
465         """
466         tvlists is (bctype,channel,start,stop,title,desc,longdesc,category) lists.
467         """
468         db = self.connect_db()
469         db[1].executemany('\
470         INSERT IGNORE INTO tv \
471         (bctype,channel,start,stop,title,exp,longexp,category) \
472         values(%s,%s,%s,%s,%s,%s,%s,%s)', \
473                           tvlists)
474         #db.commit()
475         self.close_db(db)
476     def select_by_time_ngram_tv(self, btime, etime, chtxt):
477         db = self.connect_db()
478         dbexe = "\
479         SELECT \
480         chdata.chtxt,title,start,stop,exp,longexp,category \
481         FROM tv \
482         INNER JOIN chdata \
483         WHERE chdata.ontv=tv.channel \
484         AND \
485         start >= %s \
486         AND \
487         start <= %s \
488         AND \
489         chdata.chtxt=%s"
490         dbcmd = db[1].execute(dbexe, (btime, etime, chtxt))
491         retall = []
492         if dbcmd > 0:
493             retall = db[1].fetchall()
494         self.close_db(db)
495         return retall
496     def select_by_time_auto_suggest_tv(self,keyword,btime,etime,chtxt):
497         db = self.connect_db()
498         dbexe = "\
499         SELECT \
500         chdata.chtxt,title,start,stop,exp,longexp,category \
501         FROM tv \
502         INNER JOIN chdata \
503         WHERE chdata.ontv=tv.channel \
504         AND \
505         start >= %s \
506         AND \
507         start <= %s \
508         AND \
509         ( \
510         ( title LIKE \'%%"+keyword+"%%\' ) \
511         OR \
512         ( exp LIKE \'%%"+keyword+"%%\' ) \
513         OR \
514         ( longexp LIKE \'%%"+keyword+"%%\' ) \
515         )"
516         dbcmd = db[1].execute(dbexe,(btime, etime))
517         retall = []
518         if dbcmd > 0:
519             retall = db[1].fetchall()
520         self.close_db(db)
521         return retall
522     def new_ch(self, bctype):
523         db = self.connect_db()
524         try:
525             db[1].execute("DELETE FROM ch WHERE bctype = %s", (bctype,))
526         except:
527             ""
528         try:
529             db[1].execute('\
530             CREATE TABLE ch \
531             (\
532             bctype VARCHAR(20),\
533             channel VARCHAR(20) NOT NULL,\
534             display VARCHAR(100),\
535             UNIQUE unich(bctype,channel)\
536             )')
537         except:
538             ""
539         #db.commit()
540         self.close_db(db)
541     def add_ch(self, bctype, channel, display):
542         db = self.connect_db()
543         db[1].execute('INSERT IGNORE INTO ch VALUES (%s,%s,%s)', (bctype, channel, display))
544         #db.commit()
545         self.close_db(db)
546     def add_multi_ch(self, chlists):
547         """
548         chlists is (bctype,channel,display) lists
549         """
550         db = self.connect_db()
551         db[1].executemany('INSERT IGNORE INTO ch VALUES (%s,%s,%s)', chlists)
552         self.close_db(db)
553     def new_bayeskey(self):
554         db = self.connect_db()
555         try:
556             db[1].execute('CREATE TABLE bayeskey \
557             (\
558             keychar VARCHAR(10),\
559             chtxt VARCHAR(20),\
560             ratio_rec DECIMAL(32,14),\
561             ratio_all DECIMAL(32,14),\
562             UNIQUE unibayeskey(keychar,chtxt)\
563             )')
564             db[1].execute('CREATE INDEX keycharindex ON bayeskey(keychar)')
565         except:
566             ""
567         self.close_db(db)
568
569     def add_bayeskey(self,key,chtxt,ratio_rec,ratio_all):
570         db = self.connect_db()
571         ratio_rec=str(ratio_rec)
572         ratio_all=str(ratio_all)
573         db[1].execute('\
574         INSERT IGNORE INTO bayeskey \
575         (keychar,chtxt,ratio_rec,ratio_all) \
576         values (%s,%s,%s,%s)',\
577         (key,chtxt,ratio_rec,ratio_all))
578         self.close_db(db)
579     def add_num_bayeskey(self,chtxt,add_rec_num,add_all_num):
580         db = self.connect_db()
581         add_rec_num=str(add_rec_num)
582         add_all_num=str(add_all_num)
583         db[1].execute("\
584         UPDATE bayeskey SET ratio_rec=ratio_rec+%s,ratio_all=ratio_all+%s WHERE keychar=\"NUM\" AND chtxt=%s",\
585         (add_rec_num,add_all_num,chtxt))
586         self.close_db(db)
587     def change_bayeskey(self,key,chtxt,new_ratio_rec,new_ratio_all):
588         """
589         """
590         db = self.connect_db()
591         db[1].execute("\
592         UPDATE bayeskey SET ratio_rec=%s,ratio_all=%s WHERE keychar=%s AND chtxt=%s",(str(new_ratio_rec),str(new_ratio_all),key,chtxt)\
593         )
594         self.close_db(db)
595     def change_ratio_all_reduce_bayeskey(self,chtxt,beforenum,newnum):
596         beforenum=str(beforenum)
597         newnum=str(newnum)
598         db = self.connect_db()
599         db[1].execute("\
600         UPDATE bayeskey SET ratio_all=ratio_all*%s/(%s+%s) WHERE chtxt=%s AND NOT (keychar=\"NUM\")",(beforenum,newnum,beforenum,chtxt)\
601         )
602         self.close_db(db)
603     def change_ratio_all_bayeskey(self,key,chtxt,beforenum,addnum):
604         db = self.connect_db()
605         beforenumf=beforenum
606         beforenum=str(beforenum)
607         #addnum=str(addnum)
608         #db[1].execute("\
609         #UPDATE bayeskey SET ratio_all=(ratio_all*%s+%s)/%s WHERE chtxt=%s AND keychar=%s",\
610         #(beforenum,addnum,beforenum,chtxt,key)\
611         #)
612         db[1].execute("INSERT INTO bayeskey (keychar,chtxt,ratio_rec,ratio_all) \
613         VALUES (%s,%s,%s,%s)\
614         ON DUPLICATE KEY UPDATE \
615         ratio_all=(ratio_all*%s+%s)/%s",(key,chtxt,"0",str(Decimal(addnum)/beforenumf),beforenum,chtxt,key))
616         self.close_db(db)
617     def change_many_ratio_all_bayeskey(self,chtxt,beforenum,list):
618         """
619         list={key:addnum}のリスト
620         """
621         retlist=[]
622         beforenumf=beforenum
623         beforenum=str(beforenum)
624         db = self.connect_db()
625         for i,j in list.items():
626             retl=(i,chtxt,"0",str(Decimal(j)/beforenumf),beforenum,str(j),beforenum)
627             db[1].execute("INSERT INTO bayeskey (keychar,chtxt,ratio_rec,ratio_all) \
628             VALUES (%s,%s,%s,%s)\
629             ON DUPLICATE KEY UPDATE \
630             ratio_all=(ratio_all*%s+%s)/%s",retl)
631         self.close_db(db)
632     def change_ratio_rec_bayeskey(self,key,chtxt,beforenum,addnum):
633         db = self.connect_db()
634         beforenum=str(beforenum)
635         addnum=str(addnum)
636         db[1].execute("\
637         UPDATE bayeskey SET ratio_rec=(ratio_rec*%s+%s)/%s WHERE chtxt=%s AND keychar=%s",\
638         (beforenum,addnum,beforenum,chtxt,key)\
639         )
640         self.close_db(db)
641     def select_by_key_bayeskey(self,key,chtxt):
642         db = self.connect_db()
643         dbexe = db[1].execute("\
644         SELECT keychar,chtxt,ratio_rec,ratio_all \
645         FROM bayeskey \
646         WHERE keychar = %s AND chtxt = %s", \
647                               (key,chtxt))
648         dls = []
649         if dbexe > 0:
650             dls = db[1].fetchall()
651         self.close_db(db)
652         if len(dls)>0:
653             return dls[0]
654         else:
655             return dls