vumichien commited on
Commit
553c308
·
1 Parent(s): 6b39f86

Create utils.py

Browse files
Files changed (1) hide show
  1. utils.py +47 -0
utils.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from io import BytesIO
2
+ import base64
3
+ from PIL import Image
4
+ import cv2
5
+ import numpy as np
6
+
7
+
8
+ def tts(text: str, language="ja") -> object:
9
+ """Converts text into autoplay html.
10
+ Args:
11
+ text (str): generated answer of bot
12
+ language (str): language of text
13
+ Returns:
14
+ html: autoplay object
15
+ """
16
+ tts_object = gTTS(text=text, lang=language, slow=False)
17
+ bytes_object = BytesIO()
18
+ tts_object.write_to_fp(bytes_object)
19
+ bytes_object.seek(0)
20
+ b64 = base64.b64encode(bytes_object.getvalue()).decode()
21
+ return b64
22
+
23
+
24
+ def read_image_file(file) -> Image.Image:
25
+ image = Image.open(BytesIO(file))
26
+ return image
27
+
28
+
29
+ def pil_to_base64(img, format="jpeg"):
30
+ buffer = BytesIO()
31
+ img.save(buffer, format)
32
+ img_str = base64.b64encode(buffer.getvalue()).decode("ascii")
33
+ return img_str
34
+
35
+
36
+ def base64_to_pil(img_str):
37
+ if "base64," in img_str:
38
+ img_str = img_str.split(",")[1]
39
+ img_raw = base64.b64decode(img_str)
40
+ img = Image.open(BytesIO(img_raw))
41
+ return img
42
+
43
+
44
+ def get_hist(image):
45
+ hist = cv2.calcHist([np.array(image)], [0, 1, 2], None, [8, 8, 8], [0, 256, 0, 256, 0, 256])
46
+ hist = cv2.normalize(hist, hist).flatten()
47
+ return hist