-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
1979 lines (1861 loc) · 62.4 KB
/
main.cpp
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "main.hpp"
#include "arg.h"
#include "common.h"
#include "llama.h"
#include "parser.hpp"
#include <algorithm>
#include <bit>
#include <chrono>
#include <csignal>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <memory>
#include <mutex>
#include <numeric>
#include <span>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
#include <fcntl.h>
#include <sys/types.h>
#ifndef _WIN32
#include <sys/mman.h>
#include <sys/resource.h>
#include <unistd.h>
#else
#ifndef NOMINMAX
#define NOMINMAX
#endif
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
#ifdef _MSC_VER
#include <intrin.h>
#else
#include <x86intrin.h>
#endif
#include <emmintrin.h>
#include <immintrin.h>
static_assert("か"sv == "\xE3\x81\x8B"sv, "This source file shall be compiled as UTF-8 text");
// Exit flag
volatile bool g_stop = false;
// Guiding prefix for original lines of text
std::string iprefix = "JP: ";
// En: prefix doesn't contain a space, for an interesting reason.
// For Chinese models it may turn into an explicit space token.
// In English text such token usually doesn't appear.
// However, it may appear in Chinese texts as a delimiter.
// This may provoke Chinese-speaking model to output Chinese.
std::string isuffix = "En:";
std::string g_neg;
// Translation example injected after prompt
std::string example = "JP: この物語はフィクションです。\n"
"En: This story is a work of fiction.\n";
std::string cache_prefix;
// Print line, return original speaker name if first encountered
std::string print_line(line_id id, std::string* line = nullptr, bool stream = false)
{
std::string out = apply_replaces(g_lines[id].text, false, 0);
std::string speaker;
if (g_lines[id].name.starts_with("選択肢#")) {
// Insert translated choice selection prefix
speaker += " Choice ";
speaker += g_lines[id].name.substr("選択肢#"sv.size());
} else if (!g_lines[id].name.empty()) {
// Find registered speaker translation
std::lock_guard lock(g_mutex);
const auto& found = g_dict.at(g_lines[id].name);
if (!found.first.empty()) {
speaker += " ";
speaker += found.first;
}
}
if (g_mode == op_mode::print_only) {
// Passthrough mode (print-only): add \ for multiline input
std::cout << iprefix << g_lines[id].name << out << "\\" << std::endl;
// Add Ctrl+D for same-line output
std::cout << isuffix << speaker << "\04" << std::flush;
}
if (stream) {
// Print colored output without prefixes
std::cout << g_esc.orig << *line << g_lines[id].name << out << g_esc.reset << std::endl;
}
if (line) {
line->append(iprefix);
line->append(g_lines[id].name);
line->append(out);
line->append("\n");
}
return speaker;
}
std::u16string squeeze_line(const std::string& line)
{
// For opportunistic compatibility with "bad" hooks which repeat characters, or remove repeats
std::u16string r;
std::string_view next;
char16_t prev{};
for (const char& c : line) {
next = {};
char32_t utf32 = 0;
// Decode UTF-8 sequence
if ((c & 0x80) == 0) {
next = std::string_view(&c, 1);
utf32 = c;
} else if ((c & 0xe0) == 0xc0) {
next = std::string_view(&c, 2);
utf32 = (c & 0x1f);
} else if ((c & 0xf0) == 0xe0) {
next = std::string_view(&c, 3);
utf32 = (c & 0x0f);
} else if ((c & 0xf8) == 0xf0) {
next = std::string_view(&c, 4);
utf32 = (c & 0x07);
}
for (auto& ch : next) {
// Check for null terminator (`next` could be out of bounds)
if (ch == 0)
return r;
if (&ch > next.data() && (ch & 0xc0) != 0x80) {
// Invalid UTF-8 sequence
next = {};
prev = 0;
break;
}
if (&ch > next.data()) {
utf32 <<= 6;
utf32 |= (ch & 0x3f);
}
}
// Saturate and normalize full-width to ASCII
char16_t utf16 = std::min(utf32, U'\xffff');
if (utf16 >= u'!' && utf16 <= u'~')
utf16 -= u'!' - '!';
if (!next.empty() && utf16 != prev) {
// Skip spaces (both ASCII and full-width) and control characters
if (next == " "sv || next == " "sv)
continue;
if (next[0] + 0u < 32 || next[0] == '\x7f') {
prev = 0;
continue;
}
// Append non-repeating code
r += utf16;
prev = utf16;
}
}
return r;
}
std::u32string to_utf32(const std::string& line)
{
std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> converter;
return converter.from_bytes(line);
}
std::string to_utf8(const std::u32string& line)
{
std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> converter;
return converter.to_bytes(line);
}
// Return the "cost" of changing strings s to t
// Implementation of https://en.wikipedia.org/wiki/Levenshtein_distance#Iterative_with_two_matrix_rows
uint levenshtein_distance(std::u16string_view s, std::u16string_view t)
{
if ((s.size() | t.size()) > 255)
throw std::out_of_range("levenshtein_distance: strings too big");
std::array<unsigned char, 256> v1_, v0_;
auto v0 = v0_.data();
auto v1 = v1_.data();
for (uint i = 0; i < t.size() + 1; i++)
v0[i] = i;
for (uint i = 0; i < s.size(); i++) {
v1[0] = i + 1;
for (uint j = 0; j < t.size(); j++) {
const uint del_cost = v0[j + 1] + 1;
const uint ins_cost = v1[j] + 1;
const uint sub_cost = v0[j] + (s[i] != t[j]);
v1[j + 1] = std::min({del_cost, ins_cost, sub_cost});
}
std::swap(v0, v1);
}
return v0[t.size()];
}
// Stored "columns" of g_strings for linear memory access
static std::vector<std::vector<char16_t>> s_char_columns(255);
// Return vector of the most matching strings
std::vector<std::u16string_view> levenshtein_distance(uint skip, std::span<const std::u16string_view> span, std::u16string_view t, uint last = -1)
{
std::vector<std::u16string_view> result;
const auto pitch = (span.size() + 31) & -32;
const auto flat_size = pitch * (t.size() + 1);
static constexpr auto av = std::align_val_t{32};
auto v0_flat = new (av) unsigned char[flat_size];
auto v1_flat = new (av) unsigned char[flat_size];
char16_t* ith = nullptr;
for (uint i = 0; i < t.size() + 1; i++) {
std::memset(v0_flat + i * pitch, i, pitch);
}
std::size_t max_str = span.empty() ? 0 : span[0].size();
std::size_t min_str = 1;
uint k0 = 0;
uint k1 = span.size();
for (uint i = 0; i < max_str; i++) {
ith = s_char_columns[i].data() + skip;
auto v0j = v0_flat;
auto v0j2 = v0j + pitch;
auto v1j = v1_flat;
auto v1j2 = v1j + pitch;
#if defined(__SSE2__)
for (uint k = k0 & -16; k < k1; k += 16) {
_mm_store_si128((__m128i*)(v1j + k), _mm_set1_epi8(i + 1));
}
#else
std::memset(v1j + k0, i + 1, k1 - k0);
#endif
for (uint j = 0; j < t.size(); j++) {
#if defined(__AVX2__)
auto tj = _mm256_set1_epi16(t[j]);
for (uint k = k0 & -31; k < k1; k += 32) {
auto del_cost = _mm256_add_epi8(_mm256_load_si256((const __m256i*)(v0j2 + k)), _mm256_set1_epi8(1));
auto ins_cost = _mm256_add_epi8(_mm256_load_si256((const __m256i*)(v1j + k)), _mm256_set1_epi8(1));
auto m0 = _mm256_cmpeq_epi16(_mm256_loadu_si256((const __m256i_u*)(ith + k)), tj);
auto m1 = _mm256_cmpeq_epi16(_mm256_loadu_si256((const __m256i_u*)(ith + k + 16)), tj);
auto value = _mm256_add_epi8(_mm256_load_si256((const __m256i*)(v0j + k)), _mm256_set1_epi8(1));
auto mask = _mm256_permute4x64_epi64(_mm256_packs_epi16(m0, m1), 0xd8);
auto sub_cost = _mm256_add_epi8(value, mask);
auto min_cost = _mm256_min_epu8(_mm256_min_epu8(del_cost, ins_cost), sub_cost);
_mm256_store_si256((__m256i*)(v1j2 + k), min_cost);
}
#elif defined(__SSE2__)
auto tj = _mm_set1_epi16(t[j]);
for (uint k = k0 & -16; k < k1; k += 16) {
auto del_cost = _mm_add_epi8(_mm_load_si128((const __m128i*)(v0j2 + k)), _mm_set1_epi8(1));
auto ins_cost = _mm_add_epi8(_mm_load_si128((const __m128i*)(v1j + k)), _mm_set1_epi8(1));
auto m0 = _mm_cmpeq_epi16(_mm_loadu_si128((const __m128i_u*)(ith + k)), tj);
auto m1 = _mm_cmpeq_epi16(_mm_loadu_si128((const __m128i_u*)(ith + k + 8)), tj);
auto value = _mm_add_epi8(_mm_load_si128((const __m128i*)(v0j + k)), _mm_set1_epi8(1));
auto mask = _mm_packs_epi16(m0, m1);
auto sub_cost = _mm_add_epi8(value, mask);
auto min_cost = _mm_min_epu8(_mm_min_epu8(del_cost, ins_cost), sub_cost);
_mm_store_si128((__m128i*)(v1j2 + k), min_cost);
}
// auto tj = _mm512_set1_epi16(t[j]);
// for (uint k = k0 & -63; k < k1; k += 64) {
// auto del_cost = _mm512_add_epi8(_mm512_load_epi8(v0j2 + k), _mm512_set1_epi8(1));
// auto ins_cost = _mm512_add_epi8(_mm512_load_epi8(v1j + k), _mm512_set1_epi8(1));
// __mmask64 mask = _mm512_cmp_epi16_mask(_mm512_loadu_epi16(ith + k), tj, _MM_CMPINT_NE);
// __mmask64 mask2 = _mm512_cmp_epi16_mask(_mm512_loadu_epi16(ith + k + 32), tj, _MM_CMPINT_NE);
// mask |= mask2 << 32;
// auto value = _mm512_load_epi8(v0j + k);
// auto sub_cost = _mm512_mask_add_epi8(value, mask, value, _mm512_set1_epi8(1));
// auto min_cost = _mm512_min_epu8(_mm512_min_epu8(del_cost, ins_cost), sub_cost);
// _mm512_store_epi8(v1j2 + k, min_cost);
// }
#else
for (uint k = k0; k < k1; k++) {
uint del_cost = v0j2[k] + 1;
uint ins_cost = v1j[k] + 1;
uint sub_cost = v0j[k] + (ith[k] != t[j]);
v1j2[k] = std::min({del_cost, ins_cost, sub_cost});
}
#endif
v0j += pitch;
v0j2 += pitch;
v1j += pitch;
v1j2 += pitch;
}
for (uint k = k0; k < k1; k++) {
auto s = span[k];
if (i + 1 == s.size()) {
const uint res = v1j[k];
//if (res != levenshtein_distance(s, t))
// throw std::runtime_error("Batch failed: " + std::to_string(res));
if (res < last) {
last = res;
result.clear();
}
if (res == last) {
result.push_back(s);
if (res != levenshtein_distance(s, t))
throw std::runtime_error("Bug: levenshtein_distance batch failed.");
}
// TODO: fix optimizations
//max_str = std::min(max_str, last + s.size());
// if (s.size() > last)
// min_str = std::max(min_str, s.size() - last);
//if (s.size() > max_str)
// k0 = std::max(k0, k + 1);
// while (s.size() < min_str) {
// k1 = k;
// s = span[--k];
// }
}
}
std::swap(v0_flat, v1_flat);
}
operator delete[](v0_flat, av);
operator delete[](v1_flat, av);
return result;
}
namespace fs = std::filesystem;
static std::string names_path, replaces_path;
static fs::path vnsleuth_path;
void update_names(const std::string& path)
{
if (path.empty())
return;
const auto path_tmp = path + ".tmp";
std::ofstream names(path_tmp, std::ios_base::trunc);
if (names.is_open()) {
for (auto& [orig, pair] : g_dict) {
if (pair.first != ":")
names << orig << pair.first << pair.second << "\n";
else
names << orig << "\n";
}
names.close();
fs::rename(path_tmp, path);
// Workaround to make translation files always appear as last modified
fs::last_write_time(path, fs::last_write_time(path) - 1s);
} else {
std::cerr << "Failed to open: " << path << ".tmp" << std::endl;
}
}
bool update_segment(uint seg, bool upd_names = true, uint count = -1)
{
std::lock_guard lock(g_mutex);
if (upd_names) {
update_names(names_path);
}
std::string dump = "SRC:";
dump += g_lines.segs[seg].src_name;
dump += '\n';
for (auto& name : g_lines.segs[seg].prev_segs) {
dump += "PREV:";
dump += name;
dump += '\n';
}
for (auto& line : g_lines.segs[seg].lines) {
if (count == 0)
break;
if (line.tr_text.empty())
break;
dump += line.tr_text;
count--;
}
if (count)
dump += g_lines.segs[seg].tr_tail;
auto tmp = vnsleuth_path / (g_lines.segs[seg].cache_name + ".tmp");
std::ofstream file(tmp, std::ios_base::trunc | std::ios_base::binary);
if (!file.is_open()) {
std::cerr << "Failed to open " << g_lines.segs[seg].cache_name << ".tmp" << std::endl;
return false;
}
file.write(dump.data(), dump.size());
file.close();
auto dst = vnsleuth_path / g_lines.segs[seg].cache_name;
fs::rename(tmp, dst);
if (!upd_names)
fs::last_write_time(dst, fs::last_write_time(dst) + 1s * seg);
return true;
}
std::pair<uint, uint> load_translation(uint seg, const fs::path& path, bool verify = false)
{
std::ifstream cache(path);
if (!cache.is_open()) {
std::cerr << "Failed to open " << path << std::endl;
return std::make_pair(0, 0);
}
// Extract translation
line_id id{seg, 0};
std::string temp, text;
uint kept = 0;
bool keep = true;
bool is_broken = false;
g_lines.segs[seg].prev_segs.clear();
while (std::getline(cache, temp, '\n')) {
if (temp.starts_with("SRC:")) {
continue;
}
if (temp.starts_with("PREV:")) {
g_lines.segs[seg].prev_segs.emplace_back(std::move(temp)).erase(0, 5);
continue;
}
text += temp;
text += '\n';
if (id != c_bad_id && temp.starts_with(iprefix)) {
std::string expected = iprefix;
expected += g_lines[id].name;
expected += g_lines[id].text;
if (temp != expected) {
is_broken = true;
if (g_mode == op_mode::print_info) {
// Repair
text.resize(text.size() - temp.size() - 1);
text += expected;
text += '\n';
} else {
// Consider broken, append everything to tail
while (std::getline(cache, temp, '\n')) {
text += temp;
text += '\n';
}
break;
}
}
while (std::getline(cache, temp, '\n')) {
// Store both original and translated lines as a single string
text += temp;
text += '\n';
if (!temp.starts_with(isuffix))
continue;
auto old = std::move(g_lines[id].tr_text);
g_lines[id].tr_text = std::move(text);
if (keep && g_lines[id].tr_text == old) {
kept++;
} else {
g_lines[id].tr_tts.clear();
keep = false;
}
g_lines.advance(id);
break;
}
}
}
// Clear remaining lines
for (auto id2 = id; id2 != c_bad_id; g_lines.advance(id2)) {
if (!g_lines[id2].tr_text.empty()) {
keep = false;
}
g_lines[id2].tr_text = {};
g_lines[id2].tr_tts.clear();
}
// Check and load what remains in the file
auto old = std::move(g_lines.segs[seg].tr_tail);
g_lines.segs[seg].tr_tail = std::move(text);
if (keep)
kept = -1;
return std::make_pair(id.second, verify ? !is_broken : kept);
}
void sigh(int) { g_stop = true; }
int main(int argc, char* argv[])
{
if (std::getenv("VNSLEUTH_COREDUMP")) {
rlimit lim{rlim_t(-1), rlim_t(-1)};
setrlimit(RLIMIT_CORE, &lim);
}
g_mode = op_mode::rt_llama;
if (argc == 2) {
g_mode = op_mode::rt_cached;
} else if (argc >= 3 && argv[2] == "--legacy"sv) {
g_mode = op_mode::print_only;
} else if (argc >= 3 && (argv[2] == "--check"sv || argv[2] == "--repair"sv)) {
g_mode = op_mode::print_info;
}
static const auto argv_ = argv;
static const auto print_usage = [](int, char**) {
auto argv = argv_;
std::cerr << "VNSleuth v0.5" << std::endl;
std::cerr << "Usage 0: " << argv[0] << " <game_directory> --color" << std::endl;
std::cerr << "\tUse existing translation only (only useful if it's complete)." << std::endl;
std::cerr << "Usage 1: " << argv[0] << " <game_directory> --check" << std::endl;
std::cerr << "\tPrint furigana, some information, initialize translation directory." << std::endl;
std::cerr << "Usage 2: " << argv[0] << " <game_directory> --color -m <model> [<LLAMA args>...]" << std::endl;
std::cerr << "\tStart translating in real time (recommended)." << std::endl;
std::cerr << "Nothing to do." << std::endl;
};
if (argc < 2 || argv[1] == "--help"sv) {
print_usage(argc, argv);
return 1;
}
common_params params{};
params.n_gpu_layers = 999;
params.speculative.n_gpu_layers = 999;
params.flash_attn = 1; // FA is currently NEEDED for efficient GPU KV-cache saving/restoring
//params.cache_type_k = "q8_0";
//params.cache_type_v = "q8_0";
params.n_ctx = 4096;
params.n_batch = 2048;
params.n_predict = 128;
params.sampling.seed = 0;
params.sampling.temp = 0.2;
params.sampling.top_p = 0.3;
params.sampling.penalty_last_n = 64;
params.sampling.penalty_repeat = 1.1;
params.warmup = false;
params.model = ".";
params.speculative.model = "";
// Basic param check
std::string dir_name = argv[1];
if (argc > 2) {
argc--;
argv++;
if (g_mode == op_mode::print_only || g_mode == op_mode::print_info) {
argc--;
argv++;
}
if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_SPECULATIVE, print_usage)) {
return 1;
}
// Disable colors
if (!params.use_color)
g_esc.disable();
// Allow replacing translation prefix/suffix
if (!params.input_prefix.empty())
iprefix = std::move(params.input_prefix);
if (!params.input_suffix.empty())
isuffix = std::move(params.input_suffix);
if (!params.prompt.empty()) {
example = std::move(params.prompt);
REPLACE(example, "\r", "");
if (!example.ends_with("\n"))
example += '\n';
}
if (g_mode == op_mode::rt_llama && params.model == ".")
g_mode = op_mode::rt_cached;
}
// Parse scripts in a given directory
std::string line, prompt_path;
bool is_incomplete = false;
bool is_broken = false;
// Load file list recursively
cache_prefix = fs::path(dir_name).filename();
vnsleuth_path = fs::absolute(fs::path(dir_name)).lexically_normal() / "__vnsleuth";
std::map<std::string, std::size_t, natural_order_less> file_list;
if (fs::is_directory(dir_name)) {
fs::create_directory(vnsleuth_path);
for (const auto& entry : fs::recursive_directory_iterator(vnsleuth_path.parent_path(), fs::directory_options::follow_directory_symlink)) {
if (entry.is_regular_file()) {
// Skip __vnsleuth directory entirely
const auto fname = entry.path().string();
if (fname.starts_with(vnsleuth_path.c_str()))
continue;
// Check file size
const auto size = entry.file_size();
if (size > 10)
file_list.emplace(entry.path(), size);
}
}
} else if (fs::is_regular_file(dir_name) && dir_name.ends_with(".txt")) {
// a.txt creates ./a/__vnsleuth/
vnsleuth_path = fs::absolute(fs::path(dir_name - ".txt")).lexically_normal() / "__vnsleuth";
fs::create_directories(vnsleuth_path);
} else {
std::cerr << "Not a directory: " << dir_name << std::endl;
return 1;
}
replaces_path = vnsleuth_path / "__vnsleuth_replace.txt";
prompt_path = vnsleuth_path / "__vnsleuth_prompt.txt";
names_path = vnsleuth_path / "__vnsleuth_names.txt";
// Open stat file for writing via memory map
std::shared_ptr<void> stats_ptr;
int stats_fd = open((vnsleuth_path / "__vnsleuth_stats").c_str(), O_CREAT | O_RDWR, 0666);
if (stats_fd != -1 && ftruncate(stats_fd, alignof(vnsleuth_stats)) != -1) {
stats_ptr = std::shared_ptr<void>(mmap(0, alignof(vnsleuth_stats), PROT_READ | PROT_WRITE, MAP_SHARED, stats_fd, 0), [=](void* ptr) {
munmap(ptr, alignof(vnsleuth_stats));
close(stats_fd);
});
} else {
perror("Failed to create __vnsleuth_stats");
stats_ptr = std::make_shared<vnsleuth_stats>();
}
g_stats = static_cast<vnsleuth_stats*>(stats_ptr.get());
if (g_mode == op_mode::rt_llama) {
ui64 z = 0;
g_stats->start_time.compare_exchange_strong(z, std::time(nullptr));
}
if (prompt_path.empty() || !fs::is_regular_file(prompt_path)) {
std::cerr << "Translation prompt not found: " << prompt_path << std::endl;
if (!prompt_path.empty()) {
// Create dummy prompt
std::ofstream p(prompt_path, std::ios_base::trunc);
if (p.is_open()) {
p << "This is an accurate translation of a Japanese novel to English." << std::endl;
p << "Line starting with En: only contains the translation of the preceding JP: line." << std::endl;
p << "All honorifics are always preserved as -san, -chan, -sama, etc." << std::endl;
p << "<START>" << std::endl;
p.close();
std::cerr << "Dummy translation prompt created: " << prompt_path << std::endl;
}
}
}
auto reload_names = [&]() -> bool {
// Load (pre-translated) names
std::lock_guard lock(g_mutex);
std::ifstream names(names_path);
if (names.is_open()) {
auto old = std::move(g_dict);
while (std::getline(names, line, '\n')) {
REPLACE(line, "\r", "");
if (const auto pos0 = line.find_first_of(":") + 1) {
const auto pos1 = line.find_first_of(":", pos0);
if (pos1 + 1 == 0) {
// Untranslated name only
if (pos0 != line.size()) {
std::cerr << "Incorrect name formatting: " << line << std::endl;
continue;
}
g_dict[std::move(line)];
continue;
}
g_dict.emplace(line.substr(0, pos0), std::make_pair(line.substr(pos0, pos1 + 1 - pos0), line.substr(pos1 + 1)));
} else {
std::cerr << "Incorrect name formatting: " << line << std::endl;
}
}
return g_dict != old;
} else {
std::cerr << "Translation names not found: " << names_path << std::endl;
return false;
}
};
if (!names_path.empty()) {
reload_names();
}
auto reload_replaces = [&]() -> std::size_t {
g_replaces = g_default_replaces;
if (!replaces_path.empty()) {
// Load replacement rules
std::ifstream strs(replaces_path);
if (strs.is_open()) {
std::size_t count = 0;
while (std::getline(strs, line, '\n')) {
REPLACE(line, "\r", "");
const bool a = std::count(line.cbegin(), line.cend(), ':') == 1;
const bool b = std::count(line.cbegin(), line.cend(), '=') == 1;
if (a ^ b) {
const auto pos = line.find_first_of(a ? ":" : "=");
std::string src(line.data(), pos);
std::string dst(line.data() + pos + 1);
// Override previous replace
std::erase_if(g_replaces, [&](auto& pair) { return pair.first == src; });
if (dst == src) {
// No-op replace
} else {
g_replaces.emplace_back(std::move(src), std::move(dst));
count++;
}
} else {
std::cerr << "Failed to parse replacement string: " << line << std::endl;
continue;
}
}
return count;
}
}
return 0;
};
// Analyze ExHIBIT script files to obtain "encryption" key
{
std::vector<std::string> to_analyze;
for (auto& [name, size] : file_list) {
if (name.ends_with(".rld")) {
std::string data;
data.resize(size > 0xffd0 ? 0xffd0 : size);
std::ifstream f(name, std::ios::binary);
if (f.is_open() && f.read(data.data(), data.size())) {
if (data.starts_with("\0DLR"sv)) {
to_analyze.emplace_back(std::move(data));
}
} else {
std::cerr << "Failed to read file: " << name << std::endl;
return 1;
}
}
}
std::array<uint, 1024 / 4> _key;
std::bitset<1024 / 4> conflict{};
for (uint i = 0; i < _key.size(); i++) {
uint bytes = 0;
// Raw bytes -> counter
std::unordered_map<uint, uint> stats;
for (auto& s : to_analyze) {
for (uint j = i * 4 + 16; j + 3 < s.size(); j += sizeof(_key)) {
std::memcpy(&bytes, s.data() + j, 4);
stats[bytes]++;
}
}
uint _max = 0;
for (auto& [seq, count] : stats) {
if (count > _max) {
bytes = seq;
_max = count;
}
}
uint sure = -1;
for (auto& [seq, count] : stats) {
if (count < _max)
sure = std::min(sure, _max - count);
if (count == _max && seq != bytes) {
conflict.set(i);
sure = 0;
}
}
if (sure < 10) {
std::cerr << "ExHIBIT: Key is ambiguous at position " << i * 4 << "+16" << std::endl;
conflict.set(i);
} else {
_key[i] = bytes;
}
}
if (conflict.none() && _key.size() - std::count(_key.begin(), _key.end(), 0)) {
std::fprintf(stderr, "ExHIBIT: key found: ");
for (auto& key : _key)
std::fprintf(stderr, "%08x", __builtin_bswap32(key));
std::fprintf(stderr, "\n");
extern char g_exhibit_key[1024];
std::memcpy(g_exhibit_key, _key.data(), sizeof(g_exhibit_key));
}
}
if (dir_name.ends_with(".txt") && file_list.empty()) {
// Load a single raw text file
std::ifstream txt(dir_name, std::ios::binary);
std::string data(fs::file_size(dir_name) + 1, '\n');
txt.read(data.data(), data.size() - 1);
auto& seg = g_lines.segs.emplace_back();
g_lines.segs_by_name[".txt"] = 0;
seg.src_name = ".txt";
seg.cache_name = "__vnsleuth_text.txt";
std::vector<std::u32string> lines{1};
std::u32string all_lines = to_utf32(data);
const bool no_squash = std::getenv("VNSLEUTH_NO_SQUASH");
for (std::size_t p = 0; p < all_lines.size();) {
const std::size_t end = all_lines.find_first_of(U"\n✏", p);
std::u32string line = all_lines.substr(p, end - p);
p = end + 1;
REPLACE(line, U"・・・", U"・・"); // Preprocess dot sequence (accent)
REPLACE(line, U"(・・)", U""); // Remove accent furigana
REPLACE(line, U"《・・》", U"");
REPLACE(line, U"(・・)", U"");
REPLACE(line, U"()", U""); // Remove empty furigana from certain formats
REPLACE(line, U"《》", U"");
REPLACE(line, U"()", U"");
// Trim spaces
line.resize(line.find_last_not_of(U" \t\r") + 1);
line.erase(0, line.find_first_not_of(U" \t"));
if (line.empty()) {
continue;
}
REPLACE(line, U" ", U" ");
REPLACE(line, U" ", U" ");
if (line.starts_with(U"<") && line.ends_with(U">")) {
// TODO: skip html
continue;
}
static auto is_jp = [](char32_t c) -> bool {
// TODO: revise
if ((c >= 0x3040 && c <= 0x30ff) || // Hiragana, katakana
(c >= 0x4e00 && c <= 0x9fff) || // CJK ideograms
(c >= 0xf900 && c <= 0xfaff) || //
(c >= 0xff65 && c <= 0xff9f)) // Halfwidth kana
return true;
return false;
};
// Remove padding ASCII spaces within Japanese text
for (std::size_t i = 0; i < line.size();) {
if (line[i] == ' ' && i) {
if (is_jp(line[i - 1]) || is_jp(line[i + 1])) {
line.erase(i, 1);
continue;
}
}
// Transform certain full-width character to ASCII (due to anecdotal improvement observation)
if (line[i] == U' ' && i && !is_jp(line[i - 1]) /*&& !is_jp(line[i + 1])*/)
line[i] = ' ';
if (line[i] == U'、' && i && !is_jp(line[i - 1]))
line[i] = ',';
if (line[i] == U'.' && i && !is_jp(line[i - 1]))
line[i] = '.';
if (line[i] == U''' && i && !is_jp(line[i - 1]))
line[i] = '\'';
if (line[i] == U'?' && i && !is_jp(line[i - 1]) && line[i - 1] != U'?' && line[i - 1] != U'!')
line[i] = '?';
if (line[i] == U'!' && i && !is_jp(line[i - 1]) && line[i - 1] != U'?' && line[i - 1] != U'!')
line[i] = '!';
if (line[i] == U':' && i && !is_jp(line[i - 1]))
line[i] = ':';
if (line[i] >= U'0' && line[i] <= U'9')
line[i] -= U'0' - '0';
if (line[i] >= U'A' && line[i] <= U'Z')
line[i] -= U'A' - 'A';
if (line[i] >= U'a' && line[i] <= U'z')
line[i] -= U'a' - 'a';
i++;
}
// Function to split too long strings
auto new_line = [&](std::u32string str) {
// When includes split indicator, real max_size is (max_size + 1)
static constexpr std::size_t max_size = 1023;
while (lines.back().size() > max_size + 1) {
std::size_t new_size = max_size;
// Find convenient split position (dot or comma)
for (auto delim : {U'。', U'、', U'.', U';', U','}) {
if (auto pos = lines.back().rfind(delim, max_size - 1) + 1) {
new_size = pos;
break;
}
}
// Trim starting spaces after split position
auto next = lines.back().substr(lines.back().find_first_not_of(U" \t", new_size));
lines.back().resize(new_size);
lines.back() += U'↴';
lines.emplace_back(std::move(next));
}
lines.emplace_back(std::move(str));
};
if (!line.empty() && !no_squash) {
// Check line squashing conditions
static constexpr std::array<char32_t, 3> braces[]{
U"「」", //
U"『』", //
U"【】", //
U"《》", //
U"〝〟", //
U"()", //
U"[]",
U"()", //
};
// Furigana, possibly ((thoughts))
static constexpr auto excl_braces = U"《(("sv;
static auto is_open = [](std::u32string_view str) -> int {
std::u32string stack;
for (auto& c : str) {
for (auto& [open, close, _] : braces) {
if (c == open) {
stack.push_back(close);
} else if (c == close) {
while (!stack.ends_with(close)) {
if (stack.empty())
return -1;
stack.pop_back();
}
stack.pop_back();
}
}
}
return !stack.empty();
};
static auto has_speech = [](std::u32string_view str) -> bool {
for (auto& arr : braces) {
if (excl_braces.find_first_of(arr[0]) + 1)
continue;
if (str.find_first_of(arr.data()) + 1)
return true;
}
return false;
};
static auto start_speech = [](std::u32string_view str, bool full = false) -> bool {
for (auto& [open, close, _] : braces) {
if (!full && excl_braces.find_first_of(open) + 1)
continue;
if (str.starts_with(open))
return true;
}
return false;
};
static auto end_speech = [](std::u32string_view str) -> bool {
for (auto& [open, close, _] : braces) {
if (excl_braces.find_first_of(open) + 1)
continue;
if (str.ends_with(close))
return true;
}
return false;
};
const int prev_op = is_open(lines.back());
if (has_speech(lines.back()) && prev_op == 0) {
// Don't squash two speeches
// Also don't squash with lines not starting with text (TODO: fix jp-specific check)
if (start_speech(lines.back()) && end_speech(lines.back()) && is_jp(line[0])) {
if (is_open(line) == 0 && !start_speech(line, true)) {
lines.back() += line;
// Add sentinel to prevent further squashing
new_line(U"");
continue;
}
}
} else if (prev_op > 0) {
// Squash split speech
lines.back() += U" ";
lines.back() += line;
continue;
} else if (lines.back().ends_with(U'、') || lines.back().ends_with(',')) {
// Append speech after incomplete sentence
if (prev_op == 0 && start_speech(line)) {
lines.back() += line;
continue;
}
}
}
new_line(std::move(line));
if (p >= all_lines.size())
new_line(U"");
}
for (auto& line : lines) {
if (!line.empty()) {
extern void add_line(int choice, std::string name, std::string text);
add_line(0, "", to_utf8(line));
}
}
const auto cache_path = vnsleuth_path / seg.cache_name;
if (fs::is_regular_file(cache_path)) {
const auto [tr_lines, verified] = load_translation(0, cache_path, true);
if (!verified) {
is_incomplete = true;
is_broken = true;
} else if (seg.tr_tail.empty() || tr_lines < seg.lines.size()) {
is_incomplete = true;
}
} else {
is_incomplete = true;
}
}
for (auto& [fname, fsize] : file_list) {
const int fd = open(fname.c_str(), O_RDONLY);
if (fd >= 0) {
// Map file in memory (alloc 1 more zero byte, like std::string)
const auto map_sz = fsize + 1;
const std::shared_ptr<void> file(mmap(0, map_sz, PROT_READ, MAP_SHARED, fd, 0), [=](void* ptr) {
munmap(ptr, map_sz);
close(fd);
});
// View file as chars
script_parser data{{static_cast<char*>(file.get()), fsize}};
std::string name = fs::path(fname).filename();
for (std::size_t x = g_lines.segs.size(), j = (data.read_segments(name), x); j < g_lines.segs.size();) {
auto& new_seg = g_lines.segs[j];
if (new_seg.lines.empty()) {
// Remove empty segments (should really only be last in `segs`)
g_lines.segs_by_name.erase(new_seg.src_name);
g_lines.segs.erase(g_lines.segs.begin() + j);
break;
}
if (g_mode == op_mode::print_info || g_mode == op_mode::rt_cached || g_mode == op_mode::rt_llama) {
if (g_mode == op_mode::print_info) {
std::cerr << "Found data: " << new_seg.src_name << std::endl;
std::cerr << "Translation: " << new_seg.cache_name;