"Preventing Unwanted PDF Path Prompt in Non-Dispute Modes in Python CLI Application"

The PDF path prompt keeps popping up no matter what mode the program enters… I’m not sure how to resolve this and need some assistance. I know this isn’t API specific so I hope there’s no issue I’m really just stuck and frustrated.

import argparse
import os
import openai
import pandas as pd
from dotenv import load_dotenv
from colorama import Fore, Style
from test import choose_account, generate_dispute_letters, extract_tables_from_pdf, extract_info_from_dataframe

def process_tables(tables):
        dfs = []
        for table in tables:
            column_names = [item for sublist in table[:17] for item in sublist]
            df = pd.DataFrame(table[17:], columns=column_names)
            dfs.append(df)
        return dfs

def main():
    load_dotenv()
    openai.api_key = os.getenv("OPENAI_API_KEY")

     # Create a top-level parser
    parser = argparse.ArgumentParser(description="Dispute GPT")
    subparsers = parser.add_subparsers(dest='mode', help='The mode to enter (dispute, chat and/or manual)')

    # Create a parser for 'dispute' mode and add the --pdf_path argument
    dispute_parser = subparsers.add_parser('dispute')
    dispute_parser.add_argument('--pdf_path', type=str, required=True, help='The path to the PDF file (required in dispute mode)')

    # Create parsers for 'chat' and 'manual' modes (no additional arguments needed)
    chat_parser = subparsers.add_parser('chat')
    manual_parser = subparsers.add_parser('manual')

    # Parse the command-line arguments
    args = parser.parse_args()


    print(f"{Fore.CYAN} Selected mode: {args.mode}")
    divider = "---------------------------------------------------------------"
    print(divider)
    print(f"{Fore.LIGHTWHITE_EX} Welcome to the Dispute GPT!")
    divider = "---------------------------------------------------------------"
    print(divider)
    print(f"{Fore.LIGHTWHITE_EX}Description: This tool is designed to help users generate dispute letters by extracting derogatory accounts from credit profile PDF (Experian, mainly) allowing the user to pick which account they want to dispute, create a custom prompt with a custom action & issue or dispute reason then having GPT 3.5 take care of the letter creation.")  # Replace with your actual instructions
    divider = "---------------------------------------------------------------"
    print(divider)
    print(f"{Fore.LIGHTYELLOW_EX}Usage:")
    print(f"{Fore.LIGHTYELLOW_EX}1. To generate dispute letters, run {Fore.LIGHTRED_EX}'dispute' mode with 'python cli.py --mode dispute --pdf_path /path/to/your/file.pdf")
    print(f"{Fore.LIGHTYELLOW_EX}2. To enter chat mode for interactive conversation, use the -c or --chat option.")
    print("   In chat mode, you can ask questions and get assistance from the AI.")
    print("3. Type 'quit' to exit chat mode at any time.")
    divider = f"{Fore.LIGHTWHITE_EX}---------------------------------------------------------------"
    print(divider)
   
     
    
    if args.mode == 'dispute':
         
           pdf_path = args.pdf_path
           if not pdf_path or not os.path.isfile(pdf_path):
             print(f"{Fore.LIGHTRED_EX}Error: The specified file '{pdf_path}' does not exist.")
             return

           tables = extract_tables_from_pdf(pdf_path)
           dfs = process_tables(tables)

           extracted_info_list = []
           for df in dfs:
             extracted_info = extract_info_from_dataframe(df)
             if any('Status' in info[0] and ('Account charged off' in info[1] or 'Collection account' in info[1]) for info in extracted_info):
                 extracted_info_list.append(extracted_info)
       
       
    elif args.mode == 'chat':

        def chat_with_openai(message):
            response = openai.ChatCompletion.create(
                model="gpt-3.5-turbo",
                messages=[
                    {"role": "system", "content": "You are a helpful assistant."},
                    {"role": "user", "content": message},
                ]
            )
            return response['choices'][0]['message']['content']

        print(f"{Fore.BLUE}Entering chat mode. Type 'quit' to exit.")
        while True:
            user_message = input(f"{Fore.CYAN}User: ")
            if user_message.lower() == "quit":
                break
            response = chat_with_openai(user_message)
            print(f"{Fore.LIGHTMAGENTA_EX}AI: ", response)
            print(divider)
        return

    elif args.mode == 'manual':
      
        # Prompt the user to manually enter the account details
        account_name = input("Enter the account name: ")
        account_number = input("Enter the account number: ")
        status = input("Enter the account status: ")

        # Create a list to hold the manually entered account details
        manual_account = [("Account name", account_name), ("Account Number", account_number), ("Status", status)]

        # Add the manually entered account to the extracted_info_list
        extracted_info_list = [manual_account]

        # The rest of the code is similar to the 'dispute mode'
        for extracted_info in extracted_info_list:
            print(f"{Fore.LIGHTYELLOW_EX}Account Information: ")
            for info in extracted_info:
                print(f"{Fore.LIGHTWHITE_EX}{info[0]}: {info [1]}")
        print(divider)

        # Prompt the user to choose an entity and to input the action and issue
        chosen_account_info = choose_account(extracted_info)
        actions = generate_dispute_letters(chosen_account_info, actions)

        # Generate the dispute letter using chosen account and actions
        dispute_letter = generate_dispute_letters(chosen_account_info, actions)
        print(dispute_letter)
    
           

if __name__ == "__main__":
    main()   

Python isn’t my go-to language, but this is what GPT-4 gave me. Helpful?

It seems you are experiencing an issue with the pdf_path prompt popping up, regardless of the mode entered.

Here’s a potential solution:

  1. Requiring PDF Path Only in Dispute Mode: Currently, you have required the pdf_path only in the dispute mode. So when the dispute mode is not used, it shouldn’t ask for it. However, ensure you aren’t mistakenly providing the --pdf_path argument in other modes.
  2. Check Command-Line Input: Ensure you’re entering the correct command. If you enter python cli.py --mode dispute, it will ask for the PDF path because it’s required in dispute mode. For chat mode, the command should be python cli.py chat and for manual mode python cli.py manual.
  3. Modify argparse Configuration:
  • Instead of using subparsers.add_parser('dispute'), you can directly add the argument to the main parser. This will mean that the pdf_path argument is always expected, regardless of mode.
  • To fix this, you could add a condition to check the args.mode and only require the pdf_path when in dispute mode.

Here’s a potential solution for the third point:

After your current parser setup

if args.mode == 'dispute' and not args.pdf_path:
    print(f"{Fore.LIGHTRED_EX}Error: You must specify a PDF path in 'dispute' mode using the --pdf_path argument.")
    return

Make sure this check comes immediately after the args = parser.parse_args() line.

Remember, this is based on the code you provided. It might be possible that there’s some external code or environment causing the issue, but from the information given, the above steps should help you troubleshoot the problem. If the issue persists, you might want to add more debugging prints to better understand the flow of your code and see where the unexpected behavior is coming from.

I’ll check it out. Thank you.

1 Like