ChatGPT / Scripts · 12 9 月, 2023 0

Let ChatGPT Help Merge Its Own Python Script

An AI Journey from Code Generation to Code Merging

Introduction

Imagine a world where not only can AI assist you in generating Python scripts, but it can also merge two versions of a script for you. Sounds too good to be true? Welcome to my recent adventure with ChatGPT, where the AI not only wrote a Python script for me but also automated the process of merging it with another version. Intrigued? Read on to find out more about this fun-filled AI expedition!

ChatGPT: More Than Just a Chat Buddy

When I first encountered ChatGPT, I assumed it was merely a conversational AI model. However, I quickly discovered its capabilities extended far beyond idle chatter. I presented ChatGPT with a programming task: to merge two versions of a Python script—one original and the other new, with placeholders to be replaced.

Guess what? ChatGPT not only quickly understood what I wanted, but it also volunteered to write the Python code to merge the scripts!

The AI Programming Adventure

After uploading the two versions of the script to ChatGPT and briefly outlining my requirements, ChatGPT astutely suggested using Python’s `ast` library to parse both scripts and compare their function signatures for accurate merging.

With ChatGPT’s assistance, I crafted a Python script that could automatically read in the two disparate codes and then merge them. Sounds like a dream come true, right?

A Twist in the Tale: Testing and Debugging

But as we all know, the path of programming is rarely straightforward. When we first ran our merging script, we encountered a few glitches. There were mismatches in function signatures and some minor bugs in the original code.

Fear not! ChatGPT was incredibly patient, helping me troubleshoot each issue and suggesting further tests to ensure everything was running smoothly.

The Final Chapter: A Perfect Merge

In the end, we successfully merged both versions of the script without any warnings or errors. I must say, this whole process not only taught me a more efficient way of merging code but also provided a delightful experience of problem-solving in collaboration with AI.

Conclusion

This collaboration with ChatGPT was both enjoyable and highly productive. Not only did I solve a real programming dilemma, but I also learned how to leverage AI for streamlining and automating programming tasks.

If you’re a coding enthusiast or just intrigued by AI, I highly recommend trying out a partnership with ChatGPT. It can serve as a smart coding assistant and possibly become your new best friend!

So, are you ready to code with ChatGPT? Let’s embark on this exciting AI journey together!

**Bonus**: If you’re interested in trying this out for yourself, I’ve attached the source code below along with the ChatGPT conversation [here](https://chat.openai.com/share/870285b7-574a-4d70-86ff-f53b4502ece0). Also, ChatGPT documented this entire experience in this blog post. Happy coding!

import ast
import os

def extract_function_signatures(code):
    tree = ast.parse(code)
    signatures = {}
    for node in ast.walk(tree):
        if isinstance(node, ast.FunctionDef):
            func_name = node.name
            args = [arg.arg for arg in node.args.args]
            signatures[func_name] = args
    return signatures

def compare_signatures(original_signatures, new_signatures):
    issues = []
    for func_name, args in new_signatures.items():
        if func_name not in original_signatures:
            issues.append(f"Function {func_name} exists in new code but not in original code.")
        elif args != original_signatures[func_name]:
            issues.append(f"Signature mismatch for {func_name}: Original {original_signatures[func_name]} != New {args}")
    return issues

def split_code_into_sections(code):
    lines = code.split("\n")
    sections = []
    current_section = []
    for line in lines:
        if line.startswith("def ") or line.startswith("class ") or line.startswith("#"):
            if current_section:
                sections.append("\n".join(current_section).strip())
            current_section = []
            current_section.append(line)
        else:
            current_section.append(line)
    if current_section:
        sections.append("\n".join(current_section).strip())
    return sections

def map_sections(sections):
    section_map = {}
    for section in sections:
        title = section.split("\n")[0].strip()
        section_map[title] = section
    return section_map

def merge_code(original_map, new_map):
    merged_sections = []
    warnings = []
    for section_title, section_content in new_map.items():
        if "pass # 使用您现有的代码来实现这个方法" in section_content or "Existing code ..." in section_content:
            if section_title in original_map:
                original_signatures = extract_function_signatures(original_map[section_title])
                new_signatures = extract_function_signatures(section_content)
                issues = compare_signatures(original_signatures, new_signatures)
                if issues:
                    warnings.extend(issues)
                else:
                    merged_sections.append(original_map[section_title])
            else:
                warnings.append(f"{section_title} exists in new code but not in original code.")
            merged_sections.append(section_content)
        else:
            merged_sections.append(section_content)
    return "\n\n".join(merged_sections), warnings

# Reading the original and new files
with open("path/to/original.py", "r") as f:
    original_code = f.read()

with open("path/to/new.py", "r") as f:
    new_code = f.read()

# Splitting and mapping sections
original_sections = split_code_into_sections(original_code)
new_sections = split_code_into_sections(new_code)
original_map = map_sections(original_sections)
new_map = map_sections(new_sections)

# Merging and testing
merged_code, warnings = merge_code(original_map, new_map)
if warnings:
    print("Warnings:")
    for warning in warnings:
        print(warning)

# Save the merged code to a new file
with open("path/to/merged.py", "w") as f:
    f.write(merged_code)