Commit 829c9b57 authored by Andreas Cord-Landwehr's avatar Andreas Cord-Landwehr
Browse files

Remove obsolete scripting API and remove Kross dependency

parent 92673c25
......@@ -43,8 +43,8 @@ find_package(KF5 ${KF5_MIN_VERSION} MODULE REQUIRED COMPONENTS
I18n
KIO
NewStuff
Kross
Sonnet
TextWidgets
KCMUtils
XmlGui
Notifications
......@@ -84,7 +84,6 @@ include_directories (BEFORE ${CMAKE_CURRENT_BINARY_DIR})
# Define link libs for parley executable and unittests
set( parley_LINK_LIBS
LibKEduVocDocumentImport__KEduVocDocument
KF5::KrossCore
Qt5::Core
Qt5::Svg
KF5::I18n
......@@ -137,7 +136,6 @@ endif()
add_subdirectory( docs )
add_subdirectory( src )
add_subdirectory( icons )
add_subdirectory( plugins )
add_subdirectory( themes )
add_subdirectory( tipofday )
......
......@@ -14,8 +14,4 @@ The main class is ParleyApp
File management is done in ParleyDocument
The parloid (plasmoid) consists of ParleyPlasma and ParleyEngine.
Parley supports Kross scripts.
To get started writing scripts for Parley, have a look at the scripts provided with Parley and read the scripting API documentation in the Scripting namespace.
*/
TODO to get scripting into Parley
=============================
* Make KPluginSelector save its settings (which plugin is enabled/disabled)
* On Parley startup load the enabled scripts
* Connect with signal/slot the script and the editing of vocabulary
* Expose some functions that will allow the script to add translations
* Make the translations visible to the user in a nice way.
* Read up on kross
* Define which part of the api will be exposed for scripts
- Do we need an extra layer or can it be integrated directly?
- Can we pass around complex stuff like KEduVocExpression or does that need a wrapper?
- How can scripts fill out for example the conjugations for a verb?
* Integrate with KNewStuff2
* How are scripts/plugins recognized? Probably using .desktop files. Investigate how other apps are doing this.
* Write some example scripts to validate the implementation
- Possible scripts:
+ dict.someserver
+ conjugations for spanish (http://turingmachine.org/compjugador/)
+ script: fetchTranslation("word")
* Maybe try to use python and ruby to check that both are working?
- Frederik volunteers for one py script :)
* Scripts can make use of kde bindings, so they can have a gui. If we deliver some by default, they could even be translated. If there is still time, look into that.
* Scripts (for discussion)
+ define script api
+ scripts adding actions to menu
+ script manager (amarok 1.4.x from distro packages)
#desktop files
install(FILES
google_dictionary.desktop
leo-dict.desktop
example.desktop
DESTINATION ${KDE_INSTALL_DATADIR}/parley/plugins)
#script files
install(FILES
google_dictionary.py
leo-dict.py
example.py
DESTINATION ${KDE_INSTALL_DATADIR}/parley/plugins)
add_subdirectory( wiktionary )
[Desktop Entry]
Encoding=UTF-8
Icon=mypluginicon
Type=Service
ServiceTypes=KPluginInfo
Name=Example Parley Script
Name[bg]=Примерен скрипт за Parley
Name[bs]=Primjer skripte Parley
Name[ca]=Exemple de script del Parley
Name[ca@valencia]=Exemple de script del Parley
Name[cs]=Skript Parley jako příklad
Name[da]=Parley script-eksempel
Name[de]=Parley-Beispielskript
Name[el]=Παράδειγμα σεναρίου Parley
Name[en_GB]=Example Parley Script
Name[es]=Ejemplo de guion de Parley
Name[et]=Parley näidisskript
Name[eu]=Parley script-aren adibidea
Name[fi]=Parleyn esimerkkikomentojono
Name[fr]=Script d'exemple pour Parley
Name[ga]=Script Shamplach Parley
Name[gl]=Script de exemplo para Parley
Name[gu]=ઉદાહરણ પારેલે સ્ક્રિપ્ટ
Name[he]=תסריט Parley לדוגמה
Name[hr]=Primjerak skripte za Parley
Name[hu]=Minta Parley-szkript
Name[is]=Sýniskrifta fyrir Parley
Name[it]=Script di esempio di Parley
Name[ja]=Parley スクリプトの例
Name[kk]=Parley скрипт мысалы
Name[km]=ស្គ្រីប​ Parley គំរូ
Name[ko]=Parley 스크립트 예제
Name[lt]=Parley scenarijaus pavyzdys
Name[lv]=Parley skripta piemērs
Name[mr]=पारले स्क्रिप्टचे उदाहरण
Name[nb]=Eksempelskript for Parley
Name[nds]=Bispillskript för Parley
Name[nl]=Voorbeeld Parley-script
Name[nn]=Parley-eksempelskript
Name[pl]=Przykładowy skrypt Parley
Name[pt]=Programa de Exemplo do Parley
Name[pt_BR]=Script de exemplo do Parley
Name[ru]=Пример сценария для Parley
Name[sk]=Ukážkový skript Parley
Name[sl]=Primer skripta za Parley
Name[sv]=Exempelskript för Parley
Name[tr]=Örnek Parley Betiği
Name[uk]=Приклад скрипту Parley
Name[x-test]=xxExample Parley Scriptxx
Name[zh_CN]=示例 Parley 脚本
Name[zh_TW]=範例 Parley 文稿
Comment=This example script offers two actions: 1) Move selected vocabulary to a different lesson 2) Change the grade of selected words to known (highest grade)
Comment[bs]=Ovaj primjer skripte nudi dvije akcije: 1) Premjesti odabranu riječ u drugu lekciju 2) Promijeni stepen odabranih riječi na poznate (najviši stepen)
Comment[ca]=Aquest script d'exemple ofereix dues accions: 1) Moure el vocabulari seleccionat cap a una lliçó diferent, 2) canviar el grau de les paraules seleccionades a «coneguda» (el grau més alt)
Comment[ca@valencia]=Aquest script d'exemple ofereix dues accions: 1) Moure el vocabulari seleccionat cap a una lliçó diferent, 2) canviar el grau de les paraules seleccionades a «coneguda» (el grau més alt)
Comment[cs]=Tento ukázkový skript nabízí dvě činnosti: 1) Přesun vybrané slovní zásoby do jiné lekce, 2) Změna hodnocení vybraných slov na "známé" (nejvyšší hodnotící stupeň)
Comment[da]=Dette script-eksempel tilbyder to handlinger: 1) Flyt markeret ordforråd til en anden lektion 2) Ændr niveauet for udvalgt ord til kendt (højeste niveau)
Comment[de]=Dieses Beispielskript bietet zwei Möglichkeiten an: 1) Das ausgewählte Vokabular in eine andere Lektion verschieben 2) Den Bekanntheitsgrad auf „bekannt“ (höchste Stufe) setzen
Comment[el]=Το συγκεκριμένο σενάριο-παράδειγμα σας προσφέρει δυο δυνατότητες: 1) Μετακίνηση επιλεγμένου λεξιλογίου σε διαφορετικό μάθημα 2)Τροποποίηση του βαθμού των επιλεγμένων λέξεων ώστε να θεωρούνται γνωστές (υψηλότερος βαθμός)
Comment[en_GB]=This example script offers two actions: 1) Move selected vocabulary to a different lesson 2) Change the grade of selected words to known (highest grade)
Comment[es]=Este guion de ejemplo ofrece dos acciones: 1) Mueve el vocabulario seleccionado a otra lección 2) Cambia el nivel de las palabras seleccionadas a conocer (nivel más alto)
Comment[et]=See näidisskript võimaldab kaht asja. 1) valitud sõnavara liigutamine teise õppetundi, 2) valitud sõnade taseme muutmine omandatud sõnadeks (kõrgeim tase)
Comment[eu]=Script-aren adibide honek bi ekintza eskaintzen ditu: 1) Eraman hautatutako hiztegia beste ikasgai batera 2) Aldatu hautatutako hitzen maila ezagunera (maila altuena)
Comment[fi]=Tällä esimerkkikomentojonolla voi tehdä kaksi asiaa: 1) Siirtää valitun sanan toiseen oppituntiin 2) Vaihtaa valittujen sanojen tason tunnettuun (korkein taso)
Comment[fr]=Cet script d'exemple effectue deux actions : 1) Déplace le vocabulaire sélectionné dans une leçon différente 2) Modifie l'état des mots sélectionnés à « Connu » (niveau le plus haut)
Comment[ga]=Soláthraíonn an script seo dhá ghníomh: 1) Bog stór focal roghnaithe go ceacht eile 2) Athraigh an grád d'fhocail roghnaithe go dtí an grád is airde
Comment[gl]=Este script de exemplo fornece dúas accións: 1) Move o vocabulario escollido a unha lección distinta 2) Cambiar o grao das palabras escollidas a «coñecidas» (máximo grao)
Comment[gu]=આ ઉદાહરણ સ્ક્રિપ્ટ બે ક્રિયાઓ રજૂ કરે છે: ૧) પસંદ કરેલ શબ્દભંડોળને બીજા લેસન પર ખસેડે છે ૨) પસંદ કરેલ શબ્દોનો ક્રમાંક જાણીતા (ઉંચા ક્રમાંક) પર બદલે છે
Comment[hr]=Ovaj primjerak pruža dvije akcije: 1) Pomaknite izabrani vokabular u drugu lekciju 2) Promijenite ocjenu izabranih riječi na poznato (najveća ocjena)
Comment[hu]=Ez a szkript két célt szolgál: 1) Más leckébe tudja mozgatni a kijelölt bejegyzéseket 2) A kijelölt bejegyzések szintjét módosítani tudja
Comment[is]=Þessi sýniskrifta býður upp á tvær aðgerðir: 1) Færa valinn orðaforða yfir í aðra æfingu 2) Breyta stigi valdra orða (í hæsta þekkt)
Comment[it]=Questo script offre due azioni: 1) spostare il vocabolo selezionato in una diversa lezione 2) modificare il grado delle parole selezionate in "conosciute" (il grado più alto)
Comment[ja]=このスクリプトは 2 つのアクションを提供します。1) 選択した語彙を他のレッスンに移動 2) 選択した単語の習得レベルを最高 (知っている) に変更
Comment[kk]=Бұл скрипт екі амал жасауға арналған 1) Таңдалған сөздікті басқа тілге ауыстыру 2) Таңдалған сөздерді білетін (бағасы жоғары) сөздерге жатқызу
Comment[km]=ប្រើ​វចនានុក្រម​ហ្គូហ្គល (translate.google.com) ដើម្បី​បកប្រែ​ពាក្យ
Comment[ko]=이 예제 스크립트는 두 동작을 제공합니다: 1) 선택한 단어를 다른 장으로 이동 2) 선택한 단어의 등급을 변경 (최고 등급)
Comment[lt]=Šis scenarijaus pavyzdys atlieka du veiksmus: 1) Parinktą žodyną perkelia į kitą pamoką 2) Pažymėtų žodžių rangą keičia į „žinomas“ (aukštesnis rangas)
Comment[lv]=Šis piemēra skripts parāda divas darbības: 1) Pārvietot izvēlēto vārdnīcu uz citu nodarbību 2) Nomainīt izvēlēto vārdu kategoriju uz zināmu (augstākā kategorija)
Comment[nb]=Dette eksempelskriptet kan utføre to handlinger: 1) Flytt markert ordforråd til en annen leksjon 2) Endre karakter for markerte ord til kjent (høyeste karakter)
Comment[nds]=Dit Bispillskript stellt twee Akschonen praat: 1) Den utsöchten Vokavelsett na en anner Lex verschuven 2) De Stoop vun de utsöchten Wöör op "begäng" (hööchst Stoop) setten
Comment[nl]=In dit voorbeeldscript worden twee acties uitgevoerd: 1) Geselecteerde woordenlijst naar een andere les verplaatsen 2) De beoordeling van de geselecteerde woorden naar bekend veranderen (de hoogste beoordeling)
Comment[nn]=Dette eksempelskriptet har to handlingar: 1) Flytt vald orddokument til ei anna øving. 2) Endra nivået til dei valde orda til «kjent» (høgaste nivå).
Comment[pl]=Ten przykładowy skrypt pozwala na dwie akcje: 1) przeniesienie wybranego słownictwa do innej lekcji 2) zmiany stanu wybranych słów na znane (najwyższa ocena)
Comment[pt]=Este programa de exemplo oferece duas acções: 1) Move o vocabulário seleccionado para uma lição diferente 2) Muda a nota das palavras seleccionadas para sabida (nota mais alta)
Comment[pt_BR]=Este script de exemplo oferece duas ações: 1) mover o vocabulário selecionado para uma lição diferente 2) alterar o grau das palavras selecionadas para conhecidas (grau mais alto)
Comment[ru]=Этот сценарий позволяет совершать два действия: 1) Перемещать выбранные словари в другой урок 2) Изменять оценку выбранных слов до «известных» (высшая оценка)
Comment[sk]=Tento ukážkový skript ponúka dve akcie: 1) Presun vybranej slovnej zásoby do inej lekcie 2) Zmena stupňa vybraných slov na známe (najvyšší stupeň)
Comment[sl]=Ta primer skripta ponuja dve dejanji: 1) Premakni izbrano besedišče v drugo lekcijo 2) Spremeni oceno izbranih besed v znano (najvišja ocena)
Comment[sv]=Exempelskriptet erbjuder två åtgärder: 1) Flytta valt ordförråt till en annan lektion, 2) Ändra betyg för valda ord till kända (högsta betyget)
Comment[tr]=Bu örnek betik iki eylem sunar: 1)Seçili kelimeyi farklı bir derse taşı 2)Seçili kelimelerin derecesini "bilinen"e (en yüksek derece) yap
Comment[uk]=Цей скрипт-зразок виконує дві функції: 1) Переміщує вибраний словник до іншого уроку. 2) Змінює клас вибраних слів на відому (найвищий клас).
Comment[x-test]=xxThis example script offers two actions: 1) Move selected vocabulary to a different lesson 2) Change the grade of selected words to known (highest grade)xx
Comment[zh_CN]=示例脚本包含两个操作:1、将所选词移动到其他课程内;2、将所选词的难度等级移动到已知的更高等级内
Comment[zh_TW]=此範例提供兩個動作:1) 將選取的字彙移到不同的課程中。2) 變更所選取的單字的等級。
Script=example.py
X-KDE-PluginInfo-Author=Avgoustinos Kadis
X-KDE-PluginInfo-Email=avgoustinos.kadis@kdemail.net
X-KDE-PluginInfo-Name=parley_example_script
X-KDE-PluginInfo-Version=1.1
X-KDE-PluginInfo-Website=https://edu.kde.org/parley
X-KDE-PluginInfo-Category=examples
X-KDE-PluginInfo-License=GPL
X-KDE-PluginInfo-EnabledByDefault=true
#!/usr/bin/env kf5kross
# -*- coding: utf-8 -*-
import Parley
import Kross
T = Kross.module("kdetranslation")
#FUNCTIONS
#marks the selected translations as known (grade 7)
def markAsKnown():
for tr in Parley.selectedTranslations():
tr.grade = 7
#SCRIPT MENU
#create a new action for the Scripts menu (action2)
action2 = Parley.newAction("example_action2",T.i18n("Mark as known (highest grade)"))
action2.statusTip=T.i18n("Sets the grade for the selected words to 7 (highest grade)")
Parley.connect(action2,"triggered()",markAsKnown)
[Desktop Entry]
Encoding=UTF-8
Icon=mypluginicon
Type=Service
# The next line doesn't work (didn't help recongnizing X-KDE-PluginInfo-Script=myscript.py
# ServiceTypes=Parley/Script
ServiceTypes=KPluginInfo
Name=Google Dictionary (translation)
Name[bg]=Речник на Google (превод)
Name[bs]=Google rječnik (prijevod)
Name[ca]=Diccionari de Google (traducció)
Name[ca@valencia]=Diccionari de Google (traducció)
Name[cs]=Slovník Google (překlad)
Name[da]=Google Dictionary (oversættelse)
Name[de]=Google-Wörterbuch (Übersetzung)
Name[el]=Λεξικό Google (μετάφραση)
Name[en_GB]=Google Dictionary (translation)
Name[es]=Diccionario de Google (traducción)
Name[et]=Google'i sõnaraamat (tõlkimiseks)
Name[eu]=Google hiztegia (itzulpena)
Name[fi]=Google-kääntäjä (kääntäminen)
Name[fr]=Dictionnaire Google (traduction)
Name[ga]=Foclóir Google (aistriúchán)
Name[gl]=Dicionario de Google (tradución)
Name[gu]=ગુગલ શબ્દકોશ (ભાષાંતર)
Name[he]=מילון גוגל (תרגום)
Name[hr]=Googleov rječnik (prijevod)
Name[hu]=Google Dictionary (fordítás)
Name[is]=Google orðabók (þýðingar)
Name[it]=Google Dizionario (traduzione)
Name[ja]=Google 辞書 (翻訳)
Name[kk]=Google сөздігі (аудару)
Name[km]=វចនានុក្រម​ហ្គូហ្គល (កា​របកប្រែ)
Name[ko]=구글 사전 (번역)
Name[lt]=Google žodynas (vertimas)
Name[lv]=Google vārdnīca (tulkošana)
Name[mr]=गूगल शब्दकोश (भाषांतर)
Name[nb]=Google ordbok (oversettelse)
Name[nds]=Google-Wöörbook (Översetten)
Name[nl]=Google Dictionary (vertaling)
Name[nn]=Google-ordbok (omsetjing)
Name[pa]=ਗੂਗਲ ਡਿਕਸ਼ਨਰੀ (ਅਨੁਵਾਦ)
Name[pl]=Słownik Google (tłumaczenie)
Name[pt]=Dicionário do Google (tradução)
Name[pt_BR]=Dicionário do Google (tradução)
Name[ru]=Google Переводчик
Name[sk]=Slovník Google (preklad)
Name[sl]=Google Slovar (prevod)
Name[sv]=Googles ordlista (översättning)
Name[tr]=Google Sözlük (çeviri)
Name[ug]=گۇگىل لۇغىتى (تەرجىمە)
Name[uk]=Словник Google (переклад)
Name[x-test]=xxGoogle Dictionary (translation)xx
Name[zh_CN]=Google 词典(翻译)
Name[zh_TW]=Google 字典(翻譯)
Comment=Uses Google Dictionary (translate.google.com) to translate words
Comment[bg]=Използване на речника на Google (translate.google.com) за превод на думи
Comment[bs]=Koristi Google riječnik (translate.google.com) za prijevod riječi
Comment[ca]=Usa el diccionari de Google (translate.google.com) per a traduir les paraules
Comment[ca@valencia]=Usa el diccionari de Google (translate.google.com) per a traduir les paraules
Comment[cs]=Používá slovník Google (translate.google.com) pro překlad slov
Comment[da]=Bruger Google Dictionary (translate.google.com) til at oversætte ord
Comment[de]=Verwendet Google-Wörterbuch (translate.google.de) zum Übersetzen von Wörtern
Comment[el]=Χρήση του λεξικού Google (translate.google.com) για τη μετάφραση λέξεων
Comment[en_GB]=Uses Google Dictionary (translate.google.com) to translate words
Comment[es]=Utiliza el diccionario de Google (translate.google.com) para traducir palabras
Comment[et]=Google'i sõnaraamatu (translate.google.com) kasutamine sõnade tõlkimiseks
Comment[eu]=Google hiztegia (translate.google.com) erabiltzen du hitzak itzultzeko
Comment[fi]=Käyttää Google-kääntäjää (translate.google.com) sanojen kääntämiseen
Comment[fr]=Utilise le dictionnaire Google (« translate.google.com ») pour traduire des mots
Comment[ga]=Bain úsáid as Foclóir Google (translate.google.com) chun focail a aistriú
Comment[gl]=Emprega o dicionario de Google (translate.google.com) para traducir palabras
Comment[gu]=શબ્દો ભાષાંતર કરવા માટે ગુગલ શબ્દકોશ (translate.google.com) વાપરે છે
Comment[he]=משתמש במילון של גוגל (translate.google.com) לתרגום מילים
Comment[hr]=Koristi Googleov rječnik (translate.google.com) za prijevod riječi
Comment[hu]=Fordítás a Google Dictionary (translate.google.com) használatával
Comment[is]=Notar Google orðabók (translate.google.com) til þýðingar á orðum
Comment[it]=Usa Google Dizionario (translate.google.com) per tradurre le parole
Comment[ja]=Google 辞書 (translate.google.com) を使って単語を翻訳します
Comment[kk]=Сөздерді аудару үшін Google сөздігін (translate.google.com) қолдану
Comment[km]=ប្រើ​វចនានុក្រម​ហ្គូហ្គល (translate.google.com) ដើម្បី​បកប្រែ​ពាក្យ
Comment[ko]=Google 사전 (translate.google.com)으로 단어를 번역합니다
Comment[lt]=Naudoja Google žodyną (translate.google.com), žodžių vertimui
Comment[lv]=Izmanto Google vārdnīcu (translate.google.com), lai tulkotu vārdus
Comment[nb]=Bruker Google Ordbok (translate.google.com) til å oversette ord
Comment[nds]=Bruukt dat Google-Wöörbook (translate.google.com) för't Översetten
Comment[nl]=Gebruikt Google Dictionary (woordenboek van Google: translate.google.com) voor het vertalen van woorden
Comment[nn]=Brukar Google-ordbok (translate.google.com) til å setja om ord
Comment[pl]=Używa słownika Google (translate.google.com) do tłumaczenia
Comment[pt]=Usar o Dicionário do Google (translate.google.com) para traduzir palavras
Comment[pt_BR]=Usa o dicionário do Google (translate.google.com) para traduzir palavras
Comment[ru]=Использует Google Переводчик (translate.google.com) для перевода слов
Comment[sk]=Používa slovník Google (translate.google.com) na preklad slov
Comment[sl]=Za prevod besed uporabi Google Slovar (translate.google.com)
Comment[sv]=Använder Googles ordlista (translate.google.com) för att översätta ord
Comment[tr]=Kelimeleri çevirmek için Google Sözlük'ü (translate.google.com) kullanır
Comment[ug]=سۆزلەرنى تەرجىمە قىلىش ئۈچۈن گۇگىل لۇغىتى (translate.google.com) نى ئىشلىتىدۇ
Comment[uk]=Використовує словник Google (translate.google.com) для перекладу слів
Comment[x-test]=xxUses Google Dictionary (translate.google.com) to translate wordsxx
Comment[zh_CN]=使用 Google 词典(translate.google.com)来翻译单词
Comment[zh_TW]=使用 Google 字典(translate.google.com)來翻譯單字
Script=google_dictionary.py
X-KDE-PluginInfo-Author=Avgoustinos Kadis
X-KDE-PluginInfo-Email=avgoustinos.kadis@kdemail.net
X-KDE-PluginInfo-Name=google_dict
X-KDE-PluginInfo-Version=1.1
X-KDE-PluginInfo-Website=https://edu.kde.org/parley
X-KDE-PluginInfo-Category=translation
X-KDE-PluginInfo-License=GPL
X-KDE-PluginInfo-EnabledByDefault=true
# the next line didn't work
# X-KDE-PluginInfo-Script=myscript.py
#!/usr/bin/env kf5kross
import socket
import urllib2
import urllib
from sgmllib import SGMLParser
import Parley
import re
# timeout of search (important for slow connections, not to freeze Parley by waiting for a result)
timeout = 1.0
socket.setdefaulttimeout(timeout)
# fetches the html document for the given word and language pair
def fetchData(word,from_lang,to_lang):
url = "https://translate.google.com/translate_dict"
param_word_trn = ("q",word) #set query parameter
param_lang_pair = ("langpair",from_lang+"|"+to_lang)
request_url = url + "?" + urllib.urlencode([param_word_trn,param_lang_pair])
#print request_url
try:
results = urllib2.urlopen(request_url)
return results.read()
except:
#in case of error not to return incompleted results
return ""
#parses data and returns the parser object (that contains the translations/langpairs found)
def parseData(data,word,from_lang,to_lang):
p = myParser()
p.word = word
p.from_lang = from_lang
p.to_lang = to_lang
p.feed(data)
p.close()
return p
#corrects the difference between the locale names of Parley and the google dictionary
def locale(lang):
if lang == "en_US":
return "en"
if lang == "zh_TW":
return "zh-TW"
if lang == "zh_HK":
return "zh-HK"
if lang == "zh_CN":
return "zh-CN"
return lang
# called by Parley to translate the word
def translateWord(word,from_lang,to_lang):
print "google_dictionary.py - Translating",word,from_lang,to_lang
data = fetchData(word,locale(from_lang),locale(to_lang))
parser = parseData(data,word,from_lang,to_lang)
#return parser.words
# called by Parley to retrieve the language pairs provided by this script
# should return: [("en","fr"),("en","de")] for translation from english to french and english to german
def getLanguagePairs():
data = fetchData("ignorethis","en","fr")
parser = parseData(data)
return map(split_langpair,parser.langpairs)
# function to split a language pair string into a tuple
def split_langpair(s):
[f,t] = s.split("|",1)
return (f,t)
# ------------ HTML Parser ----------- #
class myParser(SGMLParser):
#for every start_tagname function you add you have to make sure the tag is added to the self.tags_stack
def reset(self):
SGMLParser.reset(self)
self.words = [] #translated words found in html
self.langpairs = [] #language pairs found in html file
self.tags_stack = []
self.stop = False
def unknown_starttag(self,tag,attrs):
self.tags_stack.append(tag)
#print "unknown : ", tag, " ", len(self.tags_stack)
def start_span(self, attrs):
#print "known : ", "span", " ", len(self.tags_stack)
if ("class","definition") in attrs:
self.tags_stack.append("<!translation!>") #marks tag with <!translation!> to get its data in handle_data
else:
self.tags_stack.append("span")
def start_option(self, attrs):
for name,value in attrs:
if name == "value":
self.langpairs.append(value)
self.tags_stack.append("option")
def handle_data(self,data):
if data == "Web definitions": self.stop = True #to make it stop after the web definitions
if len(self.tags_stack) > 0 and self.tags_stack[len(self.tags_stack)-1] == "<!translation!>":
#print "data: ", data
self.words.append(data.strip())
#print self.word, self.from_lang, self.to_lang
if self.stop == False:
w = self.clearWord(data)
Parley.addTranslation(self.word,self.from_lang,self.to_lang,w)
def unknown_endtag(self,tag):
myParser.remove_not_closed_tags(self,tag)
if len(self.tags_stack) > 0 and self.tags_stack[len(self.tags_stack)-1] == tag:
#print "end_tag : ", tag, " ", len(self.tags_stack)
self.tags_stack.pop()
#removes all the tags from the stack that have no closed tags (don't modify)
def remove_not_closed_tags(self,tag):
while len(self.tags_stack) > 0 and self.tags_stack[len(self.tags_stack)-1] != tag:
self.tags_stack.pop()
#cleans up the given word from parentheses etc
def clearWord(self,word):
#word = "b[lue] socks (and) red shoes"
p = re.compile( '(jmdn\.|etw\.)')
word = p.sub( '', word)
p = re.compile( '(\(.*\))')
word = p.sub( '', word)
p = re.compile( '(\[.*\])')
word = p.sub( '', word)
p = re.compile( '(\W)',re.UNICODE)
word = p.sub( ' ', word)
#replace double spaces produced from the previous ones
p = re.compile( '(\s\s)')
word = p.sub( ' ', word)
return word.strip()
[Desktop Entry]
Encoding=UTF-8
Icon=mypluginicon
Type=Service
ServiceTypes=KPluginInfo
Name=LEO Dictionary (Translation)
Name[bg]=Речник LEO (превод)
Name[bs]=LEO Rječnik (prijevod)
Name[ca]=Diccionari LEO (traducció)
Name[ca@valencia]=Diccionari LEO (traducció)
Name[cs]=Slovník LEO (překlad)
Name[da]=LEO Dictionary (oversættelse)
Name[de]=LEO-Wörterbuch (Übersetzung)
Name[el]=Λεξικό LEO (μετάφραση)
Name[en_GB]=LEO Dictionary (Translation)
Name[es]=Diccionario LEO (traducción)
Name[et]=LEO sõnaraamat (tõlkimiseks)
Name[eu]=LEO hiztegia (itzulpena)
Name[fi]=LEO Dictionary (kääntäminen)
Name[fr]=Dictionnaire LEO (traduction)
Name[ga]=Foclóir LEO (Aistriúchán)
Name[gl]=Dicionario LEO (Tradución)
Name[gu]=LEO શબ્દકોશ (ભાષાંતર)
Name[he]=מילון LEO (תרגום)
Name[hr]=LEO rječnik (prijevod)
Name[hu]=LEO Dictionary (fordítás)
Name[is]=LEO orðabók (þýðing)
Name[it]=Dizionario LEO (traduzione)
Name[ja]=LEO 辞書 (翻訳)
Name[kk]=LEO Сөздігі (аудару)
Name[km]=វចនានុក្រម LEO (ការ​បកប្រែ)
Name[ko]=LEO 사전 (번역)
Name[lt]=LEO žodynas (vertimas)
Name[lv]=LEO vārdnīca (tulkošana)
Name[mr]=लिओ शब्दकोश (भाषांतर)
Name[nb]=LEO-ordbok (Oversettelse)
Name[nds]=LEO-Wöörbook (Översetten)
Name[nl]=LEO Dictionary (Vertaling)
Name[nn]=LEO-ordbok (omsetjing)
Name[pl]=Słownik LEO (tłumaczenie)
Name[pt]=Dicionário LEO (Tradução)
Name[pt_BR]=Dicionário LEO (tradução)
Name[ru]=LEO Dictionary (перевод)
Name[sk]=Slovník LEO (preklad)
Name[sl]=Slovar LEO (prevod)
Name[sv]=LEO:s ordlista (översättning)
Name[tr]=LEO Sözlük (Çeviri)
Name[ug]=LEO لۇغىتى (تەرجىمە )
Name[uk]=Словник LEO (переклад)
Name[x-test]=xxLEO Dictionary (Translation)xx
Name[zh_CN]=LEO 词典(翻译)
Name[zh_TW]=LEO 字典(翻譯)
Comment=Uses LEO Dictionary (dict.leo.org) to translate words
Comment[bg]=Използване на речника на LEO (dict.leo.org) за превод на думи
Comment[bs]=Koristi LEO rječnik (dict.leo.org) za prijevod riječi
Comment[ca]=Usa el diccionari LEO (dict.leo.org) per a traduir les paraules
Comment[ca@valencia]=Usa el diccionari LEO (dict.leo.org) per a traduir les paraules
Comment[cs]=Používá slovník LEO (dict.leo.org) pro překlad slov
Comment[da]=Bruger LEO Dictionary (dict.leo.org) til at oversætte ord
Comment[de]=Verwendet LEO-Wörterbuch (dict.leo.org) zum Übersetzen von Wörtern
Comment[el]=Χρήση λεξικού LEO (dict.leo.org) για τη μετάφραση λέξεων
Comment[en_GB]=Uses LEO Dictionary (dict.leo.org) to translate words
Comment[es]=Utiliza el diccionario LEO (dict.leo.org) para traducir palabras
Comment[et]=LEO sõnaraamatu (dict.leo.org) kasutamine sõnade tõlkimiseks
Comment[eu]=LEO hiztegia (dict.leo.org) erabiltzen du hitzak itzultzeko
Comment[fi]=Käyttää LEO Dictionaryä (dict.leo.org) sanojen kääntämiseen
Comment[fr]=Utilise le dictionnaire LEO (« dict.leo.org ») pour traduire des mots
Comment[ga]=Bain úsáid as foclóir LEO (dict.leo.org) chun focail a aistriú
Comment[gl]=Emprega o dicionario LEO (dict.leo.org) para traducir palabras
Comment[gu]=શબ્દો ભાષાંતર કરવા માટે LEO શબ્દકોશ (dict.leo.org) વાપરો
Comment[he]=משתמש במילון LEO (dict,leo.org) לתרגום מילים.
Comment[hr]=Koristi LEO rječnik (dict.leo.org) za prijevod riječi
Comment[hu]=Fordítás a LEO Dictionary használatával
Comment[is]=Notar LEO orðabók (dict.leo.org) til þýðingar á orðum
Comment[it]=Usa il dizionario LEO (dict.leo.org) per tradurre le parole
Comment[ja]=LEO 辞書 (dict.leo.org) を使って単語を翻訳します
Comment[kk]=Сөздерді аудару үшін LEO сөздігін (dict.leo.org) қолдану
Comment[km]=ប្រើ​វចនានុក្រម LEO (dict.leo.org) ដើម្បី​បកប្រែ​ពាក្យ
Comment[ko]=LEO 사전 (dict.leo.org)으로 단어를 번역합니다.
Comment[lt]=Žodžius verčia pagal LEO žodyną (dict.leo.org)
Comment[lv]=Izmanto LEO vārdnīcu (dict.leo.org), lai tulkotu vārdus
Comment[nb]=Bruker LEO-ordbok (dict.leo.org) for å oversette ord
Comment[nds]=Bruukt dat LEO-Wöörbook (dict.leo.org) för't Översetten
Comment[nl]=Gebruikt LEO Dictionary (LEO-woordenboek: dict.leo.org) voor het vertalen van woorden
Comment[nn]=Brukar LEO-ordbok (dict.leo.org) til å setja om ord
Comment[pl]=Używa słownika LEO (dict.leo.org) do tłumaczenia
Comment[pt]=Usa o Dicionário LEO (dict.leo.org) para traduzir palavras
Comment[pt_BR]=Usa o dicionário LEO (dict.leo.org) para traduzir palavras
Comment[ru]=Использовать LEO Dictionary (dict.leo.org) для перевода слов
Comment[sk]=Používa slovník LEO (dict.leo.org) na preklad slov
Comment[sl]=Za prevod besed uporabi LEO (dict.leo.org)
Comment[sv]=Använder LEO:s ordlista (dict.leo.org) för att översätta ord
Comment[tr]=Kelimeleri çevirmek için LEO Sözlük'ü (dict.leo.org) kullanır
Comment[ug]=سۆزلەرنى تەرجىمە قىلىش ئۈچۈن LEO لۇغىتى (dict.leo.org) نى ئىشلىتىدۇ
Comment[uk]=Використовує словник LEO (dict.leo.org) для перекладу слів
Comment[x-test]=xxUses LEO Dictionary (dict.leo.org) to translate wordsxx
Comment[zh_CN]=使用 LEO 词典(dict.leo.org)来翻译单词
Comment[zh_TW]=使用 LEO 字典(dict.leo.org)來翻譯單字
Script=leo-dict.py
X-KDE-PluginInfo-Author=Avgoustinos Kadis
X-KDE-PluginInfo-Email=avgoustinos.kadis@kdemail.net
X-KDE-PluginInfo-Name=leo_dict
X-KDE-PluginInfo-Version=1.1
X-KDE-PluginInfo-Website=https://edu.kde.org/parley
X-KDE-PluginInfo-Category=translation
X-KDE-PluginInfo-License=GPL
X-KDE-PluginInfo-EnabledByDefault=true
#!/usr/bin/env kf5kross
# -*- coding: utf-8 -*-
import socket
import urllib2
import urllib
from sgmllib import SGMLParser
import Parley
import re
#german to french (Glas) [links off]
#https://dict.leo.org/frde?lp=frde&lang=de&searchLoc=1&cmpType=relaxed&sectHdr=on&spellToler=on&chinese=both&pinyin=diacritic&search=Glas&relink=off
#german to spanish (Glas)
#https://dict.leo.org/esde?lp=esde&lang=de&searchLoc=1&cmpType=relaxed&sectHdr=on&spellToler=std&chinese=both&pinyin=diacritic&search=Glas&relink=on
#spanish to german (tarro)
#https://dict.leo.org/esde?lp=esde&lang=de&searchLoc=-1&cmpType=relaxed&sectHdr=on&spellToler=std&chinese=both&pinyin=diacritic&search=tarro&relink=on
#spanish to german (tarro) [links off]
#https://dict.leo.org/esde?lp=esde&lang=de&searchLoc=-1&cmpType=relaxed&sectHdr=on&spellToler=std&chinese=both&pinyin=diacritic&search=tarro&relink=off
# timeout of search (important for slow connections, not to freeze Parley by waiting for a result)
timeout = 1.0
socket.setdefaulttimeout(timeout)
def languageString(from_lang,to_lang):
combined = from_lang + "-" + to_lang
A = { 'es-de': 'esde', 'de-es':'esde', 'fr-de':'frde', 'de-fr':'frde', 'en-de':'ende', 'de-en':'ende', 'it-de':'itde', 'de-it':'itde', 'ch-de':'chde', 'de-ch':'chde' }
if (A.has_key(combined)):
return A[combined]
else:
return None
def searchLoc(from_lang,to_lang):
if from_lang == "de":
return 1
return -1
# fetches the html document for the given word and language pair
def fetchData(word,from_lang,to_lang):
locale = languageString(from_lang,to_lang)
if locale == None:
return #not supported languages
url = "https://dict.leo.org/"+locale
#esde?lp=esde&lang=de&searchLoc=-1&cmpType=relaxed&sectHdr=on&spellToler=std&chinese=both&pinyin=diacritic&search=tarro&relink=off