Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Server rewrite/enhancement #751

Merged
merged 73 commits into from
Nov 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
73 commits
Select commit Hold shift + click to select a range
0458122
config structure
frederik-uni Nov 16, 2024
5711acc
i have python. why bellow?
frederik-uni Nov 16, 2024
c5feafe
update to enum
frederik-uni Nov 16, 2024
2ccd802
split manga_translator.py into multiple files
frederik-uni Nov 16, 2024
ed2352a
rename batch, demo to local
frederik-uni Nov 16, 2024
b7c8ace
use config in manga_translator
frederik-uni Nov 17, 2024
36a1a14
use config in manga_translator
frederik-uni Nov 17, 2024
341b545
more ctx fixes
frederik-uni Nov 17, 2024
0cef143
Merge remote-tracking branch 'origin/main' into config
frederik-uni Nov 17, 2024
14bc8ca
move preprocessing into config
frederik-uni Nov 17, 2024
82f6ea4
replace ctx in components
frederik-uni Nov 17, 2024
f8996c5
fix imports
frederik-uni Nov 17, 2024
e23510c
fix stuff i forgot
frederik-uni Nov 17, 2024
fa6cd8e
convert str to enum in translatorchain
frederik-uni Nov 17, 2024
85d6739
circular import fix
frederik-uni Nov 18, 2024
2d87f49
load empty config
frederik-uni Nov 18, 2024
c6b39d3
fix inpainting
frederik-uni Nov 19, 2024
43625c6
fix inpainting
frederik-uni Nov 19, 2024
b73d1dd
load from config
frederik-uni Nov 19, 2024
4aeeb01
Merge remote-tracking branch 'origin/shared' into server
frederik-uni Nov 19, 2024
f473ed7
server
frederik-uni Nov 19, 2024
f809568
fix pre & post dict
frederik-uni Nov 19, 2024
5c672c0
Merge remote-tracking branch 'origin/config' into server
frederik-uni Nov 19, 2024
bc7f2fc
python sucks
frederik-uni Nov 19, 2024
30d9b35
api logic
frederik-uni Nov 19, 2024
b66237e
replace api
frederik-uni Nov 19, 2024
897070c
server refactor
frederik-uni Nov 19, 2024
d0e48b9
stream update
frederik-uni Nov 19, 2024
3be082d
stream_image,stream_json now working
frederik-uni Nov 20, 2024
8aa1f2b
remove old tasks on interrupt connection
frederik-uni Nov 20, 2024
0160a3e
change routes
frederik-uni Nov 20, 2024
aa94927
api goals
frederik-uni Nov 20, 2024
4dfe04c
more todos & args
frederik-uni Nov 20, 2024
29a7625
some docs & queue fix
frederik-uni Nov 21, 2024
5e16387
stream type fix
frederik-uni Nov 21, 2024
0c3908e
add server ui
frederik-uni Nov 21, 2024
b462d12
delete old code
frederik-uni Nov 21, 2024
75f07f4
changed queue a bit
frederik-uni Nov 21, 2024
bba5fc6
custom queue element with deconstructor
frederik-uni Nov 21, 2024
7085db8
Merge remote-tracking branch 'origin/shared' into server
frederik-uni Nov 21, 2024
259b807
byte response with cpp&rs examples
frederik-uni Nov 22, 2024
cbf902d
move files into examples
frederik-uni Nov 22, 2024
a2f98e6
fix docs
frederik-uni Nov 22, 2024
a0525dd
convert to normal enum
frederik-uni Nov 22, 2024
85177ed
Merge remote-tracking branch 'origin/config' into server
frederik-uni Nov 22, 2024
322ea78
configs
frederik-uni Nov 22, 2024
b6cb63d
Merge remote-tracking branch 'origin/main' into config
frederik-uni Nov 23, 2024
c9d8cbe
fix ctx -> config after merge
frederik-uni Nov 23, 2024
510db7f
server
frederik-uni Nov 19, 2024
55c59b6
python sucks
frederik-uni Nov 19, 2024
0d8d582
api logic
frederik-uni Nov 19, 2024
bc3f02e
replace api
frederik-uni Nov 19, 2024
536859e
server refactor
frederik-uni Nov 19, 2024
4a8ec99
stream update
frederik-uni Nov 19, 2024
85d7b1e
stream_image,stream_json now working
frederik-uni Nov 20, 2024
d07e7dc
remove old tasks on interrupt connection
frederik-uni Nov 20, 2024
e9ef901
change routes
frederik-uni Nov 20, 2024
c42c9f6
api goals
frederik-uni Nov 20, 2024
b53b79e
more todos & args
frederik-uni Nov 20, 2024
06e04ca
some docs & queue fix
frederik-uni Nov 21, 2024
cbd01ad
stream type fix
frederik-uni Nov 21, 2024
858675a
add server ui
frederik-uni Nov 21, 2024
8aeff8e
delete old code
frederik-uni Nov 21, 2024
aef0a27
changed queue a bit
frederik-uni Nov 21, 2024
cc37ca2
custom queue element with deconstructor
frederik-uni Nov 21, 2024
6cd1819
byte response with cpp&rs examples
frederik-uni Nov 22, 2024
cf7412e
move files into examples
frederik-uni Nov 22, 2024
aac997e
fix docs
frederik-uni Nov 22, 2024
589e037
configs
frederik-uni Nov 22, 2024
6c6a4b5
delete old code & move file
frederik-uni Nov 23, 2024
38a3a5b
Merge remote-tracking branch 'origin/server' into server
frederik-uni Nov 23, 2024
cb98b6d
gpt 3.5 fix
frederik-uni Nov 23, 2024
ef120c0
Merge remote-tracking branch 'origin/config' into server
frederik-uni Nov 23, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
116 changes: 116 additions & 0 deletions examples/response.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
#include <cstring>
#include <cassert>

struct Color {
uint8_t fg[3];
uint8_t bg[3];
};

struct Translation {
uint32_t min_x;
uint32_t min_y;
uint32_t max_x;
uint32_t max_y;
bool is_bulleted_list;
uint32_t angle;
float prob;
Color text_color;
std::unordered_map<std::string, std::string> text;
std::vector<uint8_t> background;
};

struct TranslationResponse {
std::vector<Translation> translations;
};

uint32_t read_u32(const std::vector<uint8_t>& bytes, size_t& offset) {
uint32_t value;
std::memcpy(&value, &bytes[offset], sizeof(value));
value = value;
offset += 4;
return value;
}

float read_f32(const std::vector<uint8_t>& bytes, size_t& offset) {
float value;
std::memcpy(&value, &bytes[offset], sizeof(value));
value = *reinterpret_cast<uint32_t*>(&value);
offset += 4;
return value;
}

uint8_t read_u8(const std::vector<uint8_t>& bytes, size_t& offset) {
uint8_t value = bytes[offset];
offset += 1;
return value;
}

bool read_bool(const std::vector<uint8_t>& bytes, size_t& offset) {
bool value = bytes[offset] != 0;
offset += 1;
return value;
}

std::vector<uint8_t> read_chunk(const std::vector<uint8_t>& bytes, size_t& offset) {
uint32_t size = read_u32(bytes, offset);
std::vector<uint8_t> value(bytes.begin() + offset, bytes.begin() + offset + size);
offset += size;
return value;
}

std::string read_str(const std::vector<uint8_t>& bytes, size_t& offset) {
std::vector<uint8_t> chunk = read_chunk(bytes, offset);
std::string result(chunk.begin(), chunk.end());
return result;
}

std::unordered_map<std::string, std::string> read_map(const std::vector<uint8_t>& bytes, size_t& offset) {
uint32_t count = read_u32(bytes, offset);
std::unordered_map<std::string, std::string> map;
for (uint32_t i = 0; i < count; ++i) {
std::string key = read_str(bytes, offset);
std::string value = read_str(bytes, offset);
map[key] = value;
}
return map;
}

Translation from_bytes(const std::vector<uint8_t>& bytes, size_t& offset) {
Translation translation;
translation.min_x = read_u32(bytes, offset);
translation.min_y = read_u32(bytes, offset);
translation.max_x = read_u32(bytes, offset);
translation.max_y = read_u32(bytes, offset);
translation.is_bulleted_list = read_bool(bytes, offset);
translation.angle = read_u32(bytes, offset);
translation.prob = read_f32(bytes, offset);
for (int i = 0; i < 3; ++i) {
translation.text_color.fg[i] = read_u8(bytes, offset);
translation.text_color.bg[i] = read_u8(bytes, offset);
}
translation.text = read_map(bytes, offset);
translation.background = read_chunk(bytes, offset);
return translation;
}

TranslationResponse from_bytes_response(const std::vector<uint8_t>& bytes) {
size_t offset = 0;
uint32_t count = read_u32(bytes, offset);
TranslationResponse response;

for (uint32_t i = 0; i < count; ++i) {
response.translations.push_back(from_bytes(bytes, offset));
}
return response;
}

int main() {
std::vector<uint8_t> bytes = {/* byte data here */};
TranslationResponse data = from_bytes_response(bytes);
return 0;
}
101 changes: 101 additions & 0 deletions examples/response.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
#[derive(Debug)]
struct Color {
fg: [u8; 3],
bg: [u8; 3],
}

#[derive(Debug)]
struct Translation {
min_x: u32,
min_y: u32,
max_x: u32,
max_y: u32,
is_bulleted_list: bool,
angle: u32,
prob: f32,
text_color: Color,
text: HashMap<String, String>,
background: Vec<u8>,
}

#[derive(Debug)]
struct TranslationResponse {
translations: Vec<Translation>,
}

impl TranslationResponse {
fn from_bytes(bytes: &[u8]) -> Self {
let mut offset = 0;
let v = (0..read_u32(bytes, &mut offset))
.map(|_| Translation::from_bytes(bytes, &mut offset))
.collect::<Vec<_>>();
Self { translations: v }
}
}

fn read_u32(bytes: &[u8], offset: &mut usize) -> u32 {
let value = u32::from_le_bytes(bytes[*offset..*offset + 4].try_into().unwrap());
*offset += 4;
value
}

impl Translation {
fn from_bytes(bytes: &[u8], offset: &mut usize) -> Self {
let read_f32 = |bytes: &[u8], offset: &mut usize| -> f32 {
let value = f32::from_le_bytes(bytes[*offset..*offset + 4].try_into().unwrap());
*offset += 4;
value
};

let read_u8 = |bytes: &[u8], offset: &mut usize| -> u8 {
let value = bytes[*offset];
*offset += 1;
value
};

let read_bool = |bytes: &[u8], offset: &mut usize| -> bool {
let value = bytes[*offset] != 0;
*offset += 1;
value
};

let read_chunk = |bytes: &[u8], offset: &mut usize| -> Vec<u8> {
let size = read_u32(bytes, offset);
let value = &bytes[*offset..*offset + size as usize];
*offset += size as usize;
value.to_vec()
};
let read_str = |bytes: &[u8], offset: &mut usize| -> String {
String::from_utf8(read_chunk(bytes, offset)).expect("Invalid UTF-8")
};
let read_map = |bytes: &[u8], offset: &mut usize| -> HashMap<String, String> {
(0..read_u32(bytes, offset))
.into_iter()
.map(|_| (read_str(bytes, offset), read_str(bytes, offset)))
.collect::<HashMap<String, String>>()
};
Self {
min_x: read_u32(bytes, offset),
min_y: read_u32(bytes, offset),
max_x: read_u32(bytes, offset),
max_y: read_u32(bytes, offset),
is_bulleted_list: read_bool(bytes, offset),
angle: read_u32(bytes, offset),
prob: read_f32(bytes, offset),
text_color: Color {
fg: [
read_u8(bytes, offset),
read_u8(bytes, offset),
read_u8(bytes, offset),
],
bg: [
read_u8(bytes, offset),
read_u8(bytes, offset),
read_u8(bytes, offset),
],
},
text: read_map(bytes, offset),
background: read_chunk(bytes, offset),
}
}
}
43 changes: 0 additions & 43 deletions execute_test.py

This file was deleted.

42 changes: 13 additions & 29 deletions manga_translator/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,8 @@
import logging
from argparse import Namespace

from manga_translator.share import MangaShare
from .manga_translator import (
MangaTranslator,
MangaTranslatorWeb,
MangaTranslatorWS,
MangaTranslatorAPI,
set_main_logger,
set_main_logger, load_dictionary, apply_dictionary,
)
from .args import parser
from .utils import (
Expand All @@ -27,30 +22,29 @@ async def dispatch(args: Namespace):

logger.info(f'Running in {args.mode} mode')

if args.mode in ('demo', 'batch'):
if args.mode == 'local':
if not args.input:
raise Exception('No input image was supplied. Use -i <image_path>')
translator = MangaTranslator(args_dict)
from manga_translator.mode.local import MangaTranslatorLocal
translator = MangaTranslatorLocal(args_dict)

# Load pre-translation and post-translation dictionaries
pre_dict = translator.load_dictionary(args.pre_dict)
post_dict = translator.load_dictionary(args.post_dict)
pre_dict = load_dictionary(args.pre_dict)
post_dict = load_dictionary(args.post_dict)

if args.mode == 'demo':
if len(args.input) != 1 or not os.path.isfile(args.input[0]):
raise FileNotFoundError(f'Invalid single image file path for demo mode: "{" ".join(args.input)}". Use `-m batch`.')
if len(args.input) == 1 and os.path.isfile(args.input[0]):
dest = os.path.join(BASE_PATH, 'result/final.png')
args.overwrite = True # Do overwrite result/final.png file

# Apply pre-translation dictionaries
await translator.translate_path(args.input[0], dest, args_dict)
for textline in translator.textlines:
textline.text = translator.apply_dictionary(textline.text, pre_dict)
textline.text = apply_dictionary(textline.text, pre_dict)
logger.info(f'Pre-translation dictionary applied: {textline.text}')

# Apply post-translation dictionaries
for textline in translator.textlines:
textline.translation = translator.apply_dictionary(textline.translation, post_dict)
textline.translation = apply_dictionary(textline.translation, post_dict)
logger.info(f'Post-translation dictionary applied: {textline.translation}')

else: # batch
Expand All @@ -60,37 +54,27 @@ async def dispatch(args: Namespace):
# Apply pre-translation dictionaries
await translator.translate_path(path, dest, args_dict)
for textline in translator.textlines:
textline.text = translator.apply_dictionary(textline.text, pre_dict)
textline.text = translator.apply_dictionary(textline.text, pre_dict)
logger.info(f'Pre-translation dictionary applied: {textline.text}')

# Apply post-translation dictionaries
for textline in translator.textlines:
textline.translation = translator.apply_dictionary(textline.translation, post_dict)
textline.translation = translator.apply_dictionary(textline.translation, post_dict)
logger.info(f'Post-translation dictionary applied: {textline.translation}')
except Exception :
pass

elif args.mode == 'web':
from .server.web_main import dispatch
await dispatch(args.host, args.port, translation_params=args_dict)

elif args.mode == 'web_client':
translator = MangaTranslatorWeb(args_dict)
await translator.listen(args_dict)

elif args.mode == 'ws':
from manga_translator.mode.ws import MangaTranslatorWS
translator = MangaTranslatorWS(args_dict)
await translator.listen(args_dict)

elif args.mode == 'api':
translator = MangaTranslatorAPI(args_dict)
await translator.listen(args_dict)
elif args.mode == 'shared':
from manga_translator.mode.share import MangaShare
translator = MangaShare(args_dict)
await translator.listen(args_dict)



if __name__ == '__main__':
args = None
init_logging()
Expand Down
Loading
Loading