coba implementasikan di koding ku ini
import os
import time
import random
from datetime import datetime
import geopandas as gpd
import pandas as pd
import textwrap
from tabulate import tabulate
from colorama import Fore, Style, init
from alive_progress import alive_bar
import ctypes
from ctypes import wintypes, windll
import shutil
def set_fixed_size_with_scroll_bar(width=100, height=30, buffer_width=200, buffer_height=50):
"""
Set terminal size to fixed dimensions while enabling horizontal
and vertical scrolling by properly setting the buffer size.
Disable terminal resizing, including via mouse dragging.
"""
# Step 1: Configure terminal size and active screen
os.system(f"mode con: cols={width} lines={height}")
# Step 2: Get handle to the CMD terminal
kernel32 = windll.kernel32
hwnd = kernel32.GetConsoleWindow()
if hwnd:
# a. Set buffer size larger than the window size
kernel32.SetConsoleScreenBufferSize(
kernel32.GetStdHandle(-11), # STD_OUTPUT_HANDLE
wintypes._COORD(buffer_width, buffer_height) # Buffer: Width x Height
)
# b. Modify CMD window style: Disable resizing
GWL_STYLE = -16 # Index for window style
WS_MAXIMIZEBOX = 0x00010000 # Maximize button
WS_SIZEBOX = 0x00040000 # Sizing border (mouse dragging for resize)
user32 = windll.user32
# Get current window style
current_style = user32.GetWindowLongW(hwnd, GWL_STYLE)
# Remove WS_SIZEBOX (to disable mouse resizing) and WS_MAXIMIZEBOX
new_style = current_style & ~WS_SIZEBOX & ~WS_MAXIMIZEBOX
user32.SetWindowLongW(hwnd, GWL_STYLE, new_style)
print(
Fore.LIGHTGREEN_EX
+ f"✅ Terminal fixed to {width}x{height} with scrollbars (buffer = {buffer_width}x{buffer_height}). Resizing disabled!"
)
else:
# c. Handle errors if console handle was not found
print(Fore.RED + "⚠️ Unable to modify terminal resizing. Console handle not found!")
Initialize terminal colors (Colorama)
init(autoreset=True)
Hacker-like system logs for animation
HACKER_LOGS = [
"[DEBUG] Establishing secure connections...",
"[INFO] Authenticating user credentials...",
"[SYSTEM] Compiling core resources...",
"[WARNING] High memory usage detected...",
"[INFO] Validating directory structures...",
"[DEBUG] Allocating server nodes...",
"[SUCCESS] Validation checks completed.",
"[INFO] Shapefile processing in progress...",
"[WARNING] Large data packets detected...",
"[INFO] Directory validation completed successfully...",
"[DEBUG] Framework optimization in progress...",
]
Simulated hacker terminal typing animation
def print_hacker(text):
"""
Hacker-like typing animation with custom user logs.
"""
print(Fore.LIGHTCYAN_EX + "[SYSTEM] Access Granted!")
print(Fore.LIGHTCYAN_EX + "[SYSTEM] Initializing terminal environment...")
for log in random.sample(HACKER_LOGS, 5): # Show random 5 logs
print(Fore.GREEN + log)
time.sleep(0.3)
for char in text:
print(Fore.GREEN + char, end="", flush=True)
time.sleep(0.02)
print("\n")
Display folder structure (Tree View)
def folder_tree(start_path=".", indent=" "):
"""
Display files and folders in a tree structure with animation.
"""
for root, dirs, files in os.walk(start_path):
level = root.replace(start_path, "").count(os.sep)
space = indent * level
folder_name = os.path.basename(root)
print(Fore.LIGHTCYAN_EX + f"{space}📁 {folder_name}")
for file in files:
print(Fore.GREEN + f"{space}{indent}📄 {file}")
time.sleep(0.1) # Smooth animation for folder traversal
Hacker-style loading bar using alive-progress (with simplified ASCII compatibility)
def hacker_loading(total_steps):
"""
Hacker-style progress bar for simulating tasks with ASCII-friendly spinner.
"""
spinner = ['|', '/', '-', '\'] # ASCII spinner for universal compatibility
spinner_index = 0
with alive_bar(total_steps, bar="classic", spinner="classic", title="[PROGRESS] Running system tasks...") as bar:
for step in range(total_steps):
# Simulate random hacker logs during progress
log = random.choice(HACKER_LOGS)
print(Fore.LIGHTBLACK_EX + f"{log} {spinner[spinner_index % len(spinner)]}", end="\r") # Simulate spinner
spinner_index += 1 # Update spinner position
time.sleep(0.2) # Simulate task delay for each step
bar() # Update alive-progress bar
print("\n" + Fore.LIGHTGREEN_EX + "[SUCCESS] Process completed!") # Final message after progress is done
Function to get authority name from .qgz file
def scan_authority():
"""
Detect .qgz file in the root folder and return file's base name
as the 'Authority Reference'.
"""
# Search for .qgz files in the current directory
qgz_files = [f for f in os.listdir('.') if f.endswith('.qgz')]
if not qgz_files:
print(Fore.RED + "❌ No '.qgz' file found in the root folder.")
return None
# Retrieve file name without extension
authority_name = qgz_files[0].rsplit('.', 1)[0]
print(Fore.LIGHTGREEN_EX + f"🔍 Authority Reference: '{authority_name}' detected from file '{qgz_files[0]}'")
return authority_name
Function to list files in a folder or based on file extension
def list_files(folder_path, file_extension=None):
"""
List files by extension or display all files/folders if no extension is provided.
"""
if file_extension is None:
folder_tree(folder_path) # Display folder as tree
else:
return [f for f in os.listdir(folder_path) if f.endswith(file_extension)]
Function to assign numbers to issues in a list
Function to assign numbers to issues in a list
def number_issues(issues):
"""
Format a list of issues into a properly structured list with
manual new lines added explicitly for each issue.
"""
if isinstance(issues, list) and len(issues) > 0:
# Create issues as multiline text with a newline "\n" after each
formatted_issues = "\n".join([
f"{idx + 1}. {issue}" for idx, issue in enumerate(issues)
])
return formatted_issues # No need to strip here
return "No issues found."
Function to wrap text responsively to terminal width
def wrap_text(text, width=50):
"""
Wrap long text into multiple lines if exceeding terminal width.
"""
if isinstance(text, str):
return "\n".join(textwrap.wrap(text, width=width))
elif isinstance(text, list): # If input is a list
wrapped_list = [f"- {t}" for t in text]
return "\n".join(textwrap.wrap("\n".join(wrapped_list), width=width))
return text
Main function: validate shapefiles
def validate_shapefiles():
"""
Validate shapefiles based on the following criteria:
- IDs must not be empty or duplicate
- 'authority' column must exist and not have empty values
- PDF names must exist and match the dataset
- gss_code must remain consistent with the mode
"""
SHAPEFILES_PATH = "./Shapefiles"
DOCUMENTS_PATH = "./Documents"
# Validate folder existence
if not os.path.exists(SHAPEFILES_PATH) or not os.path.exists(DOCUMENTS_PATH):
return Fore.RED + "❌ Error! Ensure 'Shapefiles' and 'Documents' folders are available."
# Scan for authority
authority = scan_authority()
if not authority:
return Fore.RED + "❌ Validation stopped. No Authority Reference found!"
# List all PDFs
pdf_files = list_files(DOCUMENTS_PATH, ".pdf")
if len(pdf_files) == 0:
return Fore.RED + "❌ No PDF files found in the 'Documents' folder!"
# Normalize PDFs (lowercase and replace spaces)
normalized_pdf_files = [
pdf.lower().replace(" ", "-").replace("_", "-").strip()
for pdf in pdf_files
]
# Report Table
report = []
shapefiles = list_files(SHAPEFILES_PATH, ".shp")
if len(shapefiles) == 0:
return Fore.RED + "❌ No shapefiles found in the 'Shapefiles' folder!"
print(Fore.LIGHTCYAN_EX + "🔍 Scanning shapefiles, please wait...")
# Progress Bar
hacker_loading(len(shapefiles))
# Process Validations
issue_count = 0
for shp_file in shapefiles:
file_path = os.path.join(SHAPEFILES_PATH, shp_file)
try:
# Read the shapefile
gdf = gpd.read_file(file_path)
# Validate columns
required_columns = ["id", "Name", "pdf_name", "gss_code", "authority"]
for col in required_columns:
if col not in gdf.columns:
issue_count += 1
report.append([
issue_count, "-", "-", "-",
f"Missing column '{col}' in shapefile '{shp_file}'"
])
continue
# Detect duplicate IDs
duplicates = gdf[gdf["id"].duplicated(keep=False)]
if not duplicates.empty:
for idx, row in duplicates.iterrows():
issue_count += 1
report.append([
issue_count,
row["id"],
row.get("Name", "N/A"),
row.get("pdf_name", "N/A"),
f"Duplicate ID detected: 'id={row['id']}'"
])
# Validate features
gss_mode = gdf["gss_code"].mode()[0]
for idx, feature in gdf.iterrows():
issues = []
fid = feature["id"]
pdf_name = str(feature["pdf_name"]).strip()
current_gss_code = feature["gss_code"]
# Validate gss_code
if current_gss_code != gss_mode:
issues.append(
f"GSS Code mismatch: '{current_gss_code}' (expected '{gss_mode}')"
)
# Validate empty IDs
if pd.isna(fid) or fid == "":
issues.append("Empty ID field detected.")
# Validate authority (specific validation for empty/null authority)
authority_value = feature.get("authority", None)
if pd.isna(authority_value) or authority_value == "":
issues.append("Empty or null 'authority' field detected.")
else:
authority_value = str(authority_value).strip()
if authority_value.lower() != authority.lower():
issues.append(
f"Authority mismatch: '{authority_value}' (expected '{authority}')"
)
# Validate associated PDFs
normalized_pdf_name = pdf_name.lower().replace(" ", "-").replace("_", "-").strip()
if normalized_pdf_name not in normalized_pdf_files:
issues.append(
f"PDF file not found: '{pdf_name}'"
)
# Add row to report if issues exist
if issues:
issue_count += 1
report.append([
issue_count,
fid or "N/A",
feature.get("Name", "N/A"),
pdf_name or "N/A",
number_issues(issues) # Use formatted issues
])
except Exception as e:
issue_count += 1
report.append([
issue_count, "-", "-", "-",
f"Error reading shapefile '{shp_file}': {str(e)}"
])
# No issues found
if not report:
return Fore.GREEN + "✅ No issues found in shapefiles."
# Display results
headers = ["No", "ID", "Name", "PDF Name", "Issues"]
return Fore.RED + "\n🛑 Shapefile Validation Report:\n" + tabulate(
report, headers, tablefmt="fancy_grid", maxcolwidths=[5, 15, 20, 25, None]
)
def auto_destroy():
"""
Auto-destroy the application: Deletes the running script file.
This option requires multiple confirmation steps for security.
"""
print(Fore.LIGHTRED_EX + "\n⚠️ WARNING: You are about to destroy this application!")
print(Fore.LIGHTYELLOW_EX + "Once executed, this action cannot be undone.")
# Confirmation Step 1
confirm = input(Fore.LIGHTCYAN_EX + "\nType 'YES' to proceed with destruction: ")
if confirm.strip().lower() != "yes":
print(Fore.RED + "[CANCELLED] Destruction terminated. Returning to menu...")
time.sleep(1.5)
return
# Confirmation Step 2
confirm_password = input(Fore.YELLOW + "Enter destruction code (e.g., 'KANDO'): ")
if confirm_password.strip() != "KANDO":
print(Fore.RED + "[CANCELLED] Incorrect destruction code. Returning to menu...")
time.sleep(1.5)
return
# Final Confirmation
print(Fore.LIGHTRED_EX + "\n🔥 Executing Application Self-Destruction 🔥...")
hacker_loading(5) # Display loading bar for dramatic effect
# Delete the running Python script
print(Fore.LIGHTRED_EX + "[SELF-DESTRUCT] Deleting the script now...")
current_script = __file__ # Get the path to this script
try:
os.remove(current_script)
print(Fore.LIGHTGREEN_EX + "[SUCCESS] Application destroyed. Goodbye!")
except Exception as e:
print(Fore.RED + f"[ERROR] Failed to delete the script: {e}")
# Exit the program after deletion
print(Fore.LIGHTYELLOW_EX + "Shutting down system...")
time.sleep(2)
os._exit(0) # Force exit the program
Display credits section
def show_credits():
"""
Display credits and a short description of the application's purpose.
"""
os.system("cls" if os.name == "nt" else "clear")
# Header
print(Fore.LIGHTMAGENTA_EX + "⭐ KandoRa v0.1 'Astral Edition' ⭐".center(60))
print(Fore.LIGHTCYAN_EX + "=" * 60)
# Developed by
print(Fore.LIGHTYELLOW_EX + "Developed with ❤️ by:")
print(Fore.LIGHTWHITE_EX + "KandoAlchemist (Developer)")
# Application description
print(Fore.LIGHTCYAN_EX + "\n✨ About KandoRa:")
print(Fore.LIGHTWHITE_EX + textwrap.dedent("""\
KandoRa is a futuristic GIS validation tool designed to simplify
shapefile validation processes. It ensures data integrity, identifies
duplicate IDs, validates PDF metadata, and provides interactive reports
with ease.
"""))
# Acknowledgments
print(Fore.LIGHTCYAN_EX + "\n🚀 Dedicated to:")
print(Fore.LIGHTWHITE_EX + " All GIS enthusiasts and professionals worldwide!")
print(Fore.LIGHTCYAN_EX + "=" * 60)
# Input to return to main menu
input(Fore.LIGHTBLACK_EX + "\nPress Enter to return to the main system...")
def hacker_loading_animation():
"""
Displays a Matrix/hacker-style loading animation to simulate
breaking through security systems.
"""
# Karakter acak Matrix
matrix_characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()-_+=<>?/|\`~"
# Baris kode random Matrix
def generate_random_matrix_line(line_length=60):
return "".join(random.choice(matrix_characters) for _ in range(line_length))
# Loading bar visual
loading_phases = ['[> ]', '[==> ]', '[====> ]', '[======> ]',
'[========> ]', '[=========>]']
# Mulai tampilan animasi
print(Fore.LIGHTGREEN_EX + "\nSystem Booting... Please Wait...\n")
# Proses loading
for phase in loading_phases:
print(Fore.GREEN + generate_random_matrix_line(), end="\r") # Garis Matrix acak
time.sleep(0.2) # Delay Matrix line tampil
print(Fore.LIGHTGREEN_EX + f"\r{phase} Initializing...", end="", flush=True) # Loading bar
time.sleep(0.5) # Delay loading bar
print(Fore.GREEN + generate_random_matrix_line()) # Print karakter acak tambahan langsung
print(Fore.GREEN + generate_random_matrix_line()) # Cetak baris tambahan Matrix
time.sleep(0.5)
print(Fore.LIGHTGREEN_EX + "\nSYSTEM ONLINE. WELCOME.\n" + Style.RESET_ALL) # Selesai
if name == "main":
# Set terminal to fixed dimensions and enable scrolling
set_fixed_size_with_scroll_bar(width=100, height=30, buffer_width=200, buffer_height=50 )
# Hacker-style loading animation before main menu
hacker_loading_animation()
Main Menu Code
while True:
# Fix CMD terminal width at start of the program
os.system("cls" if os.name == "nt" else "clear")
# Header UI
print(Fore.LIGHTMAGENTA_EX + "=" * 60)
print(Fore.LIGHTCYAN_EX + "✨ WELCOME TO ✨".center(60))
print(Fore.LIGHTWHITE_EX + "🌌 KandoRa v0.1 'Astral Edition' 🌌".center(60))
print(Fore.LIGHTMAGENTA_EX + "=" * 60)
# Display Menu Options
print(Fore.LIGHTCYAN_EX + "[1] 🔍 Initialize Shapefile Validation Protocol")
print(Fore.LIGHTCYAN_EX + "[2] 📂 Explore Directory Structure (Tree Mapping)")
print(Fore.LIGHTCYAN_EX + "[3] 🛠️ Access Program Metadata [CREDITS]")
print(Fore.LIGHTRED_EX + "[4] 💀 Terminate Session")
print(Fore.LIGHTRED_EX + "[5] ☠️ Self-Destruct Application")
# User Input
choice = input(Fore.YELLOW + "\nSelect an option [1-5]: ")
if choice == "1":
print(Fore.LIGHTCYAN_EX + "[SYSTEM] Starting shapefile validation...")
result = validate_shapefiles() # Run validation
print(result)
input(Fore.YELLOW + "\n[LOG] Press Enter to return to the main menu...")
elif choice == "2":
print(Fore.LIGHTCYAN_EX + "[SYSTEM] Accessing directory tree view...")
print(Fore.LIGHTCYAN_EX + "🔍 FILE SYSTEM STRUCTURE:")
folder_tree(".")
input(Fore.YELLOW + "\n[LOG] Press Enter to return to the main menu...")
elif choice == "3":
show_credits() # Display Credits Menu
elif choice == "4":
print(Fore.LIGHTCYAN_EX + "[LOG] Ending session...")
print_hacker("Thank you for using KandoRa v0.1 'Astral Edition.' Goodbye Brother!")
break
elif choice == "5":
# Call the auto-destroy function
auto_destroy()
else:
print(Fore.RED + "[ERROR] Invalid input detected. Retrying...")
time.sleep(1.5)