Advertisement
here2share

# tk_quick_code_modify.py

May 16th, 2025 (edited)
373
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.01 KB | None | 0 0
  1. # tk_quick_code_modify.py
  2.  
  3. import tkinter as tk
  4. from tkinter import scrolledtext, messagebox, ttk
  5.  
  6. root = tk.Tk()
  7. root.title("Code Modify")
  8. root.geometry("1200x640+0+0")
  9.  
  10. original_code = ""
  11. modifier_code = ""
  12. finalized_code = ""
  13.    
  14. # Demo original HTML code
  15. demo_original_html = """<!DOCTYPE html>
  16. <html>
  17. <head>
  18.     <title>Original Page</title>
  19.     <meta charset="UTF-8">
  20.     <style>
  21.         body { font-family: Arial; }
  22.         .header { color: blue; }
  23.     </style>
  24. </head>
  25. <body>
  26.     <div class="header">Welcome</div>
  27.    
  28.     <script>
  29.         function originalFunction() {
  30.             console.log("Original code");
  31.             // More original code here
  32.             return true;
  33.         }
  34.     </script>
  35. </body>
  36. </html>"""
  37.    
  38. # Demo modifier HTML code
  39. demo_modifier_html = """<!DOCTYPE html>
  40. <html>
  41. <head>
  42.     <!-- Keep existing head content -->
  43.     <link rel="stylesheet" href="new-styles.css">
  44. </head>
  45. <body>
  46.     <div class="header">Welcome (Modified)</div>
  47.    
  48.     <script>
  49.         function newFeature() {
  50.             console.log("Added feature");
  51.         }
  52.        
  53.         // Keep rest of the original code
  54.     </script>
  55. </body>
  56. </html>"""
  57.  
  58. # Demo original Python code
  59. demo_original_py = """# Python Application
  60. import os
  61. import sys
  62.  
  63. class MyClass:
  64.    def __init__(self, name):
  65.        self.name = name
  66.  
  67.    def greet(self):
  68.        print(f"Hello, {self.name}")
  69.        
  70. def main_function():
  71.    # This is the main logic
  72.    print("Running original main_function")
  73.    instance = MyClass("Original")
  74.    instance.greet()
  75.  
  76. def original_function(x, y):
  77.     return (x ** y) / 2
  78. """
  79.  
  80. # Demo finalized Python code
  81. demo_modifier_py = """# Python Application (Modified)
  82. # Keep existing imports
  83. import json # New import
  84.  
  85. class MyClass:
  86.    def __init__(self, name, age=0): # Modified constructor
  87.        self.name = name
  88.        self.age = age
  89.  
  90.    def greet(self):
  91.        print(f"Hello, {self.name}, you are {self.age} years old.") # Modified greet
  92.  
  93.    def new_method(self): # New method
  94.        print("This is a new method.")
  95.        
  96. def main_function():
  97.    # This is the modified main logic
  98.    print("Running MODIFIED main_function")
  99.    instance = MyClass("Modified", 30)
  100.    instance.greet()
  101.    instance.new_method() # Call new method
  102.    # Keep existing main_logic content (if any was meant to be kept below this point)
  103. """
  104.  
  105. def show_code(widget, code):
  106.     widget.delete(1.0, tk.END)
  107.     widget.insert(tk.END, code)
  108.     root.update()
  109.  
  110. def load_py_demo():
  111.     load(original_text, demo_original_py)
  112.     load(modifier_text, demo_modifier_py)
  113.  
  114. def load_html_demo():
  115.     load(original_text, demo_original_html)
  116.     load(modifier_text, demo_modifier_html)
  117.  
  118. def load(widget, text=''):
  119.     global original_code, modifier_code, finalized_code
  120.     if not text:
  121.         msg = "Code processed and merged with original"
  122.         try:
  123.             text = root.clipboard_get()
  124.         except tk.TclError:
  125.             messagebox.showerror("Clipboard Error", "No text in clipboard or clipboard access denied")
  126.             status.config(text="Failed to access clipboard")
  127.             return
  128.         except Exception as e:
  129.             messagebox.showerror("Error", f"An error occurred: {str(e)}")
  130.             status.config(text="Error occurred")
  131.             return
  132.     else:
  133.         msg = "Demo loaded - differences automatically highlighted"
  134.        
  135.     try:
  136.         text = text.encode('utf-8', errors='ignore').decode('utf-8')
  137.     except:
  138.         text = text.encode('latin-1', errors='ignore').decode('latin-1', errors='ignore')
  139.    
  140.     text = ''.join(char for char in text if char.isprintable() or char in '\n\r\t')
  141.    
  142.     if widget == original_text:
  143.         show_code(original_text, text)
  144.         show_code(modifier_text, '')
  145.         show_code(finalized_text, '')
  146.         notebook.select(original_frame)
  147.         original_code = demo_original_html
  148.         status.config(text="Original code loaded from clipboard")
  149.     else:
  150.         if not original_code:
  151.             messagebox.showwarning("Warning", "Please load original code first")
  152.             status.config(text="Load original code first")
  153.             return
  154.            
  155.         modifier_code = text
  156.         show_code(modifier_text, modifier_code)
  157.        
  158.         finalized_code = process_modifier_code()
  159.        
  160.         show_code(finalized_text, finalized_code)
  161.         status.config(text=msg)
  162.        
  163.         highlight_diffs()
  164.  
  165. def process_modifier_code():
  166.     result_lines = []
  167.     original_lines = original_code.splitlines()
  168.     modifier_lines = modifier_code.splitlines()
  169.    
  170.     def add_line(line):
  171.         result_lines.append(line)
  172.  
  173.     i = 0
  174.     while i < len(modifier_lines):
  175.         line = modifier_lines[i]
  176.        
  177.         if first_str_in_str(keep, line.lower()):
  178.             tag = get_word(line, 'content', step=(-1))
  179.             tag_start, tag_end = find_section(original_lines, tag)
  180.             if tag_start != -1:
  181.                 if i > 0 and modifier_lines[i-1].strip().startswith(f"<{tag}"):
  182.                     add_line(modifier_lines[i-1])
  183.                 result_lines.extend(original_lines[tag_start+1:tag_end])
  184.                 i += 1
  185.                 while i < len(modifier_lines) and f"</{tag}>" not in modifier_lines[i]:
  186.                     add_line(modifier_lines[i])
  187.                     i += 1
  188.                 if i < len(modifier_lines):
  189.                     add_line(modifier_lines[i])
  190.                 i += 1
  191.                 continue
  192.         elif i < len(result_lines):
  193.             if result_lines[i] != result_lines[i-1]:
  194.                 add_line(line)
  195.         else:
  196.             add_line(line)
  197.         i += 1
  198.  
  199.     return "\n".join(result_lines)
  200.  
  201. def find_section(lines, section):
  202.     section = section.lower()
  203.     start_tag = f"<{section}>"
  204.     end_tag = f"</{section}>"
  205.    
  206.     start_idx = -1
  207.     end_idx = -1
  208.    
  209.     for i, line in enumerate(lines):
  210.         if start_tag in line.lower():
  211.             start_idx = i
  212.         if end_tag in line.lower() and start_idx != -1:
  213.             end_idx = i
  214.             break
  215.    
  216.     return start_idx, end_idx
  217.  
  218. def find_context_in_original(original_code, context):
  219.     if not context:
  220.         return 0
  221.    
  222.     for i in range(len(original_code) - len(context_lines), -1, -1):
  223.         match = True
  224.         for j in range(len(context_lines)):
  225.             if original_code[i+j].strip() != context_lines[j].strip():
  226.                 match = False
  227.                 break
  228.         if match:
  229.             return i + len(context_lines)
  230.    
  231.     return -1
  232.  
  233. def highlight_diffs():
  234.     if not modifier_code:
  235.         return
  236.    
  237.     def mark(widget, s1, s2):
  238.         s2 = [s.strip() for s in s2.splitlines()]
  239.         line_num = 0
  240.         for line in s1.splitlines():
  241.             line_num += 1
  242.             s = line.strip()
  243.             if first_str_in_str(keep, s.lower()):
  244.                 pass
  245.             elif s not in s2:
  246.                 widget.tag_add("changed", f"{line_num}.0", f"{line_num}.end")
  247.    
  248.     original_text.tag_remove("changed", "1.0", tk.END)
  249.     modifier_text.tag_remove("changed", "1.0", tk.END)
  250.     finalized_text.tag_remove("changed", "1.0", tk.END)
  251.    
  252.     original_text.tag_config("changed", background="#ffaaaa")
  253.     modifier_text.tag_config("changed", background="#c8e6c9")
  254.     finalized_text.tag_config("changed", background="#c8e6c9")
  255.        
  256.     mark(original_text, original_code, finalized_code)
  257.     mark(modifier_text, modifier_code, original_code)
  258.     mark(finalized_text, finalized_code, original_code)
  259.  
  260. def export_result():
  261.     if not modifier_code:
  262.         messagebox.showwarning("Warning", "No modifier code to copy")
  263.         status.config(text="No modifier code to copy")
  264.         return
  265.    
  266.     try:
  267.         root.clipboard_clear()
  268.         root.clipboard_append(modifier_code)
  269.         status.config(text="Finalized code copied to clipboard")
  270.     except Exception as e:
  271.         messagebox.showerror("Error", f"Failed to copy to clipboard: {str(e)}")
  272.         status.config(text="Error copying to clipboard")
  273.  
  274. def get_word(text, focus, step=(-1)):
  275.     words = text.split()
  276.    
  277.     if focus not in words:
  278.         return ''
  279.  
  280.     index = words.index(focus)
  281.    
  282.     if 0 <= index + step < len(words):
  283.         return words[index + step]
  284.     return ''
  285.    
  286. def first_str_in_str(strings, target):
  287.     for s in strings:
  288.         if target.strip().startswith(s):
  289.             return s
  290.     return None
  291.    
  292. keep = ["<!-- keep ", "// keep ", "# keep "]
  293.  
  294. button_frame = tk.Frame(root)
  295. button_frame.pack(fill=tk.X, padx=5, pady=5)
  296.  
  297. notebook = ttk.Notebook(root)
  298. notebook.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
  299.  
  300. original_frame = ttk.Frame(notebook)
  301. original_text = scrolledtext.ScrolledText(original_frame, wrap=tk.WORD, font=('Consolas', 10), bg="#f5f5f5", fg="#aa0000")
  302. original_text.pack(fill=tk.BOTH, expand=True)
  303. notebook.add(original_frame, text="Original Code")
  304.  
  305. modifier_frame = ttk.Frame(notebook)
  306. modifier_text = scrolledtext.ScrolledText(modifier_frame, wrap=tk.WORD, font=('Consolas', 10), bg="#fffde7")
  307. modifier_text.pack(fill=tk.BOTH, expand=True)
  308. notebook.add(modifier_frame, text="Modifier Code")
  309.  
  310. finalized_frame = ttk.Frame(notebook)
  311. finalized_text = scrolledtext.ScrolledText(finalized_frame, wrap=tk.WORD, font=('Consolas', 10), bg="#f5f5f5")
  312. finalized_text.pack(fill=tk.BOTH, expand=True)
  313. notebook.add(finalized_frame, text="Finalized Result")
  314.  
  315. status = tk.Label(root, text="Ready...", bd=1, relief=tk.SUNKEN, anchor=tk.W)
  316. status.pack(fill=tk.X)
  317.  
  318. tk.Button(button_frame, text="Load HTML Demo", command=load_html_demo, bg="#e1f5fe").pack(side=tk.LEFT, padx=5)
  319. tk.Button(button_frame, text="Load PYTHON Demo", command=load_py_demo, bg="#e1f5fe").pack(side=tk.LEFT, padx=5)
  320. tk.Button(button_frame, text="Paste Original", command=lambda: load(original_text), bg="#fce4ec").pack(side=tk.LEFT, padx=5)
  321. tk.Button(button_frame, text="Paste Modifier", command=lambda: load(modifier_text), bg="#fffde7").pack(side=tk.LEFT, padx=5)
  322. tk.Button(button_frame, text="Copy Result", command=export_result, bg="#e8f5e9").pack(side=tk.LEFT, padx=5)
  323.  
  324. root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement