summary refs log tree commit diff stats
path: root/wizard.cpp
blob: c99ec791f15411fb9fe9d54768f3c7b6fc4b3fd7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
#include "wizard.h"

#include <Magick++.h>
#include <allheaders.h>
#include <hkutil/string.h>
#include <tesseract/baseapi.h>

#include <iostream>
#include <list>
#include <memory>
#include <random>
#include <set>
#include <tuple>
#include <vector>

#include "designer.h"
#include "prefix_search.h"

std::string stripSpaces(std::string in) {
  in.erase(std::remove_if(std::begin(in), std::end(in), ::isspace),
           std::end(in));

  return in;
}

class tesseract_deleter {
 public:
  void operator()(tesseract::TessBaseAPI* ptr) const { ptr->End(); }
};

using tesseract_ptr =
    std::unique_ptr<tesseract::TessBaseAPI, tesseract_deleter>;

class pix_deleter {
 public:
  void operator()(Pix* ptr) const { pixDestroy(&ptr); }
};

using pix_ptr = std::unique_ptr<Pix, pix_deleter>;

wizard::wizard(const cardset& cards, const imagestore& images, std::string text,
               std::mt19937& rng)
    : cards_(cards), images_(images), text_(text), rng_(rng()) {
  std::cout << "Characters: ";

  for (char ch : cards_.getCharacters()) {
    std::cout << ch;
  }

  std::cout << std::endl;
}

void wizard::set_status_callback(status_callback_type callback) {
  status_callback_ = callback;
}

Magick::Image wizard::run() {
  tesseract_ptr api{new tesseract::TessBaseAPI()};

  if (api->Init(nullptr, "eng", tesseract::OEM_TESSERACT_LSTM_COMBINED)) {
    throw std::runtime_error("Could not initialize tesseract");
  }

  std::string allChars;
  for (char ch : cards_.getCharacters()) {
    allChars.push_back(ch);
    if (std::isalpha(ch)) {
      allChars.push_back(std::toupper(ch));
    }
  }

  if (!api->SetVariable("tessedit_char_whitelist", allChars.c_str())) {
    throw std::runtime_error("Could not set tesseract allowlist");
  }

  std::string text = text_;  //"what the heck, it's just some gay guy";
  // getline(std::cin, text);
  if (text.back() == '\r') {
    text.pop_back();
  }

  std::cout << "Calculating card list..." << std::endl;
  if (status_callback_) {
    status_callback_("Calculating card list...");
  }

  std::string canonText = hatkirby::lowercase(text);
  designer des(canonText, cards_.getTitles());

  Magick::Image endImage;
  bool success = false;
  for (int attempt = 0; attempt < 10; attempt++) {
    endImage = {};

    std::list<usage> res = des.generate(rng_);

    bool firstSlice = false;
    int ui = 0;

    bool failure = false;
    for (const usage& u : res) {
      const card& theCard = cards_.getCard(u.cardId);
      const std::string& cardName = theCard.name;

      std::cout << cardName.substr(0, u.strIndex) << "["
                << cardName.substr(u.strIndex, u.strLen) << "]"
                << cardName.substr(u.strIndex + u.strLen) << std::endl;

      std::cout << "Downloading image..." << std::endl;
      if (status_callback_) {
        std::ostringstream status_stream;
        status_stream << "Processing card " << (ui + 1) << "/" << res.size()
                      << " (attempt " << (attempt + 1) << ")...";
        status_callback_(status_stream.str());
      }

      Magick::Image cardImg = images_.get(theCard.uuid, theCard.imageUri);

      std::cout << "Reading text..." << std::endl;

      Magick::Image titleImg = cardImg;
      titleImg.magick("TIFF");

      // titleImg.threshold(MaxRGB / 2);
      titleImg.write("pre.tif");

      Magick::Geometry margin;

      if (theCard.frame == card_frame::m2015) {
        margin = Magick::Geometry{595, 50, 57, 54};
      } else if (theCard.frame == card_frame::modern) {
        margin = Magick::Geometry{581, 50, 63, 57};
      }

      titleImg.crop(margin);
      titleImg.zoom({margin.width() * 5, margin.height() * 5});

      // titleImg.quantizeColorSpace(Magick::GRAYColorspace);
      // titleImg.quantizeColors(2);
      // titleImg.quantize();
      titleImg.backgroundColor("white");
      titleImg.matte(false);
      titleImg.resolutionUnits(Magick::PixelsPerInchResolution);
      titleImg.density({300, 300});
      titleImg.type(Magick::GrayscaleType);
      titleImg.gamma(3);
      // titleImg.level(0.2, 0.8);

      titleImg.write("title.tif");

      Magick::Blob titleBlob;
      titleImg.write(&titleBlob);

      pix_ptr titlePix{pixReadMemTiff(
          reinterpret_cast<const unsigned char*>(titleBlob.data()),
          titleBlob.length(), 0)};

      api->SetImage(titlePix.get());
      api->Recognize(nullptr);

      tesseract::ResultIterator* ri = api->GetIterator();
      tesseract::PageIteratorLevel level = tesseract::RIL_TEXTLINE;
      bool foundName = false;
      size_t extraChars = 0;

      if (ri) {
        do {
          const char* line = ri->GetUTF8Text(level);

          if (line) {
            std::string lineStr(line);

            size_t leadin = hatkirby::lowercase(lineStr).find(
                hatkirby::lowercase((cardName)));
            if (leadin != std::string::npos) {
              foundName = true;
              extraChars = leadin;

              break;
            } /* else {
                std::cout << "WRONG: " << lineStr << std::endl;
              }*/
          }
        } while (ri->Next(level));
      }

      if (!foundName) {
        failure = true;
        break;
      }

      level = tesseract::RIL_SYMBOL;

      for (int i = 0; i < extraChars; i++) {
        ri->Next(level);
      }

      std::vector<std::tuple<unsigned int, unsigned int>> characters;
      size_t cur = 0;

      do {
        int x1, y1, x2, y2;
        ri->BoundingBox(level, &x1, &y1, &x2, &y2);

        x1 /= 5;
        x2 /= 5;

        if (cardName.at(cur) == ' ') {
          if (cur == 0) {
            characters.emplace_back(0, x1);
          } else {
            const auto& prev = characters.back();
            characters.emplace_back(std::get<1>(characters.back()), x1);
          }

          cur++;
        }

        characters.emplace_back(x1, x2);
        std::cout << characters.size() << " " << x1 << "," << x2 << " ("
                  << ri->GetUTF8Text(level) << ")" << std::endl;

        cur++;
      } while (ri->Next(level) && (cur < cardName.length()));

      if (cur != cardName.length()) {
        throw std::runtime_error("Error detecting character bounds");
      }

      Magick::Image bakImg = cardImg;

      unsigned int left = margin.xOff() + std::get<0>(characters[u.strIndex]);
      unsigned int right =
          margin.xOff() + std::get<1>(characters[u.strIndex + u.strLen - 1]);

      cardImg.crop({right - left, cardImg.rows(), left, 0});

      if (ui == 0) {
        bakImg.crop({margin.xOff(), bakImg.rows(), 0, 0});

        cardImg.extent({cardImg.columns() + bakImg.columns(), cardImg.rows()},
                       "black", Magick::GravityType::EastGravity);

        cardImg.composite(bakImg, 0, 0);
      } else if (ui == (res.size() - 1)) {
        bakImg.crop(
            {bakImg.columns() - margin.xOff() - std::get<1>(characters.back()),
             bakImg.rows(), margin.xOff() + std::get<1>(characters.back()), 0});

        int xoff = cardImg.columns();

        cardImg.extent({cardImg.columns() + bakImg.columns(), cardImg.rows()});

        cardImg.composite(bakImg, xoff, 0);
      }

      cardImg.magick("PNG");
      cardImg.write("slice.png");

      if (!firstSlice) {
        firstSlice = true;
        endImage = cardImg;

        if (theCard.frame == card_frame::m2015) {
          // endImage.extent({endImage.columns(), endImage.rows() + 6},
          // Magick::SouthGravity);
        }
      } else {
        int xoff = endImage.columns();

        endImage.backgroundColor("black");

        endImage.extent(
            {endImage.columns() + cardImg.columns(), cardImg.rows()},
            Magick::WestGravity);

        endImage.composite(cardImg, xoff,
                           (theCard.frame == card_frame::m2015) ? 6 : 0);
      }

      // break;
      ui++;
    }

    if (!failure) {
      success = true;
      break;
    }
  }

  if (!success) {
    throw std::domain_error("Could not generate card");
  }

  endImage.magick("PNG");

  return endImage;
}