PageRenderTime 45ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/python/engine/PinYin/ZhengJuDB.py

http://scim-python.googlecode.com/
Python | 231 lines | 205 code | 1 blank | 25 comment | 0 complexity | c91691f4511c7b2c20e1e376199f185d MD5 | raw file
  1. # -*- coding: utf-8 -*-
  2. # vim: set noet ts=4:
  3. #
  4. # scim-python
  5. #
  6. # Copyright (c) 2007-2008 Yu Fan <yufanyufan@gmail.com>
  7. #
  8. #
  9. # This library is free software; you can redistribute it and/or
  10. # modify it under the terms of the GNU Lesser General Public
  11. # License as published by the Free Software Foundation; either
  12. # version 2 of the License, or (at your option) any later version.
  13. #
  14. # This library is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU Lesser General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU Lesser General Public
  20. # License along with this program; if not, write to the
  21. # Free Software Foundation, Inc., 59 Temple Place, Suite 330,
  22. # Boston, MA 02111-1307 USA
  23. #
  24. # $Id: $
  25. #
  26. import os
  27. import os.path as path
  28. import sys
  29. import sqlite3 as sqlite
  30. import traceback
  31. import PYDict
  32. from PYSQLiteDB import PYSQLiteDB, Cache
  33. import re
  34. import time
  35. (YLEN, Y0, Y1, Y2, Y3, YX, S0, S1, S2, S3, PHRASE, FREQ, USER_FREQ) = range (0, 13)
  36. USER_WORD = 119771
  37. USER_PHRASE = 119769
  38. class ZhengJuDB (PYSQLiteDB):
  39. """phrase database that contains all phrases and phrases' pinyin"""
  40. def __init__ (self, config):
  41. PYSQLiteDB.__init__ (self, user_db = "user_zhengju.db")
  42. #~ print "db init"
  43. #~ Init caches
  44. self.select_cache = Cache ()
  45. self.select_all_cache = Cache()
  46. self.longest_length_cache = Cache()
  47. self.load_config(config)
  48. def load_config(self, config):
  49. self.large_charset = config.read ("/IMEngine/Python/ZhengJu/LargeCharset", False)
  50. def clear_cache(self):
  51. #~ pass
  52. self.select_cache.clear()
  53. self.select_all_cache.clear()
  54. self.longest_length_cache.clear()
  55. def add_phrase (self, pinyin, freq, database = "user_db", user_freq = 32):
  56. """ add phrase to database"""
  57. sqlstring = """INSERT INTO %s.py_phrase (ylen, y0, y1, y2, y3, yx, s0, s1, s2, s3, phrase, freq, user_freq)
  58. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"""
  59. phrase = u"".join([i.char for i in pinyin])
  60. #~ print "commit", phrase
  61. record = [None, None, None, None, None, None, None, None, None, None, None, 0, None]
  62. record [YLEN] = len (pinyin)
  63. i = 0
  64. for p in pinyin[:4]:
  65. record[Y0 + i] = p.get_pinyin_id ()
  66. record[S0 + i] = p.get_sheng_mu_id ()
  67. i += 1
  68. if len(pinyin) > 4:
  69. record[YX] = "'".join (map (str, pinyin[4:]))
  70. record[PHRASE] = phrase
  71. record[FREQ]= freq
  72. record[USER_FREQ] = user_freq
  73. self.db.execute (sqlstring % (database, ), record)
  74. self.db.commit ()
  75. del self.select_cache[u"'".join (map (str, pinyin))]
  76. def clean_useless_phrase (self):
  77. "Remove phrase from user database"
  78. #~ print "remove", record[6]
  79. sql = "DELETE FROM user_db.py_phrase WHERE user_freq = 0"
  80. self.db.execute (sql)
  81. self.db.commit ()
  82. self.clear_cache()
  83. def remove_phrase (self, record, database = "user_db"):
  84. "Remove phrase from user database"
  85. #~ print "remove", record[6]
  86. sql = "DELETE FROM user_db.py_phrase WHERE ylen = ? AND y0 = ? AND phrase = ?"
  87. self.db.execute (sql, (record[YLEN], record[Y0], record[6]))
  88. self.db.commit ()
  89. self.clear_cache()
  90. def build_pinyin_condition(self, pys, length = None):
  91. sql_conditions = []
  92. i = 0
  93. for py in pys[:4]:
  94. sql_conditions.append ("s%d = %d" % (i, py.get_sheng_mu_id ()))
  95. if py.is_complete ():
  96. sql_conditions.append ("y%d = %d" % (i, py.get_pinyin_id ()))
  97. i += 1
  98. if len (pys) > 4:
  99. pp = lambda (x): x.get_pinyin() if x.is_complete () else x.get_pinyin() + "%"
  100. pattern = "'".join (map (pp, pys[4:]))
  101. if length == None:
  102. sql_conditions.append ("yx LIKE \"" + pattern + "%\"")
  103. else:
  104. sql_conditions.append ("yx LIKE \"" + pattern + "\"")
  105. return sql_conditions
  106. def get_longest_phrase_length(self , pylist):
  107. """return the longest word starting with first two pinyin of pylist"""
  108. if len(pylist)<5:
  109. return len(pylist)
  110. pys=pylist[:4]
  111. pinyin_string = u"'".join (map (str, pys))
  112. result = self.longest_length_cache [pinyin_string]
  113. if result != None:
  114. return result
  115. candidates = self.select_words_by_pinyin_list_all(pys)
  116. if candidates:
  117. result = max([i[YLEN] for i in candidates])
  118. else:
  119. result = 3
  120. #~ tables_union = """( SELECT ylen FROM main.py_phrase WHERE %(conditions)s UNION ALL
  121. #~ SELECT ylen FROM user_db.py_phrase WHERE %(conditions)s )"""
  122. #~ sql_conditions = self.build_pinyin_condition(pys)
  123. #~ tables_union = tables_union % { "conditions" : " AND ".join (sql_conditions) }
  124. #~ sql_string = "SELECT Max(ylen) FROM " + tables_union + " ;"
  125. #~ print "start", time.time()
  126. #~ result = list (self.db.execute (sql_string).fetchall ())
  127. #~ if not result[0][0]:
  128. #~ result = 1
  129. #~ else:
  130. #~ result = result[0][0]
  131. self.longest_length_cache[pinyin_string] = result
  132. #~ print "longest",pinyin_string, result, time.time()
  133. if result > len(pylist):
  134. return len(pylist)
  135. return result
  136. def select_words_by_phrase (self, pys, database = None):
  137. return self.select_words_by_pinyin(pys, phrase=u"".join([i.char for i in pys]),database=database)
  138. def select_phrase (self, phrase, database = None):
  139. sql_conditions = "ylen =%d AND phrase = \"%s\"" % (len(phrase), phrase)
  140. if database:
  141. tables_union = "(SELECT ylen, y0, y1, y2, y3, yx, phrase, freq, user_freq FROM " + database+ ".py_phrase WHERE %(conditions)s) "
  142. else:
  143. tables_union = """ (SELECT ylen, y0, y1, y2, y3, yx, phrase, freq, user_freq FROM user_db.py_phrase WHERE %(conditions)s UNION ALL
  144. SELECT ylen, y0, y1, y2, y3, yx, phrase, freq, user_freq FROM main.py_phrase WHERE %(conditions)s) """
  145. sql_prefix = "SELECT * FROM " + tables_union % { "conditions" : sql_conditions }
  146. sql_string = sql_prefix + " GROUP BY phrase ORDER BY freq;"
  147. result = list (self.db.execute (sql_string).fetchall ())
  148. return result
  149. def select_words_by_pinyin (self, pys, length=None, phrase=None, database = None):
  150. sql_conditions = []
  151. if length:
  152. sql_conditions = ["ylen = %d" % length ]
  153. if not self.large_charset:
  154. sql_conditions.append("freq > 0")
  155. if phrase:
  156. sql_conditions.append("phrase = \"%s" % phrase +"\"")
  157. if database:
  158. tables_union = "( SELECT ylen, y0, y1, y2, y3, yx, phrase, freq, user_freq FROM " + database+ ".py_phrase WHERE %(conditions)s )"
  159. else:
  160. tables_union = """( SELECT ylen, y0, y1, y2, y3, yx, phrase, freq, user_freq FROM user_db.py_phrase WHERE %(conditions)s UNION ALL
  161. SELECT ylen, y0, y1, y2, y3, yx, phrase, freq, user_freq FROM main.py_phrase WHERE %(conditions)s )"""
  162. sql_conditions.extend (self.build_pinyin_condition (pys, length))
  163. tables_union = tables_union % { "conditions" : " AND ".join (sql_conditions) }
  164. sql_prefix = "SELECT ylen, y0, y1, y2, y3, yx, phrase, MAX(freq*ifnull(user_freq,1)) as adj_freq FROM " + tables_union
  165. sql_string = sql_prefix + " GROUP BY phrase ORDER BY adj_freq DESC;"
  166. #~ print "by pinyin"
  167. result = list (self.db.execute (sql_string).fetchall ())
  168. #~ print result
  169. return result
  170. def select_words_by_pinyin_list_all (self, pys, length = None):
  171. """select words from database by list that contains PYDict.PinYinWord objects"""
  172. pinyin_string = u"'".join (map (str, pys))
  173. result = self.select_all_cache [pinyin_string]
  174. if result == None:
  175. result = self.select_words_by_pinyin(pys)
  176. self.select_all_cache[pinyin_string] = result
  177. #~ print "list_all",pinyin_string
  178. return result
  179. def remove_all_user_words(self):
  180. sql = "DELETE FROM user_db.py_phrase WHERE freq = " + str(USER_WORD)
  181. self.db.execute (sql)
  182. self.db.commit ()
  183. def remove_all_user_phrase(self):
  184. sql = "DELETE FROM user_db.py_phrase WHERE freq = " + str(USER_PHRASE)
  185. self.db.execute (sql)
  186. self.db.commit ()
  187. def remvoe_all_user_freq(self):
  188. sql = "DELETE FROM user_db.py_phrase WHERE freq != %d and freq != %d" (USER_PHRASE, USER_WORD)
  189. self.db.execute (sql)
  190. self.db.commit ()
  191. def select_words_by_pinyin_list (self, pys, database = None):
  192. """select words from database by list that contains PYDict.PinYinWord objects"""
  193. pinyin_string = u"'".join (map (str, pys))
  194. result = self.select_cache [pinyin_string]
  195. if result == None:
  196. result = self.select_words_by_pinyin(pys, len(pys), database)
  197. self.select_cache[pinyin_string] = result
  198. #~ print "list",pinyin_string
  199. return result
  200. def adjust_phrase_freq (self, pylist):
  201. """this function adjusts frequence of phrase in user database."""
  202. p = self.select_words_by_phrase(pylist,"user_db")
  203. if len(p)>0:
  204. q = self.select_words_by_pinyin(pylist, length = len(pylist), database = "main")
  205. if len(q) == 0 or p[0][7] > q[0][7]:
  206. sql_conditions = ["ylen = %d" % len(pylist) ]
  207. sql_conditions.extend (self.build_pinyin_condition (pylist, len(pylist)))
  208. sql_conditions.append ( "phrase != ?" )
  209. sql_conditions.append ( "user_freq * freq > " + str(p[0][7]) )
  210. sql = "UPDATE user_db.py_phrase SET user_freq = user_freq / 2 WHERE %(conditions)s" % { "conditions" : " AND ".join (sql_conditions) }
  211. self.db.execute (sql, [u"".join([i.char for i in pylist])])
  212. self.db.commit ()
  213. sql = "UPDATE user_db.py_phrase SET user_freq = user_freq * 2 WHERE phrase = ?"
  214. self.db.execute (sql,[u"".join([i.char for i in pylist])])
  215. self.db.commit ()
  216. else:
  217. p = self.select_words_by_phrase(pylist,"main")
  218. self.add_phrase(pylist,p[0][7],user_freq = 10)