LGJAS commited on
Commit
fa3ff47
·
verified ·
1 Parent(s): dcd6edd

Upload 42 files

Browse files
.gitattributes CHANGED
@@ -33,3 +33,9 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ demo/examples/0.png filter=lfs diff=lfs merge=lfs -text
37
+ examples/0.png filter=lfs diff=lfs merge=lfs -text
38
+ examples/1.png filter=lfs diff=lfs merge=lfs -text
39
+ examples/2.png filter=lfs diff=lfs merge=lfs -text
40
+ examples/3.png filter=lfs diff=lfs merge=lfs -text
41
+ static/img/loading.gif filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,3 +1,112 @@
1
- ---
2
- license: mit
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Manga Translator
2
+
3
+ Python tool for translating text found within speech bubbles in manga images. It utilizes YOLOv8 for bubble detection, MangaOCR for text extraction, OpenCV, NumPy and Pillow for image processing and translation services like google, bing, baidu and Helsinki-NLP's opus-mt-ja-en model for text translation.
4
+
5
+ ## How it works
6
+
7
+ - Detect speech bubbles in manga images.
8
+ - Extract text from detected speech bubbles.
9
+ - Clear speech bubbles for better visualization.
10
+ - Translate extracted text to the desired language.
11
+ - Add translated text back into the speech bubbles.
12
+
13
+ ## Dataset
14
+
15
+ <a href="https://universe.roboflow.com/luciano-bastos-nunes/mangas-bubble">
16
+ <img src="https://img.shields.io/badge/Dataset%201-8A2BE2"></img>
17
+ </a>
18
+ <br>
19
+ <a href="https://universe.roboflow.com/sheepymeh/manga-vd5mb/">
20
+ <img src="https://img.shields.io/badge/Dataset%202-8A2BE2"></img>
21
+ </a>
22
+
23
+ ## Getting Started
24
+
25
+ 1. Clone this repository:
26
+
27
+ ```bash
28
+ git clone https://github.com/georgescutelnicu/Manga-Translator.git
29
+ ```
30
+
31
+ 2. Install the required dependencies:
32
+
33
+ ```bash
34
+ pip install -r requirements.txt
35
+ ```
36
+
37
+ ### Command Line Interface
38
+
39
+ 1. Navigate to the directory where you cloned the repository:
40
+
41
+ ```bash
42
+ cd Manga-Translator
43
+ ```
44
+
45
+ 2. Run the `main.py` script with the required arguments:
46
+
47
+ ```bash
48
+ python main.py --model-path /path/to/model --image-path /path/to/image --font-path /path/to/font --translator [google/hf] --save-path /path/to/save
49
+ ```
50
+
51
+ Replace the arguments as follows:
52
+ - `/path/to/model`: Path to the YOLO model.
53
+ - `/path/to/image`: Path to the input manga image.
54
+ - `/path/to/font`: Path to the font file for adding text. (default: "fonts/animeace_i.ttf")
55
+ - `[google/hf]`: Choose the translation service, either "google" for Google Translator or "hf" for Helsinki-NLP. (default: "google")
56
+ - `/path/to/save`: Path to save the output image.
57
+
58
+ ### Flask Web App
59
+
60
+ 1. Navigate to the directory where you cloned the repository:
61
+
62
+ ```bash
63
+ cd Manga-Translator
64
+ ```
65
+
66
+ 2. Run the Flask app:
67
+
68
+ ```bash
69
+ python app.py
70
+ ```
71
+
72
+ 3. Open your web browser and go to `http://localhost:5000` to access the app.
73
+
74
+ ## Demo
75
+
76
+ <a href="https://huggingface.co/spaces/georgescutelnicu/MangaTranslator">
77
+ <img src="https://img.shields.io/badge/Deployed%20on%20Hugging%20Face%20with%20Gradio-FFA500"></img>
78
+ </a>
79
+
80
+ ## Examples
81
+
82
+ ## 1.
83
+
84
+ | Original Image | Bubbles Detection |
85
+ |:-----------------:|:-----------------:|
86
+ | ![Image 1](examples/0.png) | ![Image 2](examples/1.png) |
87
+
88
+ | Clear Bubbles | Add translation |
89
+ |:-----------------:|:-----------------:|
90
+ | ![Image 3](examples/2.png) | ![Image 4](examples/3.png) |
91
+
92
+ ## 2.
93
+
94
+ | Original Image | Bubbles Detection |
95
+ |:-----------------:|:-----------------:|
96
+ | ![Image 1](examples/ex0.png) | ![Image 2](examples/ex1.png) |
97
+
98
+ | Clear Bubbles | Add translation |
99
+ |:-----------------:|:-----------------:|
100
+ | ![Image 3](examples/ex2.png) | ![Image 4](examples/ex3.png) |
101
+
102
+ ## Caveats
103
+
104
+ - **Translation Quality**: Please note that the translation quality may vary, as we utilize free translation services.
105
+ - **Potential Solution**: Training a translation model or using a paid translation service for improved translation quality.
106
+ <br> <br>
107
+ - **Limited Dataset**: The model's performance may be affected by the size and quality of the dataset used for training.
108
+ - **Potential Solution**: Creating a custom dataset.
109
+
110
+ ## License
111
+
112
+ This project is licensed under the MIT License.
add_text.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import Image, ImageDraw, ImageFont
2
+ import numpy as np
3
+ import textwrap
4
+ import cv2
5
+
6
+
7
+ def add_text(image, text, font_path, bubble_contour):
8
+ """
9
+ Add text inside a speech bubble contour.
10
+
11
+ Args:
12
+ image (numpy.ndarray): Processed bubble image (cv2 format - BGR).
13
+ text (str): Text to be placed inside the speech bubble.
14
+ font_path (str): Font path.
15
+ bubble_contour (numpy.ndarray): Contour of the detected speech bubble.
16
+
17
+ Returns:
18
+ numpy.ndarray: Image with text placed inside the speech bubble.
19
+ """
20
+ pil_image = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
21
+ draw = ImageDraw.Draw(pil_image)
22
+
23
+ x, y, w, h = cv2.boundingRect(bubble_contour)
24
+
25
+ line_height = 16
26
+ font_size = 14
27
+ wrapping_ratio = 0.075
28
+
29
+ wrapped_text = textwrap.fill(text, width=int(w * wrapping_ratio),
30
+ break_long_words=True)
31
+
32
+ font = ImageFont.truetype(font_path, size=font_size)
33
+
34
+ lines = wrapped_text.split('\n')
35
+ total_text_height = (len(lines)) * line_height
36
+
37
+ while total_text_height > h:
38
+ line_height -= 2
39
+ font_size -= 2
40
+ wrapping_ratio += 0.025
41
+
42
+ wrapped_text = textwrap.fill(text, width=int(w * wrapping_ratio),
43
+ break_long_words=True)
44
+
45
+ font = ImageFont.truetype(font_path, size=font_size)
46
+
47
+ lines = wrapped_text.split('\n')
48
+ total_text_height = (len(lines)) * line_height
49
+
50
+ # Vertical centering
51
+ text_y = y + (h - total_text_height) // 2
52
+
53
+ for line in lines:
54
+ text_length = draw.textlength(line, font=font)
55
+
56
+ # Horizontal centering
57
+ text_x = x + (w - text_length) // 2
58
+
59
+ draw.text((text_x, text_y), line, font=font, fill=(0, 0, 0))
60
+
61
+ text_y += line_height
62
+
63
+ image[:, :, :] = cv2.cvtColor(np.array(pil_image), cv2.COLOR_RGB2BGR)
64
+
65
+ return image
app.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, render_template, request, redirect
2
+ from detect_bubbles import detect_bubbles
3
+ from process_bubble import process_bubble
4
+ from translator.translator import MangaTranslator
5
+ from add_text import add_text
6
+ from manga_ocr import MangaOcr
7
+ from PIL import Image
8
+ import numpy as np
9
+ import base64
10
+ import cv2
11
+ import os
12
+
13
+
14
+ app = Flask(__name__)
15
+ app.config["SECRET_KEY"] = os.environ.get("SECRET_KEY", "secret_key")
16
+
17
+ MODEL_PATH = "model/model.pt"
18
+
19
+
20
+ @app.route("/")
21
+ def home():
22
+ return render_template("index.html")
23
+
24
+
25
+ @app.route("/translate", methods=["POST"])
26
+ def upload_file():
27
+ if "Opus-mt model" == request.form["selected_translator"]:
28
+ selected_translator = "hf"
29
+ else:
30
+ selected_translator = request.form["selected_translator"].lower()
31
+
32
+ selected_font = request.form["selected_font"].lower()
33
+
34
+ if "file" in request.files:
35
+ file = request.files["file"]
36
+ name = file.filename.split(".")[0]
37
+
38
+ file_stream = file.stream
39
+ file_bytes = np.frombuffer(file_stream.read(), dtype=np.uint8)
40
+ image = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR)
41
+
42
+ results = detect_bubbles(MODEL_PATH, image)
43
+
44
+ manga_translator = MangaTranslator()
45
+ mocr = MangaOcr()
46
+
47
+ for result in results:
48
+ x1, y1, x2, y2, score, class_id = result
49
+
50
+ detected_image = image[int(y1):int(y2), int(x1):int(x2)]
51
+
52
+ im = Image.fromarray(np.uint8(detected_image * 255))
53
+ text = mocr(im)
54
+
55
+ detected_image, cont = process_bubble(detected_image)
56
+ text_translated = manga_translator.translate(text, method=selected_translator)
57
+
58
+ add_text(detected_image, text_translated, f"fonts/{selected_font}i.ttf", cont)
59
+
60
+ _, buffer = cv2.imencode(".png", image)
61
+ image = buffer.tobytes()
62
+ encoded_image = base64.b64encode(image).decode("utf-8")
63
+
64
+ return render_template("translate.html", name=name, uploaded_image=encoded_image)
65
+
66
+ return redirect("/")
67
+
68
+
69
+ if __name__ == "__main__":
70
+ app.run(debug=True)
demo/add_text.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import Image, ImageDraw, ImageFont
2
+ import numpy as np
3
+ import textwrap
4
+ import cv2
5
+
6
+
7
+ def add_text(image, text, font_path, bubble_contour):
8
+ """
9
+ Add text inside a speech bubble contour.
10
+
11
+ Args:
12
+ image (numpy.ndarray): Processed bubble image (cv2 format - BGR).
13
+ text (str): Text to be placed inside the speech bubble.
14
+ font_path (str): Font path.
15
+ bubble_contour (numpy.ndarray): Contour of the detected speech bubble.
16
+
17
+ Returns:
18
+ numpy.ndarray: Image with text placed inside the speech bubble.
19
+ """
20
+ pil_image = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
21
+ draw = ImageDraw.Draw(pil_image)
22
+
23
+ x, y, w, h = cv2.boundingRect(bubble_contour)
24
+
25
+ line_height = 16
26
+ font_size = 14
27
+ wrapping_ratio = 0.075
28
+
29
+ wrapped_text = textwrap.fill(text, width=int(w * wrapping_ratio),
30
+ break_long_words=True)
31
+
32
+ font = ImageFont.truetype(font_path, size=font_size)
33
+
34
+ lines = wrapped_text.split('\n')
35
+ total_text_height = (len(lines)) * line_height
36
+
37
+ while total_text_height > h:
38
+ line_height -= 2
39
+ font_size -= 2
40
+ wrapping_ratio += 0.025
41
+
42
+ wrapped_text = textwrap.fill(text, width=int(w * wrapping_ratio),
43
+ break_long_words=True)
44
+
45
+ font = ImageFont.truetype(font_path, size=font_size)
46
+
47
+ lines = wrapped_text.split('\n')
48
+ total_text_height = (len(lines)) * line_height
49
+
50
+ # Vertical centering
51
+ text_y = y + (h - total_text_height) // 2
52
+
53
+ for line in lines:
54
+ text_length = draw.textlength(line, font=font)
55
+
56
+ # Horizontal centering
57
+ text_x = x + (w - text_length) // 2
58
+
59
+ draw.text((text_x, text_y), line, font=font, fill=(0, 0, 0))
60
+
61
+ text_y += line_height
62
+
63
+ image[:, :, :] = cv2.cvtColor(np.array(pil_image), cv2.COLOR_RGB2BGR)
64
+
65
+ return image
demo/app.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from add_text import add_text
2
+ from detect_bubbles import detect_bubbles
3
+ from process_bubble import process_bubble
4
+ from translator import MangaTranslator
5
+ from ultralytics import YOLO
6
+ from manga_ocr import MangaOcr
7
+ from PIL import Image
8
+ import gradio as gr
9
+ import numpy as np
10
+ import cv2
11
+
12
+
13
+ MODEL = "model.pt"
14
+ EXAMPLE_LIST = [["examples/0.png"],
15
+ ["examples/ex0.png"]]
16
+ TITLE = "Manga Translator"
17
+ DESCRIPTION = "Translate text in manga bubbles!"
18
+
19
+
20
+ def predict(img, translation_method, font):
21
+ if translation_method == None:
22
+ translation_method = "google"
23
+ if font == None:
24
+ font = "fonts/animeace_i.ttf"
25
+
26
+ results = detect_bubbles(MODEL, img)
27
+
28
+ manga_translator = MangaTranslator()
29
+ mocr = MangaOcr()
30
+
31
+ image = np.array(img)
32
+
33
+ for result in results:
34
+ x1, y1, x2, y2, score, class_id = result
35
+
36
+ detected_image = image[int(y1):int(y2), int(x1):int(x2)]
37
+
38
+ im = Image.fromarray(np.uint8((detected_image)*255))
39
+ text = mocr(im)
40
+
41
+ detected_image, cont = process_bubble(detected_image)
42
+
43
+ text_translated = manga_translator.translate(text,
44
+ method=translation_method)
45
+
46
+ image_with_text = add_text(detected_image, text_translated, font, cont)
47
+
48
+ return image
49
+
50
+ demo = gr.Interface(fn=predict,
51
+ inputs=["image",
52
+ gr.Dropdown([("Google", "google"),
53
+ ("Helsinki-NLP's opus-mt-ja-en model",
54
+ "hf"),
55
+ ("Baidu", "baidu"),
56
+ ("Bing", "bing")],
57
+ label="Translation Method",
58
+ value="google"),
59
+ gr.Dropdown([("animeace_i", "fonts/animeace_i.ttf"),
60
+ ("mangati", "fonts/mangati.ttf"),
61
+ ("ariali", "fonts/ariali.ttf")],
62
+ label="Text Font",
63
+ value="fonts/animeace_i.ttf")
64
+ ],
65
+ outputs=[gr.Image()],
66
+ examples=EXAMPLE_LIST,
67
+ title=TITLE,
68
+ description=DESCRIPTION)
69
+
70
+
71
+ demo.launch(debug=False,
72
+ share=False)
demo/detect_bubbles.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ultralytics import YOLO
2
+
3
+
4
+ def detect_bubbles(model_path, image_path):
5
+ """
6
+ Detects bubbles in an image using a YOLOv8 model.
7
+
8
+ Args:
9
+ model_path (str): The file path to the YOLO model.
10
+ image_path (str): The file path to the input image.
11
+
12
+ Returns:
13
+ list: A list containing the coordinates, score and class_id of
14
+ the detected bubbles.
15
+ """
16
+ model = YOLO(model_path)
17
+ bubbles = model(image_path)[0]
18
+
19
+ return bubbles.boxes.data.tolist()
demo/examples/0.png ADDED

Git LFS Details

  • SHA256: cfccaf6c12b806994d153cc083dd595c4f43884a4de54504d1cfac82b4e79de2
  • Pointer size: 132 Bytes
  • Size of remote file: 1.31 MB
demo/examples/ex0.png ADDED
demo/fonts/animeace_i.ttf ADDED
Binary file (28.8 kB). View file
 
demo/fonts/ariali.ttf ADDED
Binary file (717 kB). View file
 
demo/fonts/mangati.ttf ADDED
Binary file (30.4 kB). View file
 
demo/model.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2f1a64e4e4c0dd30b361eb332866dea0f52eab9acb288b9ffdcb2622cb5d1cdb
3
+ size 6234585
demo/packages.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ python3-opencv
demo/process_bubble.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+
4
+
5
+ def process_bubble(image):
6
+ """
7
+ Processes the speech bubble in the given image, making its contents white.
8
+
9
+ Parameters:
10
+ - image (numpy.ndarray): Input image.
11
+
12
+ Returns:
13
+ - image (numpy.ndarray): Image with the speech bubble content set to white.
14
+ - largest_contour (numpy.ndarray): Contour of the detected speech bubble.
15
+ """
16
+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
17
+ _, thresh = cv2.threshold(gray, 240, 255, cv2.THRESH_BINARY)
18
+
19
+ contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
20
+ largest_contour = max(contours, key=cv2.contourArea)
21
+
22
+ mask = np.zeros_like(gray)
23
+ cv2.drawContours(mask, [largest_contour], -1, 255, cv2.FILLED)
24
+
25
+ image[mask == 255] = (255, 255, 255)
26
+
27
+ return image, largest_contour
demo/requirements ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ deep-translator==1.11.4
2
+ translators==5.9.1
3
+ huggingface-hub==0.22.2
4
+ manga-ocr==0.1.11
5
+ numpy==1.24.2
6
+ opencv-python==4.9.0.80
7
+ pillow==10.3.0
8
+ ultralytics==8.1.43
demo/translator.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from deep_translator import GoogleTranslator
2
+ from transformers import pipeline
3
+ import translators as ts
4
+
5
+
6
+ class MangaTranslator:
7
+ def __init__(self):
8
+ self.target = "en"
9
+ self.source = "ja"
10
+ self.translators = {
11
+ "google": self._translate_with_google,
12
+ "hf": self._translate_with_hf,
13
+ "baidu": self._translate_with_baidu,
14
+ "bing": self._translate_with_bing
15
+ }
16
+
17
+ def translate(self, text, method="google"):
18
+ """
19
+ Translates the given text to the target language using the specified method.
20
+
21
+ Args:
22
+ text (str): The text to be translated.
23
+ method (str):"google" for Google Translator,
24
+ "hf" for Helsinki-NLP's opus-mt-ja-en model (HF pipeline)
25
+ "baidu" for Baidu Translate
26
+ "bing" for Microsoft Bing Translator
27
+
28
+ Returns:
29
+ str: The translated text.
30
+ """
31
+ translator_func = self.translators.get(method)
32
+
33
+ if translator_func:
34
+ return translator_func(self._preprocess_text(text))
35
+ else:
36
+ raise ValueError("Invalid translation method.")
37
+
38
+ def _translate_with_google(self, text):
39
+ translator = GoogleTranslator(source=self.source, target=self.target)
40
+ translated_text = translator.translate(text)
41
+ return translated_text if translated_text is not None else text
42
+
43
+ def _translate_with_hf(self, text):
44
+ pipe = pipeline("translation", model=f"Helsinki-NLP/opus-mt-ja-en")
45
+ translated_text = pipe(text)[0]["translation_text"]
46
+ return translated_text if translated_text is not None else text
47
+
48
+ def _translate_with_baidu(self, text):
49
+ translated_text = ts.translate_text(text, translator="baidu",
50
+ from_language="jp",
51
+ to_language=self.target)
52
+ return translated_text if translated_text is not None else text
53
+
54
+ def _translate_with_bing(self, text):
55
+ translated_text = ts.translate_text(text, translator="bing",
56
+ from_language=self.source,
57
+ to_language=self.target)
58
+ return translated_text if translated_text is not None else text
59
+
60
+ def _preprocess_text(self, text):
61
+ preprocessed_text = text.replace(".", ".")
62
+ return preprocessed_text
detect_bubbles.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ultralytics import YOLO
2
+
3
+
4
+ def detect_bubbles(model_path, image_path):
5
+ """
6
+ Detects bubbles in an image using a YOLOv8 model.
7
+
8
+ Args:
9
+ model_path (str): The file path to the YOLO model.
10
+ image_path (str): The file path to the input image.
11
+
12
+ Returns:
13
+ list: A list containing the coordinates, score and class_id of
14
+ the detected bubbles.
15
+ """
16
+ model = YOLO(model_path)
17
+ bubbles = model(image_path)[0]
18
+
19
+ return bubbles.boxes.data.tolist()
examples/0.png ADDED

Git LFS Details

  • SHA256: cfccaf6c12b806994d153cc083dd595c4f43884a4de54504d1cfac82b4e79de2
  • Pointer size: 132 Bytes
  • Size of remote file: 1.31 MB
examples/1.png ADDED

Git LFS Details

  • SHA256: ab9b80456431019170b545de2acf0ad2c3c0b945093939ef2b50a9458b11eb97
  • Pointer size: 132 Bytes
  • Size of remote file: 1.3 MB
examples/2.png ADDED

Git LFS Details

  • SHA256: a32b641717568084cecd5bc5212643cd37b7ad0e62b333b04e4fafacb58b0643
  • Pointer size: 132 Bytes
  • Size of remote file: 1.19 MB
examples/3.png ADDED

Git LFS Details

  • SHA256: a516cd53189bde9a3276cfca98355525e1411b800ccfb8441655e15de1d7aa2c
  • Pointer size: 132 Bytes
  • Size of remote file: 1.21 MB
examples/ex0.png ADDED
examples/ex1.png ADDED
examples/ex2.png ADDED
examples/ex3.png ADDED
fonts/animeace_i.ttf ADDED
Binary file (28.8 kB). View file
 
fonts/ariali.ttf ADDED
Binary file (717 kB). View file
 
fonts/mangati.ttf ADDED
Binary file (30.4 kB). View file
 
main.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from detect_bubbles import detect_bubbles
2
+ from process_bubble import process_bubble
3
+ from translator.translator import MangaTranslator
4
+ from add_text import add_text
5
+ from manga_ocr import MangaOcr
6
+ from PIL import Image
7
+ import numpy as np
8
+ import cv2
9
+ import argparse
10
+
11
+
12
+ if __name__ == "__main__":
13
+ parser = argparse.ArgumentParser(description="Manga Translator")
14
+
15
+ parser.add_argument("--model-path", "-m", type=str, required=True, help="Path to model")
16
+ parser.add_argument("--image-path", "-i", type=str, required=True, help="Path to image")
17
+ parser.add_argument("--font-path", "-f", type=str, default="fonts/animeace_i.ttf", help="Path to font")
18
+ parser.add_argument("--translator", "-t", type=str, choices=["google", "hf"], default="google",
19
+ help="Translator to use (google or hf)")
20
+ parser.add_argument("--save-path", "-s", type=str, required=True, help="Path where the output image to be saved")
21
+
22
+ args = parser.parse_args()
23
+
24
+ results = detect_bubbles(args.model_path, args.image_path)
25
+
26
+ manga_translator = MangaTranslator()
27
+ mocr = MangaOcr()
28
+
29
+ image = cv2.imread(args.image_path)
30
+
31
+ for result in results:
32
+ x1, y1, x2, y2, score, class_id = result
33
+
34
+ detected_image = image[int(y1):int(y2), int(x1):int(x2)]
35
+
36
+ im = Image.fromarray(np.uint8(detected_image * 255))
37
+ text = mocr(im)
38
+
39
+ detected_image, cont = process_bubble(detected_image)
40
+ text_translated = manga_translator.translate(text, method=args.translator)
41
+
42
+ add_text(detected_image, text_translated, args.font_path, cont)
43
+
44
+ save_path = args.save_path + "/output_image.jpg"
45
+ cv2.imwrite(save_path, image)
model/model.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2f1a64e4e4c0dd30b361eb332866dea0f52eab9acb288b9ffdcb2622cb5d1cdb
3
+ size 6234585
model/model_training.ipynb ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "colab": {
6
+ "provenance": []
7
+ },
8
+ "kernelspec": {
9
+ "name": "python3",
10
+ "display_name": "Python 3"
11
+ },
12
+ "language_info": {
13
+ "name": "python"
14
+ }
15
+ },
16
+ "cells": [
17
+ {
18
+ "cell_type": "markdown",
19
+ "source": [
20
+ "**YOLOv8 model training using ultralytics**"
21
+ ],
22
+ "metadata": {
23
+ "id": "7PihFE53D92W"
24
+ }
25
+ },
26
+ {
27
+ "cell_type": "code",
28
+ "execution_count": null,
29
+ "metadata": {
30
+ "id": "toxMDptj5Psd"
31
+ },
32
+ "outputs": [],
33
+ "source": [
34
+ "!pip install ultralytics"
35
+ ]
36
+ },
37
+ {
38
+ "cell_type": "code",
39
+ "source": [
40
+ "from ultralytics import YOLO\n",
41
+ "import os"
42
+ ],
43
+ "metadata": {
44
+ "id": "0Jw1Ow2A5_Sf"
45
+ },
46
+ "execution_count": null,
47
+ "outputs": []
48
+ },
49
+ {
50
+ "cell_type": "code",
51
+ "source": [
52
+ "# Path to the root directory that contains config.yaml file and the dataset\n",
53
+ "# annotated in the YOLOv8 format\n",
54
+ "ROOT_DIR = \"Path\"\n",
55
+ "\n",
56
+ "# Path to the pretrained model if exists\n",
57
+ "PRETRAINED_MODEL_PATH = \"Path\"\n",
58
+ "\n",
59
+ "# Number of iterations (forward pass) to train the model\n",
60
+ "NUM_EPOCHS = 100"
61
+ ],
62
+ "metadata": {
63
+ "id": "NDclcuR05QZP"
64
+ },
65
+ "execution_count": null,
66
+ "outputs": []
67
+ },
68
+ {
69
+ "cell_type": "code",
70
+ "source": [
71
+ "def train_model(load_model=False):\n",
72
+ " if load_model:\n",
73
+ " model = YOLO(PRETRAINED_MODEL_PATH)\n",
74
+ " results = model.train(data=os.path.join(ROOT_DIR, \"config.yaml\"),\n",
75
+ " epochs=NUM_EPOCHS)\n",
76
+ " else:\n",
77
+ " model = YOLO(\"yolov8n.yaml\")\n",
78
+ " results = model.train(data=os.path.join(ROOT_DIR, \"config.yaml\"),\n",
79
+ " epochs=NUM_EPOCHS)\n",
80
+ ""
81
+ ],
82
+ "metadata": {
83
+ "id": "PAYhaotC5QcB"
84
+ },
85
+ "execution_count": null,
86
+ "outputs": []
87
+ },
88
+ {
89
+ "cell_type": "code",
90
+ "source": [
91
+ "train_model()"
92
+ ],
93
+ "metadata": {
94
+ "id": "mCxI3Xlr7Ryu"
95
+ },
96
+ "execution_count": null,
97
+ "outputs": []
98
+ }
99
+ ]
100
+ }
process_bubble.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+
4
+
5
+ def process_bubble(image):
6
+ """
7
+ Processes the speech bubble in the given image, making its contents white.
8
+
9
+ Parameters:
10
+ - image (numpy.ndarray): Input image.
11
+
12
+ Returns:
13
+ - image (numpy.ndarray): Image with the speech bubble content set to white.
14
+ - largest_contour (numpy.ndarray): Contour of the detected speech bubble.
15
+ """
16
+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
17
+ _, thresh = cv2.threshold(gray, 240, 255, cv2.THRESH_BINARY)
18
+
19
+ contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
20
+ largest_contour = max(contours, key=cv2.contourArea)
21
+
22
+ mask = np.zeros_like(gray)
23
+ cv2.drawContours(mask, [largest_contour], -1, 255, cv2.FILLED)
24
+
25
+ image[mask == 255] = (255, 255, 255)
26
+
27
+ return image, largest_contour
requirements.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ deep-translator==1.11.4
2
+ translators==5.9.1
3
+ huggingface-hub==0.22.2
4
+ manga-ocr==0.1.11
5
+ numpy==1.24.2
6
+ opencv-python==4.9.0.80
7
+ pillow==10.3.0
8
+ ultralytics==8.1.43
9
+ Flask==2.2.5
10
+ Werkzeug==3.0.1
11
+ gunicorn==21.2.0
12
+
static/css/style.css ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ body {
2
+ font-family: 'Exo 2', sans-serif;
3
+ background-color: #f7f7f7;
4
+ margin: 0;
5
+ justify-content: center;
6
+ align-items: center;
7
+ height: 100vh;
8
+ }
9
+
10
+ header {
11
+ margin-bottom: 75px;
12
+ box-shadow: 0 0 10px #cccccc;
13
+ background-image: url("../img/header.png");
14
+ background-size: 100% 100%;
15
+ padding: 1.4%;
16
+ }
17
+
18
+ .container {
19
+ margin: 150px auto auto;
20
+ background-color: #fff;
21
+ border-radius: 10px;
22
+ box-shadow: 0 0 10px #b2b2b2;
23
+ padding: 20px;
24
+ width: 25%;
25
+ box-sizing: border-box;
26
+ }
27
+
28
+ @media (max-width: 1060px) {
29
+ .container {
30
+ width: 40%;
31
+ }
32
+ }
33
+
34
+ @media (max-width: 660px) {
35
+ .container {
36
+ width: 80%;
37
+ }
38
+ }
39
+
40
+ img {
41
+ display: block;
42
+ margin: 0 auto;
43
+ width: 33%;
44
+ height: auto;
45
+ margin-top: 20px;
46
+ }
47
+
48
+ form {
49
+ text-align: center;
50
+ margin-top: 20px;
51
+ }
52
+
53
+ input[type="file"] {
54
+ display: none;
55
+ }
56
+
57
+ .file {
58
+ appearance: none;
59
+ margin: auto;
60
+ display: block;
61
+ padding: 10px;
62
+ border: 2px dashed rgb(94, 22, 117);
63
+ border-radius: 10px;
64
+ box-sizing: border-box;
65
+ justify-content: center;
66
+ text-align: center;
67
+ width: 220px;
68
+ cursor: pointer;
69
+ }
70
+
71
+ button {
72
+ display: inline-block;
73
+ padding: 13px 20px;
74
+ background-color: #fff;
75
+ color: #5E1675;
76
+ border: 1px solid #5E1675;
77
+ border-radius: 10px;
78
+ cursor: pointer;
79
+ width: 220px;
80
+ box-sizing: border-box;
81
+ transition: background-color 0.3s ease;
82
+ margin-top: 12px;
83
+ font-weight: bold;
84
+ }
85
+
86
+ button:hover {
87
+ background-color: #5E1675;
88
+ color: #fff;
89
+ }
90
+
91
+ .select-wrapper {
92
+ margin: 3%;
93
+ }
94
+
95
+ label {
96
+ display: block;
97
+ font-size: 14px;
98
+ font-weight: bold;
99
+ margin-bottom: 10px;
100
+ }
101
+
102
+ .custom-select {
103
+ position: relative;
104
+ width: 220px;
105
+ margin: auto;
106
+ }
107
+
108
+ .select-box {
109
+ border: 1px solid #5E1675;
110
+ border-radius: 18px;
111
+ padding: 8px 20px;
112
+ cursor: pointer;
113
+ user-select: none;
114
+ background-color: white;
115
+ display: flex;
116
+ justify-content: space-between;
117
+ }
118
+
119
+ .selected {
120
+ display: inline-block;
121
+ overflow: hidden;
122
+ white-space: nowrap;
123
+ text-overflow: ellipsis;
124
+ }
125
+
126
+ .icon {
127
+ color: gray;
128
+ }
129
+
130
+ .options {
131
+ position: absolute;
132
+ top: calc(100% + 5px);
133
+ left: 0;
134
+ z-index: 1;
135
+ display: none;
136
+ width: calc(100% + 2px);
137
+ border: 1px solid #5E1675;
138
+ border-radius: 8px;
139
+ background-color: white;
140
+ cursor: pointer;
141
+ }
142
+
143
+ .option {
144
+ display: block;
145
+ padding: 8px 30px;
146
+ border-radius: 3px;
147
+ position: relative;
148
+ }
149
+
150
+ .option.selected {
151
+ font-weight: bold;
152
+ }
153
+
154
+ .option:hover {
155
+ background-color: rgba(204, 146, 157, 0.1);
156
+ color: #7a595f;
157
+ }
158
+
159
+ .custom-select.open .select-box .icon {
160
+ transform: rotate(180deg);
161
+ }
162
+
163
+ .checkmark {
164
+ position: absolute;
165
+ left: 10px;
166
+ color: darkgray;
167
+ font-weight: bold;
168
+ }
169
+
170
+ footer {
171
+ width: 100%;
172
+ position: absolute;
173
+ bottom: 0;
174
+ background-color: white;
175
+ box-shadow: 0 0 10px #cccccc;
176
+ }
177
+
178
+ footer p {
179
+ text-align: center;
180
+ }
181
+
182
+ .git {
183
+ color: #000;
184
+ font-weight: 500;
185
+
186
+ }
187
+
188
+ .git:hover {
189
+ text-decoration: none;
190
+ }
191
+
192
+ .uploaded-image {
193
+ display: block;
194
+ margin: auto;
195
+ width: 25rem;
196
+ max-height: 615px;
197
+ margin-top: 120px;
198
+ border-radius: 5%;
199
+ box-shadow: 0 0 10px #b2b2b2;
200
+ }
201
+
202
+ .buttons_image {
203
+ display: flex;
204
+ justify-content: center;
205
+ }
206
+
207
+ .buttons_image a {
208
+ text-align: center;
209
+ display: inline-block;
210
+ padding: 13px 20px;
211
+ background-color: #fff;
212
+ border-radius: 10px;
213
+ cursor: pointer;
214
+ box-sizing: border-box;
215
+ transition: background-color 0.3s ease;
216
+ font-weight: bold;
217
+ width: 175px;
218
+ margin: 2% 1%;
219
+ text-decoration: none;
220
+ }
221
+
222
+ .green {
223
+ border: 1px solid #50C878;
224
+ color: #50C878;
225
+ transition: background-color 0.3s ease;
226
+ }
227
+
228
+ .green:hover {
229
+ background-color: #50C878;
230
+ color: #fff;
231
+ }
232
+
233
+ .red {
234
+ border: 1px solid #fd5c63;
235
+ color: #fd5c63;
236
+ transition: background-color 0.3s ease;
237
+ }
238
+
239
+ .red:hover {
240
+ background-color: #fd5c63;
241
+ color: #fff;
242
+ }
243
+
244
+ #loading-img {
245
+ display: none;
246
+ width: 100%;
247
+ }
248
+
249
+ #loading-p {
250
+ display: none;
251
+ text-align: center;
252
+ }
static/img/header.png ADDED
static/img/loading.gif ADDED

Git LFS Details

  • SHA256: b5e6c0bfb72db987730d9716676b1078d26ead7c985e717a8ca7377380de2b25
  • Pointer size: 132 Bytes
  • Size of remote file: 1.24 MB
static/img/logo.png ADDED
static/js/app.js ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Sets up custom dropdown behavior for all select wrappers
2
+ document.addEventListener("DOMContentLoaded", () => {
3
+ const selectWrappers = document.querySelectorAll('.select-wrapper');
4
+
5
+ selectWrappers.forEach(wrapper => {
6
+ const selectBox = wrapper.querySelector('.custom-select');
7
+ const selectedText = selectBox.querySelector('.selected');
8
+ const options = selectBox.querySelector('.options');
9
+ const optionList = selectBox.querySelectorAll('.option');
10
+
11
+ const defaultOption = optionList[0];
12
+ selectedText.textContent = defaultOption.textContent;
13
+ defaultOption.classList.add('selected');
14
+
15
+ // Toggle options display on select box click
16
+ selectBox.addEventListener('click', () => {
17
+ options.style.display = options.style.display === 'block' ? 'none' : 'block';
18
+ selectBox.classList.toggle('open');
19
+ });
20
+
21
+ // Update selected option and hide options on option click
22
+ optionList.forEach(option => {
23
+ option.addEventListener('click', () => {
24
+ selectedText.textContent = option.textContent;
25
+ optionList.forEach(opt => opt.classList.remove('selected'));
26
+ option.classList.add('selected');
27
+ });
28
+ });
29
+
30
+ // Hide options when clicking outside the select box
31
+ window.addEventListener('click', e => {
32
+ if (!wrapper.contains(e.target)) {
33
+ options.style.display = 'none';
34
+ selectBox.classList.remove('open');
35
+ }
36
+ });
37
+ });
38
+ });
39
+
40
+ // Handles file upload change event
41
+ document.getElementById('file-upload').addEventListener('change', function() {
42
+ const fileName = this.files[0].name;
43
+ const truncatedFileName = truncateFileName(fileName, 20);
44
+ document.querySelector('.file').innerText = truncatedFileName;
45
+ });
46
+
47
+ // Truncates file name if it exceeds the maximum length
48
+ function truncateFileName(fileName, maxLength) {
49
+ return fileName.length <= maxLength ? fileName : fileName.substr(0, maxLength - 3) + '...';
50
+ }
51
+
52
+ // Updates hidden input fields with selected options
53
+ function updateHiddenInputs() {
54
+ const selectedLanguage = document.querySelector("#language .selected").innerText;
55
+ const selectedTranslator = document.querySelector("#translator .selected").innerText;
56
+ const selectedFont = document.querySelector("#font .selected").innerText;
57
+
58
+ document.getElementById("selected_language").value = selectedLanguage;
59
+ document.getElementById("selected_translator").value = selectedTranslator;
60
+ document.getElementById("selected_font").value = selectedFont;
61
+
62
+ document.querySelector('form').style.display = 'none';
63
+ document.getElementById('loading-img').style.display = 'block';
64
+ document.getElementById('loading-p').style.display = 'block';
65
+ }
templates/index.html ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <link rel="preconnect" href="https://fonts.googleapis.com">
7
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
8
+ <title>Manga Translator</title>
9
+ <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
10
+ <link href="https://fonts.googleapis.com/css2?family=Exo+2:ital,wght@0,100..900;1,100..900&display=swap" rel="stylesheet">
11
+ </head>
12
+ <body>
13
+ <header>
14
+ </header>
15
+ <div class="container">
16
+ <img src="{{ url_for('static', filename='img/logo.png') }}" alt="Statistics Icon">
17
+ <form class="" action="/translate" method="post" enctype="multipart/form-data"
18
+ onsubmit="return updateHiddenInputs()">
19
+ <div class="select-wrapper">
20
+ <label for="language" class="translator-label">Language</label>
21
+ <div class="custom-select" id="language" tabindex="0">
22
+ <div class="select-box">
23
+ <span class="selected"></span>
24
+ <span class="icon">&#9660;</span>
25
+ </div>
26
+ <div class="options">
27
+ <span class="option">English</span>
28
+ </div>
29
+ </div>
30
+ </div>
31
+ <div class="select-wrapper">
32
+ <label for="translator" class="translator-label">Translator</label>
33
+ <div class="custom-select" id="translator" tabindex="0">
34
+ <div class="select-box">
35
+ <span class="selected"></span>
36
+ <span class="icon">&#9660;</span>
37
+ </div>
38
+ <div class="options">
39
+ <span class="option">Google</span>
40
+ <span class="option">Baidu</span>
41
+ <span class="option">Bing</span>
42
+ <span class="option">Opus-mt model</span>
43
+ </div>
44
+ </div>
45
+ </div>
46
+ <div class="select-wrapper">
47
+ <label for="font" class="translator-label">Font</label>
48
+ <div class="custom-select" id="font" tabindex="0">
49
+ <div class="select-box">
50
+ <span class="selected"></span>
51
+ <span class="icon">&#9660;</span>
52
+ </div>
53
+ <div class="options">
54
+ <span class="option">Animeace</span>
55
+ <span class="option">Mangat</span>
56
+ <span class="option">Arial</span>
57
+ </div>
58
+ </div>
59
+ </div>
60
+ <input id="file-upload" type="file" name="file" accept=".jpg, .jpeg, .png" required>
61
+ <label for="file-upload" class="file">
62
+ Upload Image
63
+ </label>
64
+ <input type="hidden" id="selected_language" name="selected_language">
65
+ <input type="hidden" id="selected_translator" name="selected_translator">
66
+ <input type="hidden" id="selected_font" name="selected_font">
67
+ <button type="submit">Upload</button>
68
+ </form>
69
+ <img id="loading-img" src="{{ url_for('static', filename='img/loading.gif') }}" alt="">
70
+ <p id="loading-p">Be patient, it might take some time!</p>
71
+ </div>
72
+ <footer>
73
+ <p>Manga Translator - Find the codebase on
74
+ <a class="git" href="https://github.com/georgescutelnicu/Manga-Translator">GitHub</a>
75
+ </p>
76
+ </footer>
77
+ <script src="{{ url_for('static', filename='js/app.js') }}"></script>
78
+ </body>
79
+ </html>
templates/translate.html ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <title>Manga Translator</title>
6
+ <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
7
+ <link href="https://fonts.googleapis.com/css2?family=Exo+2:ital,wght@0,100..900;1,100..900&display=swap" rel="stylesheet">
8
+ </head>
9
+ <body>
10
+ <header>
11
+ </header>
12
+ <div>
13
+ {% if uploaded_image %}
14
+ <img class="uploaded-image" src="data:image/png;base64,{{ uploaded_image }}" alt="Uploaded Image">
15
+ {% else %}
16
+ <p>No image uploaded.</p>
17
+ {% endif %}
18
+ </div>
19
+ <div class="buttons_image">
20
+ <a href="/" class="green" id="save-image">Save Image</a>
21
+ <a href="/" class="red">Go Back</a>
22
+ </div>
23
+ <footer>
24
+ <p>Manga Translator - Find the codebase on
25
+ <a class="git" href="https://github.com/georgescutelnicu/Manga-Translator">GitHub</a>
26
+ </p>
27
+ </footer>
28
+ </body>
29
+ <script>
30
+ // Save the image
31
+ document.getElementById("save-image").addEventListener("click", () => {
32
+ const uploadedImage = "{{ uploaded_image }}";
33
+ const a = document.createElement("a");
34
+ a.href = "data:image/png;base64," + uploadedImage;
35
+ a.download = "{{ name }}" + "_translated.png";
36
+ a.click();
37
+ });
38
+ </script>
39
+ </html>
translator/test_translator.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ from translator import MangaTranslator
3
+
4
+
5
+ JA_TEXT = "こんばんわ!"
6
+ EN_TRANSLATION = "good evening!"
7
+
8
+
9
+ @pytest.fixture
10
+ def translator():
11
+ return MangaTranslator()
12
+
13
+
14
+ @pytest.mark.parametrize("method", ["google", "hf", "baidu", "bing"])
15
+ def test_translate(translator, method):
16
+ translated_text = translator.translate(JA_TEXT, method=method)
17
+ assert translated_text.lower() == EN_TRANSLATION
18
+
19
+
20
+ def test_invalid_translation_method(translator):
21
+ with pytest.raises(ValueError) as e:
22
+ translator.translate(JA_TEXT, method="Mirai")
23
+ assert str(e.value) == "Invalid translation method."
translator/translator.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from deep_translator import GoogleTranslator
2
+ from transformers import pipeline
3
+ import translators as ts
4
+
5
+
6
+ class MangaTranslator:
7
+ def __init__(self):
8
+ self.target = "en"
9
+ self.source = "ja"
10
+ self.translators = {
11
+ "google": self._translate_with_google,
12
+ "hf": self._translate_with_hf,
13
+ "baidu": self._translate_with_baidu,
14
+ "bing": self._translate_with_bing
15
+ }
16
+
17
+ def translate(self, text, method="google"):
18
+ """
19
+ Translates the given text to the target language using the specified method.
20
+
21
+ Args:
22
+ text (str): The text to be translated.
23
+ method (str):"google" for Google Translator,
24
+ "hf" for Helsinki-NLP's opus-mt-ja-en model (HF pipeline)
25
+ "baidu" for Baidu Translate
26
+ "bing" for Microsoft Bing Translator
27
+
28
+ Returns:
29
+ str: The translated text.
30
+ """
31
+ translator_func = self.translators.get(method)
32
+
33
+ if translator_func:
34
+ return translator_func(self._preprocess_text(text))
35
+ else:
36
+ raise ValueError("Invalid translation method.")
37
+
38
+ def _translate_with_google(self, text):
39
+ translator = GoogleTranslator(source=self.source, target=self.target)
40
+ translated_text = translator.translate(text)
41
+ return translated_text if translated_text is not None else text
42
+
43
+ def _translate_with_hf(self, text):
44
+ pipe = pipeline("translation", model=f"Helsinki-NLP/opus-mt-ja-en")
45
+ translated_text = pipe(text)[0]["translation_text"]
46
+ return translated_text if translated_text is not None else text
47
+
48
+ def _translate_with_baidu(self, text):
49
+ translated_text = ts.translate_text(text, translator="baidu",
50
+ from_language="jp",
51
+ to_language=self.target)
52
+ return translated_text if translated_text is not None else text
53
+
54
+ def _translate_with_bing(self, text):
55
+ translated_text = ts.translate_text(text, translator="bing",
56
+ from_language=self.source,
57
+ to_language=self.target)
58
+ return translated_text if translated_text is not None else text
59
+
60
+ def _preprocess_text(self, text):
61
+ preprocessed_text = text.replace(".", ".")
62
+ return preprocessed_text