mirror of
https://github.com/open-mmlab/mmdeploy.git
synced 2025-01-14 08:09:43 +08:00
* check in cmake * move backend_ops to csrc/backend_ops * check in preprocess, model, some codebase and their c-apis * check in CMakeLists.txt * check in parts of test_csrc * commit everything else * add readme * update core's BUILD_INTERFACE directory * skip codespell on third_party * update trt_net and ort_net's CMakeLists * ignore clion's build directory * check in pybind11 * add onnx.proto. Remove MMDeploy's dependency on ncnn's source code * export MMDeployTargets only when MMDEPLOY_BUILD_SDK is ON * remove useless message * target include directory is wrong * change target name from mmdeploy_ppl_net to mmdeploy_pplnn_net * skip install directory * update project's cmake * remove useless code * set CMAKE_BUILD_TYPE to Release by force if it isn't set by user * update custom ops CMakeLists * pass object target's source lists * fix lint end-of-file * fix lint: trailing whitespace * fix codespell hook * remove bicubic_interpolate to csrc/backend_ops/ * set MMDEPLOY_BUILD_SDK OFF * change custom ops build command * add spdlog installation command * update docs on how to checkout pybind11 * move bicubic_interpolate to backend_ops/tensorrt directory * remove useless code * correct cmake * fix typo * fix typo * fix install directory * correct sdk's readme * set cub dir when cuda version < 11.0 * change directory where clang-format will apply to * fix build command * add .clang-format * change clang-format style from google to file * reformat csrc/backend_ops * format sdk's code * turn off clang-format for some files * add -Xcompiler=-fno-gnu-unique * fix trt topk initialize * check in config for sdk demo * update cmake script and csrc's readme * correct config's path * add cuda include directory, otherwise compile failed in case of tensorrt8.2 * clang-format onnx2ncnn.cpp Co-authored-by: zhangli <lzhang329@gmail.com> Co-authored-by: grimoire <yaoqian@sensetime.com>
174 lines
4.9 KiB
C++
174 lines
4.9 KiB
C++
// Copyright (c) OpenMMLab. All rights reserved.
|
|
|
|
#include <sstream>
|
|
|
|
#include "core/device.h"
|
|
#include "core/model.h"
|
|
#include "core/registry.h"
|
|
#include "core/tensor.h"
|
|
#include "core/utils/formatter.h"
|
|
#include "core/value.h"
|
|
#include "experimental/module_adapter.h"
|
|
#include "mmocr.h"
|
|
|
|
namespace mmdeploy::mmocr {
|
|
|
|
using std::string;
|
|
using std::vector;
|
|
|
|
class CTCConvertor : public MMOCRPostprocess {
|
|
public:
|
|
explicit CTCConvertor(const Value& cfg) : MMOCRPostprocess(cfg) {
|
|
auto model = cfg["context"]["model"].get<Model>();
|
|
// BaseConverter
|
|
if (cfg.contains("dict_file")) {
|
|
auto filename = cfg["dict_file"].get<std::string>();
|
|
auto content = model.ReadFile(filename).value();
|
|
idx2char_ = SplitLines(content);
|
|
} else if (cfg.contains("dict_list")) {
|
|
from_value(cfg["dict_list"], idx2char_);
|
|
} else if (cfg.contains("dict_type")) {
|
|
auto dict_type = cfg["dict_type"].get<std::string>();
|
|
if (dict_type == "DICT36") {
|
|
idx2char_ = SplitChars(DICT36);
|
|
} else if (dict_type == "DICT90") {
|
|
idx2char_ = SplitChars(DICT90);
|
|
} else {
|
|
ERROR("unknown dict_type: {}", dict_type);
|
|
throw_exception(eInvalidArgument);
|
|
}
|
|
} else {
|
|
ERROR("either dict_file, dict_list or dict_type must be specified");
|
|
throw_exception(eInvalidArgument);
|
|
}
|
|
// CTCConverter
|
|
idx2char_.insert(begin(idx2char_), "<BLK>");
|
|
|
|
if (cfg.value("with_unknown", false)) {
|
|
unknown_idx_ = static_cast<int>(idx2char_.size());
|
|
idx2char_.emplace_back("<UKN>");
|
|
}
|
|
|
|
model_ = model;
|
|
}
|
|
|
|
Result<Value> operator()(const Value& _data, const Value& _prob) {
|
|
// auto img = _data["img"].get<Tensor>();
|
|
// WARN("img shape: {}", img.shape());
|
|
|
|
auto d_conf = _prob["output"].get<Tensor>();
|
|
std::vector<float> h_conf;
|
|
|
|
float* data{};
|
|
if (d_conf.device() != kHost) {
|
|
h_conf.resize(d_conf.byte_size() / sizeof(float));
|
|
OUTCOME_TRY(d_conf.CopyTo(h_conf.data(), stream_));
|
|
OUTCOME_TRY(stream_.Wait());
|
|
data = h_conf.data();
|
|
} else {
|
|
OUTCOME_TRY(stream_.Wait());
|
|
data = d_conf.data<float>();
|
|
}
|
|
|
|
auto shape = d_conf.shape();
|
|
auto w = static_cast<int>(shape[1]);
|
|
auto c = static_cast<int>(shape[2]);
|
|
|
|
auto valid_ratio = _data["img_metas"]["valid_ratio"].get<float>();
|
|
auto [indexes, scores] = Tensor2Idx(data, w, c, valid_ratio);
|
|
|
|
auto text = Idx2Str(indexes);
|
|
DEBUG("text: {}", text);
|
|
|
|
TextRecognizerOutput output{text, scores};
|
|
|
|
return make_pointer(to_value(output));
|
|
}
|
|
|
|
static std::pair<vector<int>, vector<float> > Tensor2Idx(const float* data, int w, int c,
|
|
float valid_ratio) {
|
|
auto decode_len = static_cast<int>(std::ceil(w * valid_ratio));
|
|
vector<int> indexes;
|
|
indexes.reserve(decode_len);
|
|
vector<float> scores;
|
|
scores.reserve(decode_len);
|
|
vector<float> prob(c);
|
|
int prev = blank_idx_;
|
|
for (int t = 0; t < decode_len; ++t, data += c) {
|
|
softmax(data, prob.data(), c);
|
|
auto iter = max_element(begin(prob), end(prob));
|
|
auto index = static_cast<int>(iter - begin(prob));
|
|
if (index != 0 && index != prev) {
|
|
indexes.push_back(index);
|
|
scores.push_back(*iter);
|
|
}
|
|
prev = index;
|
|
}
|
|
return {indexes, scores};
|
|
}
|
|
|
|
string Idx2Str(const vector<int>& indexes) {
|
|
size_t count = 0;
|
|
for (const auto& idx : indexes) {
|
|
count += idx2char_[idx].size();
|
|
}
|
|
std::string text;
|
|
text.reserve(count);
|
|
for (const auto& idx : indexes) {
|
|
text += idx2char_[idx];
|
|
}
|
|
return text;
|
|
}
|
|
|
|
// TODO: move softmax & top-k into model
|
|
static void softmax(const float* src, float* dst, int n) {
|
|
auto max_val = *std::max_element(src, src + n);
|
|
float sum{};
|
|
for (int i = 0; i < n; ++i) {
|
|
dst[i] = std::exp(src[i] - max_val);
|
|
sum += dst[i];
|
|
}
|
|
for (int i = 0; i < n; ++i) {
|
|
dst[i] /= sum;
|
|
}
|
|
}
|
|
|
|
protected:
|
|
static vector<string> SplitLines(const string& s) {
|
|
std::istringstream is(s);
|
|
vector<string> ret;
|
|
string line;
|
|
while (std::getline(is, line)) {
|
|
ret.push_back(std::move(line));
|
|
}
|
|
return ret;
|
|
}
|
|
|
|
static vector<string> SplitChars(const string& s) {
|
|
vector<string> ret;
|
|
ret.reserve(s.size());
|
|
for (char c : s) {
|
|
ret.push_back({c});
|
|
}
|
|
return ret;
|
|
}
|
|
|
|
static constexpr const auto DICT36 = R"(0123456789abcdefghijklmnopqrstuvwxyz)";
|
|
static constexpr const auto DICT90 = R"(0123456789abcdefghijklmnopqrstuvwxyz)"
|
|
R"(ABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'())"
|
|
R"(*+,-./:;<=>?@[\]_`~)";
|
|
|
|
static constexpr const auto kHost = Device(0);
|
|
|
|
Model model_;
|
|
|
|
static constexpr const int blank_idx_{0};
|
|
int unknown_idx_{-1};
|
|
|
|
vector<string> idx2char_;
|
|
};
|
|
|
|
REGISTER_CODEBASE_MODULE(MMOCRPostprocess, CTCConvertor);
|
|
|
|
} // namespace mmdeploy::mmocr
|