captchaboy commited on
Commit
6d71e4c
·
1 Parent(s): 0fbbe99

Create new file

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