You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

174 lines
5.4KB

  1. #!/usr/bin/python
  2. #-*- coding: utf-8 -*-
  3. #
  4. # KCnrtl is a simple and messy KDE graphical client to access
  5. # the CNRTL linguistic resources
  6. #
  7. # Copyright (C) 2012 Bogdan Cordier
  8. #
  9. # This program is free software: you can redistribute it and/or modify
  10. # it under the terms of the GNU General Public License as published by
  11. # the Free Software Foundation, either version 3 of the License, or
  12. # (at your option) any later version.
  13. #
  14. # This program 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 General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License
  20. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  21. import sys
  22. import httplib2
  23. from bs4 import BeautifulSoup
  24. from PyQt4.QtCore import *
  25. from PyQt4.QtGui import *
  26. from gui.Ui_kcnrtl import Ui_MainWindow
  27. import re
  28. import shutil
  29. def main():
  30. app = QApplication(sys.argv)
  31. myapp = Main()
  32. myapp.show()
  33. sys.exit(app.exec_())
  34. class Main(QMainWindow):
  35. def __init__(self, parent=None):
  36. super(QWidget, self).__init__(parent)
  37. #QWidget.__init__(self, parent)
  38. self.ui = Ui_MainWindow()
  39. self.ui.setupUi(self)
  40. self.ui.lineEdit.selectAll()
  41. self.ui.lineEdit.setFocus()
  42. self.ui.comboBox.setCurrentIndex(0)
  43. self.ui.checkBox.setChecked(False)
  44. self.clipboard = QApplication.clipboard()
  45. self.ui.lineEdit.returnPressed.connect(self.updateUi)
  46. self.ui.comboBox.activated.connect(self.changeCombo)
  47. self.ui.webView.settings().setUserStyleSheetUrl(
  48. QUrl.fromLocalFile(":/lexi.css"))
  49. self.ui.listView.clicked.connect(self.rowClicked)
  50. self.clipboard.dataChanged.connect(self.autoGetFromClipboard)
  51. def updateUi(self):
  52. try:
  53. # Check if input text is a word
  54. if len(unicode(self.ui.lineEdit.text()).split()) <= 1:
  55. self.typed = unicode(self.ui.lineEdit.text())
  56. self.getLexi(self.typed)
  57. self.ui.comboBox.clear()
  58. self.ui.comboBox.addItems(self.lexiForm())
  59. self.lexiContent()
  60. self.ui.listView.setModel(self.getSynoAnto("synonymie"))
  61. self.ui.listView_2.setModel(self.getSynoAnto("antonymie"))
  62. else:
  63. self.ui.lineEdit.setText("Veuillez entrer UN mot")
  64. except:
  65. self.ui.lineEdit.setText("Veuillez entrer un mot")
  66. # Copy selected item in list to the clipboard
  67. def rowClicked(self, qmodelindex):
  68. self.item = qmodelindex.data(Qt.DisplayRole).toString()
  69. self.clipboard.setText(self.item)
  70. def autoGetFromClipboard(self):
  71. if self.ui.checkBox.isChecked():
  72. self.ui.lineEdit.setText(unicode(self.clipboard.text()))
  73. self.updateUi()
  74. def changeCombo(self):
  75. self.getLexi(self.typed)
  76. self.lexiContent()
  77. def getSynoAnto(self, form):
  78. tag = []
  79. soup = BeautifulSoup(self.getHtml(self.typed, form))
  80. tagy = soup.find_all('td', "%s_format" % (form[:4]))
  81. i = 0
  82. while i < len(tagy):
  83. tag_a = tagy[i]
  84. tag.append(tag_a.text)
  85. i += 1
  86. model = ListModel(tag, self)
  87. return model
  88. def getLexi(self, text):
  89. h = self.getHtml(text, "definition")
  90. global soup
  91. soup = BeautifulSoup(h, "lxml")
  92. return soup
  93. def lexiContent(self):
  94. tagy = soup.find_all('div', {'id': 'contentbox'})
  95. tag = str(tagy[0])
  96. self.ui.webView.setHtml(tag.decode('utf8'))
  97. return tagy
  98. # Check if there is more than one definition
  99. def lexiForm(self):
  100. a = re.compile("return sendRequest\(5,'/definition/.*")
  101. multdef = soup.find_all('a', {'onclick': a})
  102. tagform = []
  103. i = 0
  104. while i < len(multdef):
  105. multdef_a = multdef[i]
  106. # Delete digits in definition title
  107. multdef_clean = ''.join(c for c in
  108. multdef_a.text if not c.isdigit())
  109. tagform.append(multdef_clean)
  110. i += 1
  111. return tagform
  112. def getHtml(self, text, form):
  113. conn = httplib2.Http(".cache")
  114. numdef = self.ui.comboBox.currentIndex()
  115. if form == "definition":
  116. htmlSource = conn.request("http://www.cnrtl.fr/%s/%s//%s" %
  117. (form, text, numdef), "GET")
  118. else:
  119. htmlSource = conn.request("http://www.cnrtl.fr/%s/%s" %
  120. (form, text), "GET")
  121. return htmlSource[1]
  122. # Delete cache directory on close
  123. def closeEvent(self, event):
  124. shutil.rmtree('.cache')
  125. print "closed"
  126. class ListModel(QAbstractListModel):
  127. def __init__(self, datain, parent=None, *args):
  128. """ datain: a list where each item is a row
  129. """
  130. QAbstractListModel.__init__(self, parent, *args)
  131. self.listdata = datain
  132. def rowCount(self, parent=QModelIndex()):
  133. return len(self.listdata)
  134. def data(self, index, role):
  135. if index.isValid() and role == Qt.DisplayRole:
  136. return QVariant(self.listdata[index.row()])
  137. else:
  138. return QVariant()
  139. if __name__ == "__main__":
  140. main()