Skip to content

Commit

Permalink
add alfred workflow
Browse files Browse the repository at this point in the history
  • Loading branch information
ademozay committed Dec 20, 2020
1 parent 15847de commit 1974932
Show file tree
Hide file tree
Showing 8 changed files with 272 additions and 164 deletions.
69 changes: 69 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# Lügat

`TDK Güncel Türkçe Sözlük` için komut satırı arabirimi.

![ön izleme](https://raw.githubusercontent.com/ademozay/lugat/master/lugat.gif "Lügat")

## Nasıl Yüklenir?

pip (Python 3) ile

```sh
pip install lugat
```

Docker ile kullanmak isterseniz aşağıdaki fonksiyonu profil dosyanıza(.bash_rc, .zsh_rc vb.) ekleyebilirsiniz.

```sh
function lugat() {
docker run -it --rm ademozay/lugat $@
}
```

## Nasıl Kullanılır?

Komut satırında

```sh
lugat <kelime, atasözü, deyim vb.>

# Atasözleri, deyimler, birleşik fiiller ve birleşik kelimeler gibi detaylar için

lugat -h <kelime, atasözü, deyim vb.>
```

Python paketi olarak

```python
from lugat import lookup, LookupException

try:
word = lookup(search)
variations = word.get_variations() # kelimenin tüm varyasyonları

for v in variations:
print(v.name) # varyasyonun özel ismi
print(v.origin) # kelimenin kökeni
print(v.meanings) # özellikleri ve örnekleriyle birlikte kelimenin anlamları
print(v.compound_words) # ilgili birleşik kelimeler
print(v.proverbs) # ilgili atasözleri, deyimler ve birleşik fiiller

except LookupException:
pass

```

`Alfred` ile

[Lugat.alfredworkflow](<https://github.com/ademozay/lugat/releases/download/0.2.0/Lugat.alfredworkflow>)'u indirip kurduktan sonra bir kısayol atamanız gerekecek.
Ben `Option + Shift + L` kombiyasyonunu kullanıyorum. Eğer kısayol atamak istemezseniz, Alfred'e `lügat` yazdıktan sonra yine arama yapabilirsiniz.

`Command + L` kısayolu ile, Alfred ekranına sığmayan tanımları ve kullanım örneklerini `Large Type` ile görüntüleyebilirsiniz.

`Command + Enter` kısayolu ile, ilgili sonuçları terminalde görüntüleyebilirsiniz.

Sistemde seçili olan bir kelimeyi direkt olarak aramak istediğiniz takdirde; Alfred kısayolunu ayarladığınız pencerede, `Argument` için `Selection on macOS` seçili olmalı.

[![Lügat | Alfred](https://raw.githubusercontent.com/ademozay/lugat/master/alfred_thumbnail.jpg)](https://www.youtube.com/watch?v=YSDX0bgr5Zk "Lügat | Alfred")

*Not: [Alfred](alfredapp.com), yalnızca macOS üzerinde çalışan bir üretkenlik uygulaması, başarılı bir Spotlight alternatifi.*
62 changes: 0 additions & 62 deletions README.rst

This file was deleted.

Binary file added alfred_thumbnail.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
60 changes: 60 additions & 0 deletions lugat/alfred.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import json

class Alfred(dict):

def __init__(self):
dict.__init__(self, items=[])

def add_item(self, item):
self['items'].append(item)

def alphy(self):
return json.dumps(self, ensure_ascii=False)

class AlfredItem(dict):

def __init__(self, title, subtitle, arg):
dict.__init__(self,
title=title,
subtitle=subtitle,
arg=arg,
text={},
)

def set_clipboard_text(self, text):
self['text']['copy'] = text

def set_largetype_text(self, text):
self['text']['largetype'] = text

def alphy(search, variations) -> str:
alfred = Alfred()

for v in variations:
name = v.name
for m in v.meanings:
title = m.text
subtitle = ', '.join(m.props)
arg = search

if v.origin:
subtitle = "{} - {}".format(v.origin, subtitle)

sample = ''
for s in m.samples:
sample += '- {}'.format(s.text)
if s.authors:
sample += '\\n'
sample += ', '.join(s.authors)
break

largetype = '{}\\n{}\\n\\n{}\\n\\n{}'.format(name, subtitle, title, sample)

item = AlfredItem(title, subtitle, arg)

item.set_clipboard_text(title)
item.set_largetype_text(largetype)

alfred.add_item(item)

return alfred.alphy()
70 changes: 70 additions & 0 deletions lugat/args.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import sys
import unicodedata

from enum import Enum

from termcolor import colored

from lugat.__version__ import __version__

HELP_TEXT = '''
''' + colored("TDK Güncel Türkçe Sözlük'te arama yapın.", attrs=['bold']) + '''
''' + colored('lugat', attrs=['bold']) + ''' mütevazı
''' + colored('lugat', attrs=['bold']) + ''' cefakâr
Daha detaylı sonuçlar için:
''' + colored('lugat', attrs=['bold']) + ''' -h çırak
''' + colored('lugat', attrs=['bold']) + ''' -h usta
* Detaylı sonuçlar; atasözleri, deyimler,
birleşik fiiller ve birleşik kelimelerden oluşur.
lugat ''' + colored('v' + __version__, attrs=['bold']) + '''
'''

class Args:

class Flag(Enum):
VERBOSE = '-h'
ALFRED = '--alfred'

flags = [f.value for f in Flag]
enabled_flags = []
input = ''

def __init__(self):
args = sys.argv[1:]
if len(args) < 1:
sys.stdout.write(HELP_TEXT)
exit(2)

self._resolve_flags(args)
self._resolve_input(args)

def is_enabled(self, flag):
return flag.value in self.enabled_flags

def get_input(self):
return self.input

def _resolve_flags(self, args):
for arg in args:
for flag in self.flags:
if flag == arg:
self.enabled_flags.append(flag)

def _resolve_input(self, args):
remaing_args = list(filter(lambda arg: arg not in self.flags, args))
input = ' '.join(remaing_args)
self.input = self._normalize(input)

if not self.input:
sys.stdout.write(HELP_TEXT)
sys.exit(2)

def _normalize(self, text, normalization='NFC'):
# https://www.alfredforum.com/topic/7357-encoding-in-script-filter-input/?tab=comments#comment-39232
return unicodedata.normalize(normalization, text)
120 changes: 20 additions & 100 deletions lugat/cli.py
Original file line number Diff line number Diff line change
@@ -1,109 +1,29 @@
import sys

from termcolor import colored

from lugat.__version__ import __version__
from lugat.dict import lookup, LookupException

HELP_TEXT = '''
''' + colored("TDK Güncel Türkçe Sözlük'te arama yapın.", attrs=['bold']) + '''
''' + colored('lugat', attrs=['bold']) + ''' mütevazı
''' + colored('lugat', attrs=['bold']) + ''' cefakâr
Daha detaylı sonuçlar için:
''' + colored('lugat', attrs=['bold']) + ''' -h çırak
''' + colored('lugat', attrs=['bold']) + ''' -h usta
*Detaylı sonuçlar; atasözleri, deyimler,
birleşik fiiller ve birleşik kelimelerden oluşur.

lugat ''' + colored('v' + __version__, attrs=['bold']) + '''
'''

VERBOSE_FLAG = '-h'
FLAGS = [VERBOSE_FLAG]
from lugat.dict import lookup
from lugat.alfred import alphy
from lugat.colorize import colorize
from lugat.args import Args

def main():
args = sys.argv[1:]

if len(args) < 1:
print(HELP_TEXT)
exit(2)

verbose = False
if VERBOSE_FLAG in args:
verbose = True

remaing_args = list(filter(lambda arg: arg not in FLAGS, args))
remaing_args = list(filter(lambda arg: not arg.startswith('-'), args))

search = ' '.join(remaing_args)

if not search:
print(HELP_TEXT)
sys.exit(2)

word = lookup(search)

if word is not None:
variations = word.get_variations()

def colorize_variations():
text = ''
for i, v in enumerate(variations, start=1):
text += colored(v.name, 'yellow', attrs=['bold', 'underline'])
if len(variations) > 2:
text += ' {}'.format(colored('[{}]'.format(i), attrs=['dark']))
if v.origin:
text += ' - ' + colored(v.origin, 'yellow', attrs=['dark'])

text += '\n\n'
for m in v.meanings:
text += '• ' + m.text + ' '

if m.props:
text += colored(
', '.join(m.props),
'yellow', attrs=['dark'],
)

text += '\n'
for s in m.samples:
text += ' {} '.format(colored('Örnek', 'magenta'))
text += ' {}'.format(colored(s.text, 'green'))
if s.authors:
text += '\n'
text += ' {} '.format(colored('Yazarlar', 'magenta'))
text += colored(', '.join(s.authors), 'blue')
text += '\n'
else:
text += '\n'

if not verbose:
continue

if v.compound_words:
text += colored('Birleşik Kelimeler', 'cyan') + '\n'
text += '\n'.join(['• ' + c for c in v.compound_words])
text += '\n\n'

if v.proverbs:
text += colored(
'Atasözleri, Deyimler veya Birleşik Fiiller', 'cyan'
)
text += '\n'
text += '\n'.join(['• ' + p for p in v.proverbs])
text += '\n'

return text

out = colorize_variations()

print(out.rstrip('\n'))

args = Args()
search = args.get_input()
word = lookup(search)

if word is None:
exit(0)

variations = word.get_variations()

if args.is_enabled(Args.Flag.ALFRED):
out = alphy(search, variations)
sys.stdout.write(out)
else:
verbose = args.is_enabled(Args.Flag.VERBOSE)
out = colorize(variations, verbose)
sys.stdout.write(out)

if __name__ == "__main__":
main()
Loading

0 comments on commit 1974932

Please sign in to comment.