fix this code import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import os
import threading
import fitz  # Import PyMuPDF 
import logging

# Configure logging to a file with improved formatting
logging.basicConfig(filename='pdf_to_markdown_converter.log',
                    level=logging.DEBUG,
                    format='%(asctime)s - %(levelname)s - %(message)s')

def pdf_to_markdown(pdf_path, md_path):
    """Converts a PDF file to a Markdown file using PyMuPDF."""
    try:
        doc = fitz.open(pdf_path)
        md_content = ""
        for page_num in range(doc.page_count):
            logging.info(f"Processing page {page_num + 1} of {pdf_path}")
            page = doc.load_page(page_num)
            text = page.get_text("text")  

            if text:
                # Replace special characters for better Markdown compatibility
                # (You might need to adjust these replacements depending on the output)
                for char, replacement in [
                    ('\u2022', '*'), ('\u2013', '-'), ('\u2014', '-'),
                    ('\u2018', "'"), ('\u2019', "'"), ('\u201c', '"'), ('\u201d', '"')
                ]:
                    text = text.replace(char, replacement)
                md_content += text.strip() + "\n\n"  # Add double newline for paragraph breaks

        with open(md_path, "w", encoding="utf-8") as md_file:
            md_file.write(md_content)
        logging.info(f"Successfully converted {pdf_path} to {md_path}")

    except Exception as e:
        logging.error(f"Error converting {pdf_path}: {e}")
        # Handle errors gracefully in the GUI thread
        tk.messagebox.showerror("Error", f"Failed to convert {pdf_path}: {e}")


def browse_pdf_folder():
    """Opens a file dialog to select the PDF folder and updates the label."""
    try:
        folder_path = filedialog.askdirectory(title="Select PDF Folder")
        if folder_path:
            pdf_folder_label.config(text=folder_path)
    except Exception as e:
        logging.error(f"Error browsing for PDF folder: {e}")
        tk.messagebox.showerror("Error", f"An error occurred while selecting the PDF folder: {e}")

def browse_md_folder():
    """Opens a file dialog to select the output Markdown folder and updates the label."""
    try:
        folder_path = filedialog.askdirectory(title="Select Output Markdown Folder")
        if folder_path:
            md_folder_label.config(text=folder_path)
    except Exception as e:
        logging.error(f"Error browsing for output folder: {e}")
        tk.messagebox.showerror("Error", f"An error occurred while selecting the output folder: {e}")

def convert_pdfs():
    """Converts PDFs in the selected folder to Markdown files in the output folder."""
    try:
        pdf_folder = pdf_folder_label.cget("text")
        md_folder = md_folder_label.cget("text")

        if not pdf_folder or not md_folder:
            tk.messagebox.showerror("Error", "Please select both input and output folders.")
            return

        pdf_files = [f for f in os.listdir(pdf_folder) if f.endswith(".pdf")]
        progress_bar["value"] = 0
        progress_bar["maximum"] = len(pdf_files)

        def conversion_thread():
            for filename in pdf_files:
                pdf_path = os.path.join(pdf_folder, filename)
                md_path = os.path.join(md_folder, os.path.splitext(filename)[0] + ".md")
                try:
                    pdf_to_markdown(pdf_path, md_path)
                finally: 
                    progress_bar.step()
                    window.update_idletasks()
            tk.messagebox.showinfo("Success", "Conversion complete!")

        if not pdf_files:
            tk.messagebox.showwarning("Warning", "No PDF files found in the selected folder.")
        else:
            threading.Thread(target=conversion_thread).start()

    except Exception as e:
        logging.error(f"Unexpected error during conversion: {e}")
        tk.messagebox.showerror("Error", f"An unexpected error occurred: {e}")

def clear_selections():
    """Clears the selected folder paths in the labels."""
    pdf_folder_label.config(text="Select PDF Folder")
    md_folder_label.config(text="Select Output Markdown Folder")

# Create the main window
window = tk.Tk()
window.title("PDF to Markdown Converter")

# PDF folder selection
pdf_folder_frame = tk.Frame(window)
pdf_folder_frame.pack(pady=10)
tk.Label(pdf_folder_frame, text="PDF Folder:").pack(side=tk.LEFT)
pdf_folder_label = tk.Label(pdf_folder_frame, text="Select PDF Folder", relief=tk.SUNKEN, width=40)
pdf_folder_label.pack(side=tk.LEFT, padx=5)
tk.Button(pdf_folder_frame, text="Browse...", command=browse_pdf_folder).pack(side=tk.LEFT)

# Markdown folder selection
md_folder_frame = tk.Frame(window)
md_folder_frame.pack(pady=10)
tk.Label(md_folder_frame, text="Output Folder:").pack(side=tk.LEFT)
md_folder_label = tk.Label(md_folder_frame, text="Select Output Markdown Folder", relief=tk.SUNKEN, width=40)
md_folder_label.pack(side=tk.LEFT, padx=5)
tk.Button(md_folder_frame, text="Browse...", command=browse_md_folder).pack(side=tk.LEFT)

# Convert button
tk.Button(window, text="Convert PDFs", command=convert_pdfs).pack(pady=20)

# Progress bar with taller frame
progress_frame = tk.Frame(window)
progress_frame.pack(pady=10)
progress_bar = ttk.Progressbar(progress_frame, orient="horizontal", length=300, mode="determinate")
progress_bar.pack()

# Clear button
tk.Button(window, text="Clear", command=clear_selections).pack()

window.mainloop()