comparison templates/dictionary.cpp @ 0:a4671277546c tip

created the repository for the thymian project
author ferencd
date Tue, 17 Aug 2021 11:19:54 +0200
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:a4671277546c
1 #include "dictionary.h"
2
3 #include <tntdb.h>
4 #include <boost/algorithm/string.hpp>
5
6 const std::vector<std::string> dictionary::supported_languages = {"gb", "no"};
7 std::map<std::string, std::map<std::string, std::string>> dictionary::m_inMemoryTranslations;
8
9 template<typename T>
10 std::string join(const std::vector<T> in,
11 const std::string & separator =", ", // see 1.
12 const std::string & concluder =" ") // see 1.
13 {
14 std::ostringstream ss;
15 std::size_t i = 0;
16 for(; i<in.size() - 1; i++)
17 {
18 ss << in[i] << separator;
19 }
20
21 ss << in[i] << concluder;
22 return ss.str();
23 }
24
25 std::string dictionary::translate(const std::string & what, const std::string &target_language, bool other_languages_too, std::map<std::string, std::string> &translations)
26 {
27 std::string result_translation;
28 bool found = false;
29
30 try {
31 tntdb::Connection conn = tntdb::connect("sqlite:lang.db");
32
33 // TODO: prepared statement
34
35 std::string v = "select " + join(supported_languages) + " from translations where source='" + what + "'";
36 tntdb::Result result = conn.select(v);
37 for (tntdb::Result::const_iterator it = result.begin(); it != result.end(); ++it)
38 {
39 tntdb::Row row = *it;
40
41 for(size_t i=0; i<row.size(); i++)
42 {
43 std::string row_name = boost::to_lower_copy(row.getName(i));
44
45 if(other_languages_too)
46 {
47 std::string temp;
48 row[i].get(temp);
49 translations[row_name] = temp;
50 }
51
52 if(row_name == boost::to_lower_copy(target_language))
53 {
54 row[i].get(result_translation);
55 found = true;
56 }
57 }
58 }
59
60 }
61 catch (std::exception& ex)
62 {
63 std::cerr << ex.what();
64 return "";
65 }
66
67 if(!found)
68 {
69 if(m_inMemoryTranslations.count(what))
70 {
71 for(const auto& l : supported_languages)
72 {
73 if(m_inMemoryTranslations[what].count(l))
74 {
75 translations[l] = m_inMemoryTranslations[what][l];
76 }
77 }
78 if(m_inMemoryTranslations[what].count(target_language))
79 {
80 result_translation = m_inMemoryTranslations[what][target_language];
81 }
82 }
83 }
84
85 return result_translation;
86 }
87
88 std::string dictionary::translate(const std::string &what, const std::string &target_language)
89 {
90 std::map<std::string, std::string> translations;
91 return translate(what, target_language, false, translations);
92 }
93
94 void dictionary::add_translation(const std::string &key, const std::string &language, const std::string &translated)
95 {
96 m_inMemoryTranslations[key][language] = translated;
97 }