captchaboy commited on
Commit
a7fd755
1 Parent(s): 18956dd

Create new file

Browse files
Files changed (1) hide show
  1. app.py +99 -0
app.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # from transformers import AutoModel
2
+ import argparse
3
+ import logging
4
+ import os
5
+ import glob
6
+ import tqdm
7
+ import torch, re
8
+ import PIL
9
+ import cv2
10
+ import numpy as np
11
+ import torch.nn.functional as F
12
+ from torchvision import transforms
13
+ from utils import Config, Logger, CharsetMapper
14
+ import gradio as gr
15
+
16
+ import gdown
17
+ gdown.download(id='16PF_b4dURVkBt4OT7E-a-vq-SRxi0uDl', output='lol.pth')
18
+ gdown.download(id='19rGjfo73P25O_keQv30snfe3IHrK0uV2', output='config.yaml')
19
+
20
+ gdown.download(id='1qyNV80qmYHx_r4KsG3_8PXQ6ff1a1dov', output='modules.zip')
21
+ os.system('unzip modules.zip')
22
+
23
+ def get_model(config):
24
+ import importlib
25
+ names = config.model_name.split('.')
26
+ module_name, class_name = '.'.join(names[:-1]), names[-1]
27
+ cls = getattr(importlib.import_module(module_name), class_name)
28
+ model = cls(config)
29
+ logging.info(model)
30
+ model = model.eval()
31
+ return model
32
+
33
+
34
+ def load(model, file, device=None, strict=True):
35
+ if device is None: device = 'cpu'
36
+ elif isinstance(device, int): device = torch.device('cuda', device)
37
+ assert os.path.isfile(file)
38
+ state = torch.load(file, map_location=device)
39
+ if set(state.keys()) == {'model', 'opt'}:
40
+ state = state['model']
41
+ model.load_state_dict(state, strict=strict)
42
+ return model
43
+
44
+ config = Config('config.yaml')
45
+ config.model_vision_checkpoint = None
46
+ model = get_model(config)
47
+ model = load(model, 'lol.pth')
48
+
49
+
50
+ def postprocess(output, charset, model_eval):
51
+ def _get_output(last_output, model_eval):
52
+ if isinstance(last_output, (tuple, list)):
53
+ for res in last_output:
54
+ if res['name'] == model_eval: output = res
55
+ else: output = last_output
56
+ return output
57
+
58
+ def _decode(logit):
59
+ """ Greed decode """
60
+ out = F.softmax(logit, dim=2)
61
+ pt_text, pt_scores, pt_lengths = [], [], []
62
+ for o in out:
63
+ text = charset.get_text(o.argmax(dim=1), padding=False, trim=False)
64
+ text = text.split(charset.null_char)[0] # end at end-token
65
+ pt_text.append(text)
66
+ pt_scores.append(o.max(dim=1)[0])
67
+ pt_lengths.append(min(len(text) + 1, charset.max_length)) # one for end-token
68
+ return pt_text, pt_scores, pt_lengths
69
+
70
+ output = _get_output(output, model_eval)
71
+ logits, pt_lengths = output['logits'], output['pt_lengths']
72
+ pt_text, pt_scores, pt_lengths_ = _decode(logits)
73
+
74
+ return pt_text, pt_scores, pt_lengths_
75
+
76
+ def preprocess(img, width, height):
77
+ img = cv2.resize(np.array(img), (width, height))
78
+ img = transforms.ToTensor()(img).unsqueeze(0)
79
+ mean = torch.tensor([0.485, 0.456, 0.406])
80
+ std = torch.tensor([0.229, 0.224, 0.225])
81
+ return (img-mean[...,None,None]) / std[...,None,None]
82
+
83
+ def process_image(image):
84
+ charset = CharsetMapper(filename=config.dataset_charset_path, max_length=config.dataset_max_length + 1)
85
+
86
+ img = image.convert('RGB')
87
+ img = preprocess(img, config.dataset_image_width, config.dataset_image_height)
88
+ res = model(img)
89
+ return postprocess(res, charset, 'alignment')[0][0]
90
+
91
+ iface = gr.Interface(fn=process_image,
92
+ inputs=gr.inputs.Image(type="pil"),
93
+ outputs=gr.outputs.Textbox(),
94
+ title="8kun kek",
95
+ description="Making Jim Watkins sheete because he is a techlet pedo",
96
+ # article=article,
97
+ # examples=glob.glob('figs/test/*.png')
98
+ )
99
+ iface.launch(debug=True)