import os
import sys
import subprocess
import tkinter as tk
from tkinter import *
from tkinter import font
from tkinter.ttk import *
from tkinter import filedialog
import re
import chardet
import glob
from concurrent.futures import ProcessPoolExecutor, as_completed
import mmap
from collections import deque

def check_file(file_path, regex_secret, processed_matches):
    results = []
    if os.path.splitext(file_path)[1].lower() in [".java", ".txt", ".xml", ".json", ".js", ".yaml", ".yml"]:
        if os.path.getsize(file_path) > 0:
            with open(file_path, 'rb') as f:
                with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as mm:
                    content = bytes(mm)
                    encoding = chardet.detect(content)['encoding']
                    if encoding is None:  # Add this check
                        encoding = 'utf-8'
                    try:
                        content = content.decode(encoding, errors='ignore')
                    except LookupError:
                        content = content.decode('utf-8', errors='ignore')
            for title, pattern in regex_secret.items():
                for match in re.finditer(pattern, content):
                    if match.group() in processed_matches:
                        continue
                    processed_matches.add(match.group())
                    start = match.start()
                    end = match.end()
                    lines = content.split("\n")
                    match_line = ""
                    for i, line in enumerate(lines):
                        if start <= len(line):
                            match_line = line
                            break
                    if match.group() in match_line:
                        fp = "No"
                    else:
                        fp = "Yes"
                    file_path_url = "<a href='file:///"+ file_path.replace("\\", "/") + "' target='_blank'>" + file_path + "</a>"
                    results.append([title, match.group(), fp, file_path_url])
                    print(f"{title} : {match.group()}")
    return results

def process_files(file_paths, regex_secret):
    results = deque()
    processed_matches = set()
    for file_path in file_paths:
        file_results = check_file(file_path, regex_secret, processed_matches)
        results.extend(file_results)
    return results

class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("APK Scanner")
        self.geometry("200x150")  # Set the window size
        self.eval('tk::PlaceWindow . center') # Center the window on the screen

        self.defaultFont = font.nametofont("TkDefaultFont")
        self.defaultFont.configure(family="Segoe UI", size=14)

        # Create a frame for buttons
        button_frame = Frame(self)
        button_frame.pack()

        # Create and center the browse button
        self.browse_button = Button(button_frame, text="Browse APK", command=self.browse)
        self.browse_button.configure(width=15)
        self.browse_button.pack(side="top", padx=10, pady=10)

        # Create and center the scan button
        self.scan_button = Button(button_frame, text="Scan", command=self.scan)
        self.scan_button.configure(width=15)
        self.scan_button.pack(side="bottom", padx=10, pady=10)

        self.apk_path = None
        self.regex_secret = {
        "Google_Docs_Link": r"https://docs\\.google\\.com/(?:document|spreadsheets|forms|presentation)/d/[a-zA-Z0-9_-]+",
        "UUID_V1": r'^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-1[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$',
        "gocardless-api-token": r'''[\w.-]{0,50}?(?:gocardless)[ \t\w.-]{0,20}[\s'"]{0,3}(?:=|>|:{1,3}=|\|\|:|<=|=>|:|\?=)['"\s=\x60]{0,5}(live_[a-z0-9\-_=]{40})(?:['"\n\r\s\x60;]|$)''',
    }

    def browse(self):
        self.apk_path = filedialog.askopenfilename(filetypes=[("APK files", "*.apk")])
        print(self.apk_path)

    def scan(self):
        if not self.apk_path:
            return

        apk_folder = os.path.splitext(self.apk_path)[0]
        print(apk_folder)
        os.makedirs(apk_folder, exist_ok=True)
        # Run brew install gitleaks 
        subprocess.run("brew install gitleaks", shell=True)
        subprocess.run(["jadx", "-d", apk_folder, self.apk_path], shell=False)

        table_data = []
        result_queue = deque()

        regex_patterns = {k: re.compile(v) for k, v in self.regex_secret.items()}
        with ProcessPoolExecutor() as executor:
            file_paths = list(glob.iglob(os.path.join(apk_folder, "**/*"), recursive=True))
            batch_size = len(file_paths) // 20 + 1
            batches = [file_paths[i:i+batch_size] for i in range(0, len(file_paths), batch_size)]
            futures = [executor.submit(process_files, batch, regex_patterns) for batch in batches]
            for future in as_completed(futures):
                result_queue.extend(future.result())

        while result_queue:
            result = result_queue.popleft()
            table_data.append([result[0], result[1], result[2], f'<a href="{result[3]}" target="_blank">{result[3]}</a>'])

        with open(os.path.join(apk_folder, "result.html"),"w") as f:
            f.write("<html>")
            f.write("<head>")           
            f.write('    <meta charset="utf-8">    <meta name="viewport" content="width=device-width,initial-scale=1.0">    <link rel="stylesheet" href="../assets/js/plugins/datatables-bs5/css/dataTables.bootstrap5.min.css">    <link rel="stylesheet" href="../assets/js/plugins/datatables-buttons-bs5/css/buttons.bootstrap5.min.css">    <link rel="stylesheet" href="../assets/js/plugins/datatables-responsive-bs5/css/responsive.bootstrap5.min.css"> <link rel="stylesheet" id="css-main" href="../assets/css/oneui.min.css">   </head>')
            f.write('   <body ng-app="appProperty" ng-controller="ctrlProperty">        <main id="main-container">')
            f.write('        <div class="bg-body-light">          <div class="content content-full">            <div class="d-flex flex-column flex-sm-row justify-content-sm-between align-items-sm-center py-2">              <div class="flex-grow-1">                <h1 class="h3 fw-bold mb-2">                  Leaked API Keys                </h1>                <h2 class="fs-base lh-base fw-medium text-muted mb-0">                  Tables transformed with dynamic features.                </h2>              </div>              <nav class="flex-shrink-0 mt-3 mt-sm-0 ms-sm-3" aria-label="breadcrumb">                <ol class="breadcrumb breadcrumb-alt">                  <li class="breadcrumb-item">                    <a class="link-fx" href="javascript:void(0)">Tables</a>                  </li>                  <li class="breadcrumb-item" aria-current="page">                    Leaked API Keys                  </li>                </ol>              </nav>            </div>          </div>        </div>')
            f.write('        <div class="content">          <div class="block block-rounded">            <div class="block-header block-header-default">              <h3 class="block-title">Dynamic Table <small>Full</small></h3>            </div>            <div class="block-content block-content-full">')
            f.write('<table id="resultTable" style="max-width: 2000px; table-layout: fixed; word-wrap: break-word; text-overflow: ellipsis; overflow: hidden;" class="table table-bordered table-striped table-vcenter js-dataTable-full" datatable="ng" dt-options="vm.dtOptions" ng-init="findall()">')
            f.write("<thead>")
            f.write('<tr><th class="text-center" style="width: 30px;">Title</th><th class="text-center" style="width: 100px;">Result/Leaked Key</th><th class="text-center" style="width: 10px;">FP</th><th class="text-center" style="width: 80px;">Filename</th></tr>')
            f.write("</thead>")
            f.write('<tbody ng-repeat="row in rows">')
            for row in table_data:
                f.write("<tr>")
                for cell in row:
                    f.write(f'<td class="d-none d-sm-table-cell fs-sm">{cell}</td>')
                f.write("</tr>")
            f.write("</tbody>")
            f.write("</table>")
            f.write('            </div>          </div>        </div>       </main>')
            f.write('    <script src="../assets/js/oneui.app.min.js"></script>    <script src="../assets/js/lib/jquery.min.js"></script>    <script src="../assets/js/plugins/datatables/jquery.dataTables.min.js"></script>    <script src="../assets/js/plugins/datatables-bs5/js/dataTables.bootstrap5.min.js"></script>    <script src="../assets/js/plugins/datatables-responsive/js/dataTables.responsive.min.js"></script>    <script src="../assets/js/plugins/datatables-responsive-bs5/js/responsive.bootstrap5.min.js"></script>    <script src="../assets/js/plugins/datatables-buttons/dataTables.buttons.min.js"></script>    <script src="../assets/js/plugins/datatables-buttons-bs5/js/buttons.bootstrap5.min.js"></script>    <script src="../assets/js/plugins/datatables-buttons-jszip/jszip.min.js"></script>    <script src="../assets/js/plugins/datatables-buttons-pdfmake/pdfmake.min.js"></script>    <script src="../assets/js/plugins/datatables-buttons-pdfmake/vfs_fonts.js"></script>    <script src="../assets/js/plugins/datatables-buttons/buttons.print.min.js"></script>    <script src="../assets/js/plugins/datatables-buttons/buttons.html5.min.js"></script>    <script src="../assets/js/pages/be_tables_datatables.min.js"></script>')
            f.write('</body>')
            f.write('<script>table.destroy(); $(document).ready(function() {$')
            f.write('#resultTable')
            f.write('.DataTable({"order": [[ 0, "asc" ]],"paging": true,"searching": true,"autoWidth": true,"pageLength": 100});});</script>')            
            f.write("</html>")

        print("Scan completed successfully!")
        print("Result saved at: " + os.path.join(apk_folder, "result.html"))
        self.destroy()  # Exit the Tkinter app

        # Change directory to apk_folder
        os.chdir(apk_folder)

        # Run gitleaks command
        subprocess.run(["gitleaks", "detect", "--no-git", "--report-path", os.path.join(apk_folder, "gitleaks-result.json")])
        print("Gitleaks scan completed successfully!")
        print("Result saved at: " + os.path.join(apk_folder, "gitleaks-result.json"))
        sys.exit()

if __name__ == "__main__":
    app = App()
    app.mainloop()

---

I am a Bug Hunter. Convert this python script to a script that accepts /path/to/a/file with any extension and then scan that file for any regex match to search for hardcoded keys or credentials.
Then print the matched key on the cli. I don't want any report or anything. Make sure it works no matter what. Handle everything, every exception, every error.