Skip to content

Instantly share code, notes, and snippets.

@iamjinlei0312
Last active July 24, 2020 02:30
Show Gist options
  • Select an option

  • Save iamjinlei0312/1b969a048f2498e4920d22185699f920 to your computer and use it in GitHub Desktop.

Select an option

Save iamjinlei0312/1b969a048f2498e4920d22185699f920 to your computer and use it in GitHub Desktop.
Jinlei's assignment #1
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Describe :
# @Time : 2020/7/23 10:36
# @Author : Jinlei
import random
import argparse
import re
from PIL import Image
from time import sleep
from termcolor import colored
from simpleeval import simple_eval
parser = argparse.ArgumentParser()
parser.add_argument('file')
parser.add_argument('--width', type=int, default=30)
parser.add_argument('--height', type=int, default=30)
args = parser.parse_args()
IMG = args.file
WIDTH = args.width
HEIGHT = args.height
ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")
class Bot(object):
"""Base class"""
wait = 1
def __init__(self):
self.q = ''
self.a = ''
def _think(self, s):
"""Implementation of each chatbot processing algorithm."""
raise NotImplementedError()
def _format(self, s):
return colored(s, 'magenta')
def _say(self, s):
sleep(Bot.wait)
print(self._format(s))
def run(self):
self._say(self.q)
self.a = input()
self._say(self._think(self.a))
class HelloBot(Bot):
def __init__(self):
self.q = "Hi, what is your name?"
def _think(self, s):
return f"Hello {s}"
class GreetingBot(Bot):
def __init__(self):
self.q = "How are you today?"
def _think(self, s):
if 'good' in s.lower() or 'fine' in s.lower():
return "I'm feeling good too"
else:
return "Sorry to hear that"
class FavoriteColorBot(Bot):
def __init__(self):
self.q = "What's your favorite color?"
def _think(self, s):
colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'purple']
return f"You like {s.lower()}? My favorite color is {random.choice(colors)}"
class CalcBot(Bot):
def __init__(self):
self.q = "Through recent upgrade I can do calculation now. Input some arithmetic expression to try:"
def _think(self, s):
result = simple_eval(s)
return f"Done. Result = {result}"
def run(self):
self._say(self.q)
pattern = r'(?:-?\d+)(?:\s*[+\-*\/]\s*)(?:-?\d+)'
while True:
self.a = input()
if not self.a:
continue
if self.a in ['x', 'q', 'exit', 'quit', '退出']:
break
res = re.findall(pattern, self.a)
if not res:
continue
self._say(self._think(res[0]))
class ImageBot(Bot):
def __init__(self, img=IMG):
self.q = "No matter what your mood is, look at a picture and relax."
self.im = Image.open(img).resize((WIDTH, HEIGHT), Image.NEAREST)
def _think(self):
txt = ""
for i in range(HEIGHT):
for j in range(WIDTH):
txt += self._get_char(*self.im.getpixel((j, i)))
txt += '\n'
return txt
@staticmethod
def _get_char(r, g, b, alpha=256):
if alpha == 0:
return ' '
length = len(ascii_char)
gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)
unit = (256.0 + 1) / length
return ascii_char[int(gray / unit)]
def run(self):
self._say(self.q)
self._say(self._think())
class HellChef:
def __init__(self, wait=1):
Bot.wait = wait
self.bots = []
def add(self, bot):
self.bots.append(bot)
def _prompt(self, s):
print(s)
print()
def run(self):
self._prompt("This is HellChef dialog system. Let's talk.")
for bot in self.bots:
bot.run()
if __name__ == '__main__':
hellchef = HellChef()
hellchef.add(HelloBot())
hellchef.add(GreetingBot())
hellchef.add(FavoriteColorBot())
hellchef.add(CalcBot())
hellchef.add(ImageBot())
hellchef.run()
@iamjinlei0312
Copy link
Copy Markdown
Author

iamjinlei0312 commented Jul 23, 2020

直接在命令行执行: python hellchef.py ascii_dora.png

注:ascii_dora.png 可以是其他你喜欢的图片

我这里的 ascii_dora.png 长这样:

ascii_dora

@iamjinlei0312
Copy link
Copy Markdown
Author

iamjinlei0312 commented Jul 23, 2020

运行结果:

This is HellChef dialog system. Let's talk.

Hi, what is your name?
jinlei
Hello jinlei
How are you today?
fine
I'm feeling good too
What's your favorite color?
red
You like red? My favorite color is purple
Through recent upgrade I can do calculation now. Input some arithmetic expression to try:


!!!!@@#$&&**((

!!!!1            +                  2########
Done. Result = 3
-1 + 667
Done. Result = 666
q
No matter what your mood is, look at a picture and relax.
                    
      $x# z J       
     xxxI>h nx      
    #xx  pn)        
    xx     n        
    x> kop -  f     
    x  kkkkkkop     
    x  fffkkk       
    xu  fffk        
     x   Jc         
     $hoJ  ww       
      xxx  Ih       
      xuc      -    
      xxdf          
     k#xx   (       
      xxxxxxx       
     "xxxx          
       x            
     8              
                    


Process finished with exit code 0

@iamjinlei0312
Copy link
Copy Markdown
Author

iamjinlei0312 commented Jul 23, 2020

图片在这里:

第二张为了可爱的哆啦A梦漂亮一点,截成 瘦长 版的了。同理,第一张为了显示字符,就截成 矮胖 版,中间用 666 来衔接

WeChat17eb7e1af3b77f9dfea0c50b5965ba8d

WeChat5e23d25368bba40c82706be6b1e3c8fa

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment