Belajar Python (Membuat translator sederhana memanfaatkan library Google Translate)
Library yang diperlukan
pip install googletrans==4.0.0-rc1
Jika ada pesan untuk update silahkan di update
[notice] A new release of pip is available: 24.2 -> 24.3.1
[notice] To update, run: python.exe -m pip install --upgrade pip
Tampilan program :
Program :
import tkinter as tk
from tkinter import filedialog, messagebox
from googletrans import Translator, LANGUAGES
from tkinter import font, ttk
class TranslatorApp:
def __init__(self, root):
self.root = root
self.root.title("Penerjemah Teks, Dibuat November 2024")
self.root.geometry("500x450")
self.center_window() # Memusatkan jendela
self.root.config(bg="#f0f0f5")
# Membuat objek Translator
self.translator = Translator()
# Font styling
self.header_font = font.Font(family="Helvetica", size=16, weight="bold")
self.label_font = font.Font(family="Helvetica", size=10)
# Variabel untuk menyimpan path file
self.input_file_path = None
self.output_file_path = None
# Label Judul
self.title_label = tk.Label(
root,
text="Aplikasi Penerjemah Teks",
font=self.header_font,
bg="#f0f0f5",
fg="blue",
anchor="w",
justify="left"
)
self.title_label.pack(fill="x", padx=10, pady=15)
# Frame pilihan bahasa
self.lang_frame = tk.Frame(root, bg="#f0f0f5")
self.lang_frame.pack(fill="x", padx=10, pady=10)
# Membuat daftar bahasa untuk dropdown
self.languages = [nama.capitalize() for nama in LANGUAGES.values()]
# Label dan dropdown untuk bahasa asal
tk.Label(self.lang_frame, text="Bahasa Asal:", font=self.label_font, bg="#f0f0f5", anchor="w").grid(row=0, column=0, padx=5, sticky="w")
self.src_lang = tk.StringVar()
self.src_dropdown = ttk.Combobox(self.lang_frame, textvariable=self.src_lang, values=["Deteksi otomatis"] + self.languages, width=30, state="readonly")
self.src_dropdown.set("Deteksi otomatis")
self.src_dropdown.grid(row=0, column=1, padx=10, pady=5, sticky="w")
# Label dan dropdown untuk bahasa tujuan
tk.Label(self.lang_frame, text="Bahasa Tujuan:", font=self.label_font, bg="#f0f0f5", anchor="w").grid(row=1, column=0, padx=5, sticky="w")
self.dest_lang = tk.StringVar()
self.dest_dropdown = ttk.Combobox(self.lang_frame, textvariable=self.dest_lang, values=self.languages, width=30, state="readonly")
self.dest_dropdown.set("Pilih bahasa tujuan")
self.dest_dropdown.grid(row=1, column=1, padx=10, pady=5, sticky="w")
# Frame untuk pilihan file
self.file_frame = tk.Frame(root, bg="#f0f0f5")
self.file_frame.pack(fill="x", padx=10, pady=10)
# Tombol pilih file input
self.input_button = tk.Button(self.file_frame, text="Pilih File Input", command=self.buka_file_input, bg="#4CAF50", fg="white", width=15)
self.input_button.grid(row=0, column=0, padx=5, pady=5, sticky="w")
self.input_label = tk.Label(self.file_frame, text="File input belum dipilih", bg="#f0f0f5", font=self.label_font, fg="#666", anchor="w")
self.input_label.grid(row=0, column=1, padx=10, sticky="w")
# Tombol pilih file output
self.output_button = tk.Button(self.file_frame, text="Pilih File Output", command=self.buka_file_output, bg="#4CAF50", fg="white", width=15)
self.output_button.grid(row=1, column=0, padx=5, pady=5, sticky="w")
self.output_label = tk.Label(self.file_frame, text="File output belum dipilih", bg="#f0f0f5", font=self.label_font, fg="#666", anchor="w")
self.output_label.grid(row=1, column=1, padx=10, sticky="w")
# Checkbox untuk memilih apakah teks asli akan ditampilkan
self.include_original = tk.BooleanVar()
self.include_original_checkbox = tk.Checkbutton(root, text="Sertakan teks asli dalam output", variable=self.include_original, bg="#f0f0f5", font=self.label_font, anchor="w")
self.include_original_checkbox.pack(fill="x", padx=10, pady=5)
# Frame untuk tombol terjemahkan
self.translate_frame = tk.Frame(root, bg="#f0f0f5")
self.translate_frame.pack(fill="x", padx=10, pady=5)
self.translate_button = tk.Button(self.translate_frame, text="Terjemahkan", command=self.terjemahkan_per_paragraf, bg="#1E90FF", fg="white", font=self.label_font, width=15)
self.translate_button.grid(row=0, column=0, padx=5, pady=5, sticky="w")
# Progress bar dan label progres
self.progress = ttk.Progressbar(root, orient="horizontal", length=500, mode="determinate")
self.progress.pack(padx=10, pady=10)
self.progress_label = tk.Label(root, text="Progres: 0%", font=self.label_font, bg="#f0f0f5", anchor="w")
self.progress_label.pack(fill="x", padx=10, pady=5)
def center_window(self):
screen_width = self.root.winfo_screenwidth()
screen_height = self.root.winfo_screenheight()
window_width = 500
window_height = 450
center_x = (screen_width - window_width) // 2
center_y = (screen_height - window_height) // 2
self.root.geometry(f"{window_width}x{window_height}+{center_x}+{center_y}")
def buka_file_input(self):
self.input_file_path = filedialog.askopenfilename(filetypes=[("Text Files", "*.txt")])
if self.input_file_path:
self.input_label.config(text=f"File input: {self.input_file_path}")
else:
self.input_label.config(text="File input belum dipilih")
def buka_file_output(self):
self.output_file_path = filedialog.asksaveasfilename(defaultextension=".txt", filetypes=[("Text Files", "*.txt")])
if self.output_file_path:
self.output_label.config(text=f"File output: {self.output_file_path}")
else:
self.output_label.config(text="File output belum dipilih")
def get_lang_code(self, lang_name):
for code, name in LANGUAGES.items():
if name.capitalize() == lang_name:
return code
return None
def deteksi_bahasa(self, teks):
try:
detected = self.translator.detect(teks)
return detected.lang
except Exception as e:
messagebox.showerror("Error", f"Gagal mendeteksi bahasa: {e}")
return None
def terjemahkan_per_paragraf(self):
if not self.input_file_path or not self.output_file_path:
messagebox.showwarning("Error", "Pilih file input dan file output terlebih dahulu.")
return
dest_code = self.get_lang_code(self.dest_lang.get())
if not dest_code:
messagebox.showwarning("Error", "Pilih bahasa tujuan yang valid.")
return
try:
with open(self.input_file_path, 'r', encoding='utf-8') as infile:
lines = infile.readlines()
if self.src_lang.get() == "Deteksi otomatis":
for line in lines:
line = line.strip()
if line:
src_code = self.deteksi_bahasa(line)
break
else:
src_code = self.get_lang_code(self.src_lang.get())
if not src_code:
messagebox.showwarning("Error", "Gagal mendeteksi bahasa asal.")
return
with open(self.output_file_path, 'w', encoding='utf-8') as outfile:
for idx, paragraph in enumerate(lines):
paragraph = paragraph.rstrip()
if paragraph:
if self.include_original.get():
outfile.write(f"{paragraph}\n")
translated_text = self.translator.translate(paragraph, src=src_code, dest=dest_code).text
outfile.write(f"{translated_text}\n\n")
else:
outfile.write("\n")
progress = int((idx + 1) / len(lines) * 100)
self.progress['value'] = progress
self.progress_label.config(text=f"Progres: {progress}%")
self.root.update_idletasks()
messagebox.showinfo("Berhasil", "Terjemahan berhasil disimpan.")
except Exception as e:
messagebox.showerror("Error", f"Terjadi kesalahan saat menerjemahkan teks: {e}")
# Main program
if __name__ == "__main__":
root = tk.Tk()
app = TranslatorApp(root)
root.mainloop()