I will provide you the whole codebase of a warframe market programming project that was used to find deals on the website. The project was coded by a beginner and we have to bring it to the highest standards. In short, the idea is not to rewrite the provided code with better syntax, the real idea is to write it from scratch while maintaining functionality and better coding standards, adding a GUI, making it more efficient, etc.


    while True:
        print("Which mode do you want to use?:\n")
        print("1. Find the best ducat/plat items and sellers\n")
        print("2. Scan the market for deals\n")
        print("3. Find the best spare parts to sell in sets\n")
        print("4. Find the best endo/plat mods\n")
        print("5. Scan the best relics to buy and sell\n")
        print("6. Search for your buy orders\n")
        print("7. Autofarm reputation.\n")

        try:
            mode = int(input("Introduce a number: "))
        except ValueError:
            print("Write a number between 1 and 2. \n")
        if 0 < mode < 9:
            break
    if mode == 1:
        from src.ducanator import use_ducanator

        use_ducanator(ask_for_ducat_scan())
    elif mode == 2:
        scan_for_deals()
    elif mode == 3:
        import src.scanners.part_scanner as part_scanner

        part_scanner.part_scanner()
    elif mode == 4:
        endo_scan()
    elif mode == 5:
        import src.scanners.relic_scanner as relic_scanner

        relic_scanner.scan_relics()
    elif mode == 6:
        scan_buys()
    elif mode == 7:
        import src.scanners.part_scanner as part_scanner

        email, password = ask_for_email(), ask_for_pass()
        part_scanner.upvote_farmer(email, password)


def ask_for_email():
    """Asks the user for its wfm email"""

    while True:
        try:
            email = str(
                input(
                    "Introduce the email associated to your warframe.market account: "
                )
            )
        except ValueError:
            print("An error happened when reading your email, please try again. \n")
        if email:
            return email


def ask_for_pass():
    """Asks the user for its wfm password"""

    while True:
        try:
            password = str(getpass("Introduce your password: "))
        except ValueError:
            print("An error happened when reading your password, please try again. \n")
        if password:
            return password


def ask_for_name():
    """Asks the user for its wfm username"""

    while True:
        try:
            name = str(input("Introduce your profile name: "))
        except ValueError:
            print(
                "An error happened when reading your profile name, please try again. \n"
            )
        if name:
            return name


def relist_auctions():
    """Asks the user about its options for relisting"""

    import src.riven_stuff.riven_relisting

    while True:
        print(
            "Do you want to relist all your auctions or only the ones without bids?:\n"
        )
        print("1. All the auctions\n")
        print("2. Only the ones without bid\n")
        try:
            bids = int(input("Introduce a number: "))
        except ValueError:
            print("Write a number between 1 and 2. \n")
        if 0 < bids < 3:
            break

    relist_type = bids == 2
    print("Introduce your warframe.market login credentials:\n")
    email = ask_for_email()
    password = ask_for_pass()
    utils.login(email, password)
    src.riven_stuff.riven_relisting.relist_auctions(relist_type)


# asks the user which kind of search he wants to do.
def define_search():
    """Defines the type of search the user wants to use"""

    while True:
        print("Which search do you want to use?:\n")
        print(
            "1. Fast search (low amount of rivens. specific rolls, unrolleds for wanted weapons, generic godrolls)\n"
        )
        print(
            "2. Slow search (high amount of rivens. will also search for godrolls for the wanted weapons)\n"
        )
        print(
            "3. Specific search (only searches for a weapon or your specific combinations)\n"
        )
        try:
            search_type = int(input("Introduce a number\n"))
        except ValueError:
            print("Write a number between 1 and 5. \n")
        if 0 < search_type < 6:
            break

    if search_type == 2:
        settings.search_type = True
    elif search_type == 3:
        specific_search()
    riv_search()


def specific_search():
    """Gets data needed to execute an specific search"""

    while True:
        print("Do you want to search for a specific weapon or your specific combos? \n")
        print("1. A specific weapon\n")
        print("2. My specific combos\n")
        try:
            specific = int(input())
        except ValueError:
            print("Write a number between 1 and 2\n")
        if specific == 1:
            settings.specific_weapon = True
            weapon_combo()
            break
        if specific == 2:
            settings.specific_search = True
            break


def weapon_combo():
    """Asks the user if he wants a broad search with generic godroll combinations
    or a specific one for the selected weapon."""

    while True:
        try:
            weapon_name = str(
                input("Which weapon do you want to search? write a non variant name\n")
            )
        except ValueError:
            print("Write the name of the weapon you want to search for \n")
        weapon_name = weapon_name.lower().replace(" ", "_")
        if (
            weapon_name in settings.weapons[utils.get_weapon_type(weapon_name)].keys()
            and utils.check_variant(weapon_name) is False
        ):
            settings.weapon_name = weapon_name
            break
        print("Name not valid")

    while True:
        print("Do you want the riven to have specific stats or a generic combo?\n")
        print("1. Specific stats\n")
        print("2. Generic combo\n")
        try:
            stats_type = int(input())
        except ValueError:
            print("Introduce a number between 1 and 2 \n")
        if stats_type == 1:
            ask_for_stats()
            break
        if stats_type == 2:
            break


def ask_for_stats():
    """Asks for the stats to search for the selected weapon.
    A restart option should be added in case the user makes a mistake"""

    print("The list of stats: \n")
    stat_list = [value["name"] for value in settings.stat_list.values()]
    order = ["first positive", "second positive", "third positive", "negative"]
    stat_name = ["stat1", "stat2", "stat3", "negative"]
    thirdpos, neg = 0, 0

    for i, stat in enumerate(stat_list):
        print(str(i) + ". " + stat)
    stat_list = list(settings.stat_list.keys())
    for i in range(4):
        if i == 2:
            while thirdpos not in (1, 2):
                print("Do you want a third positive? \n")
                print("1. Yes")
                print("2. No")
                try:
                    thirdpos = int(input())
                except ValueError:
                    print("Introduce a number between 1 and 2")
                if thirdpos in (1, 2):
                    break
            if thirdpos == 2:
                continue
        if i == 3:
            while neg not in (1, 2):
                print("Do you want a negative? \n")
                print("1. Yes")
                print("2. No")
                try:
                    neg = int(input())
                except ValueError:
                    print("Introduce a number between 1 and 2")
            if neg == 2:
                break
        try:
            statnum = int(input("Write the number of the " + order[i] + "\n"))
        except ValueError:
            print("Introduce a number between 1 and " + str(len(stat_list)))
        if statnum < len(stat_list):
            settings.weapon_stats[stat_name[i]] = (
                stat_list[statnum].lower().replace(" ", "_")
            )


def ask_for_ducat_scan():
    """Asks the user about his ducat limit and the scanning"""

    print(
        "The program will scan the market for items with a ducat value higher than your limit.\n"
    )
    print(
        "At the end of the scan, it'll provide you with a list of the best sellers to buy off the market.\n"
    )
    while True:
        print("Write the ducats/plat ratio you want to search for.\n")
        try:
            ducat_ratio = float(input())
        except ValueError:
            print("Introduce a number between 1 and 2")
        if ducat_ratio >= 0:
            return ducat_ratio


def riv_search():
    """Process used to search for rivens, step by step"""
    import src.request_processor
    import src.riven_stuff.riven_requests
    import src.url_creation

    # gets the urls for the searches we have to do.
    res = src.url_creation.data_creation()
    # requests said searches to the server and returns them.
    res = src.riven_stuff.riven_requests.mass_riven_request(res)
    # processes the requests and converts them into riven objects.
    res = src.request_processor.process_data(res).values()
    # sorts them by price.
    res = sorted(res, key=lambda riven: (riven.buyout_price, riven.real_value))
    # exports them into txt files.
    src.request_processor.export_txt(res)

    print("Rivens found: " + str(len(res)))


def scan_for_deals():
    """Searches for deals in the market"""
    import src.scanners.deal_scanner as deal_scanner

    deal_scanner.deal_finder()


def scan_buys():
    """Searches for good prices the user wants"""
    import src.scanners.buy_scanner as buy_scanner

    buy_scanner.scan_buys(ask_for_name())


def endo_scan():
    """Searches for good endo/plat deals in the market"""
    import src.scanners.endo_scanner as endo_scanner

    while True:
        print(
            "If the program finds an item with a good endo/plat ratio it will save it and show a message."
        )
        print("Type the endo/plat to look for. (default 400)")
        try:
            endo = int(input())
        except ValueError:
            print("Introduce a number between 1 and 2")
        if endo > 0:
            endo_scanner.endo_scan(endo)

``````
------ src/utils.py ------
``````
"""Common methods used by all modules"""

import json
import re

import random

import requests
from ratelimit import limits, sleep_and_retry

import src.settings as settings

jwt_token = None

headerss = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:121.0) Gecko/20100101 Firefox/121.0",
    "Accept": "application/json",
    "Accept-Language": "es-ES,es;q=0.8,en-US;q=0.5,en;q=0.3",
    "Accept-Encoding": "gzip, deflate, br",
    "Referer": "https://warframe.market/",
    "content-type": "application/json",
    "language": "en",
    "platform": "pc",
    "Origin": "https://warframe.market",
    "DNT": "1",
    "Connection": "keep-alive",
    "Sec-Fetch-Dest": "empty",
    "Sec-Fetch-Mode": "cors",
    "Sec-Fetch-Site": "same-site",
    "TE": "trailers",
}

cookies = {
    "language": "en",
    "sessionid": "yoursessionid",
    "csrftoken": "yourtoken",
}
headers = {
    "x-csrftoken": "yourtoken",
    "Connection": "keep-alive",
}
params = {
    "interval": "7 day",
}

ingame_name = None
WFM_API = "https://api.warframe.market/v1/"
RH_API = "https://rivenhunter.com/api/v1/rivensearch/?itemtype="
session = requests.Session()


@sleep_and_retry
# @limits(calls=3, period=1.2)
def get_wfm_request(url):
    """Executes a wfm query"""
    request = session.get(WFM_API + url, stream=True, headers=headerss)
    if request.status_code == 200:
        return request.json()["payload"]
    return None


@sleep_and_retry
def get_rh_request(url):
    """Executes a rh query"""
    request = session.get(
        RH_API + url, params=params, cookies=cookies, headers=headers
    ).json()
    if len(request) != 0 and len(request["data"]) != 0:
        return request["data"]
    return None


def get_weapon(weapon_name):
    """Returns the weapon data given a name"""
    weapon_name = weapon_name.replace("_", " ").title()
    weapon = [x for x in settings.weapons if x["name"] == weapon_name]
    if len(weapon) == 0:
        return None
    return weapon[0]


def get_weapon_type(weapon_name):
    """Returns the weapon type given the name."""
    weapon = get_weapon(weapon_name)
    if weapon is None:
        return 3
    return weapon["weapon_type"]


def check_variant(weapon_name):
    """Returns if the weapon is a variant given the name."""
    weapon_name = weapon_name.replace("_", " ").title()
    family = [w for w in settings.weapons if w["name"] == weapon_name][0]["family"]
    if family == weapon_name:
        return False
    return True


def scale_range(actual, actual_min, actual_max, wanted_min, wanted_max):
    """Scales a value from within a range to another range"""

    return (wanted_max - wanted_min) * (
        (actual - actual_min) / (actual_max - actual_min)
    ) + wanted_min


def compare_stats(little_list, big_list):
    """Returns if the first list is a subset of the second one."""

    return set(little_list).issubset(big_list)


def login(
    user_email: str, user_password: str, platform: str = "pc", language: str = "en"
):
    """Login function, copied from the wfm discord."""

    global jwt_token, ingame_name, headers
    headers = {
        "content-type": "application/json; utf-8",
        "accept": "application/json",
        "authorization": "jwt",
        "platform": platform,
        "language": language,
    }
    content = {"email": user_email, "password": user_password, "auth_type": "header"}
    response = requests.post(
        f"{WFM_API}/auth/signin", data=json.dumps(content), headers=headers
    )
    if response.status_code != 200:
        print("couldn't login with those credentials")
        return None
    print("logged succesfully")
    ingame_name = response.json()["payload"]["user"]["ingame_name"]
    jwt_token = response.headers["authorization"]
    headers["authorization"] = jwt_token
    headers["auth_type"] = "header"
    return [headers, ingame_name, jwt_token]


def get_current_auctions():
    """Returns the current auctions of the user."""
    if ingame_name:
        url = "profile/" + ingame_name + "/auctions"
        result = get_wfm_request(url)
        if result:
            return result["auctions"]
    return None


@sleep_and_retry
@limits(calls=3, period=1.2)
def upvote_wfm_user(user_name):
    # We'll do a positive review of the user, the URL is like this https://api.warframe.market/v1/profile/{user_name}/review
    # But we have to add the fields review_type = 1 and text = "Good seller"
    url = "profile/" + user_name + "/review"
    texts = [
        "Nice trader!",
        "Fast trader",
        "Good prices",
        "Generous trader",
        "Good trader",
        "Nice trader",
        "+1",
    ]
    data = {"review_type": 1, "text": random.choice(texts)}
    result = requests.post(WFM_API + url, data=json.dumps(data), headers=headers)
    if result.status_code == 200:
        print("upvoted " + user_name)
        return True
    return False


def wfm_string(item_name, seller_name, price, rank=None):
    """Writes a message that can be copied directly as if the user came from wfm"""
    if rank is not None:
        print(
            "/w "
            + str(seller_name)
            + " hi! i want to buy: "
            + item_name.title().replace("_", " ")
            + " (rank "
            + str(rank)
            + ") for "
            + str(price)
            + " platinum. (warframe.market)\n"
        )
    else:
        print(
            "/w "
            + str(seller_name)
            + " hi! i want to buy: "
            + item_name.title().replace("_", " ")
            + " for "
            + str(price)
            + " platinum. (warframe.market)\n"
        )


def translate_stat_rh_wfm(stat):
    return [x["wfm_name"] for x in settings.stat_list if stat in x["rh_names"]][0]


def translate_stat_wfm_rh(stat, type):
    return [x["rh_names"][type] for x in settings.stat_list if stat == x["wfm_name"]][0]


def translate_stats_wiki_wfm(stat):
    res = [stat2 for stat2 in settings.stat_list if stat2["wiki_name"] == stat]
    if len(res) != 0:
        return str(res[0]["wfm_name"])
    return str(re.sub("([a-z0-9])([A-Z])", r"\1_\2", stat).lower())

``````
------ src/weapon_updater.py ------
``````
"""File used to update the weapon list used on the rest of modules.
   Must be greatly improved in the future, by not depending on WFCD's data."""

from io import StringIO

import pandas as pd
import requests
from numpy import NaN

import src.utils as utils


def call_api(slot):
    """Return a table of weapons of a specific slot using MediaWikiAPI."""
    url = "https://warframe.fandom.com/api.php"
    question = (
        "local CSV = require('Module:Weapons/csv') print(CSV._csvGunComparisonTable('{}'))".format(
            slot
        )
        if slot != "Melee"
        else "local CSV = require('Module:Weapons/csv') print(CSV._csvMeleeComparisonTable())"
    )

    params = {
        "action": "scribunto-console",
        "format": "json",
        "title": "Module:Weapons/csv",
        "content": "",
        "question": question,
        "clear": 1,
    }

    response = requests.get(url, params=params).json()["print"]
    response = (
        response.replace("/\\n/gm", "\n")
        .replace("/\\t/gm", "\t")
        .replace('/\\"/gm', '"')
        .split("calculating FireRate from Burst stats for Gorgon Wraith")[-1]
        .split("\n", 1)[1]
        # .split("Name,")[1]
        # .split("+1\n", 1)[1]
    )

    return response


def correct_kitguns(weapons):
    """Corrects the kitgun stats."""
    with open("kitguns.csv", encoding="utf-8") as file:
        exceptions = pd.read_csv(file)
        for name, type in zip(exceptions["name"], exceptions["slot"]):
            for weapon in weapons["name"]:
                if name.lower() in weapon.lower() and type.lower() in weapon.lower():
                    for column in exceptions.columns.tolist():
                        if column not in ["name", "slot", "Unnamed: 0"]:
                            weapons.loc[
                                weapons["name"] == weapon, column
                            ] = exceptions.loc[
                                exceptions["name"] == name, column
                            ].values[
                                0
                            ]
                    break
        for name, type in zip(exceptions["name"], exceptions["slot"]):
            for weapon in weapons["name"]:
                if name.lower() in weapon.lower() and type.lower() in weapon.lower():
                    weapons.loc[weapons["name"] == weapon, "name"] = name.title()
    file.close()
    return weapons


def update_weapons():
    """Updates the weapons.json file."""
    slots = [
        "Primary",
        "Secondary",
        "Melee",
        "Robotic",
        "Arch-Gun",
        "Arch-Gun (Atmosphere)",
        "Amp",
    ]
    print("Updating weapon database.")
    weapons = pd.concat(
        [pd.read_csv(StringIO(call_api(slot))) for slot in slots]
    ).reset_index(drop=True)
    weapons = weapons.loc[weapons.groupby("Name")["TotalDamage"].idxmax()]
    weapons["TotalDamage"] = weapons["TotalDamage"] + 0.1
    slots.insert(1, "Shotgun")
    alternatives = slots[5:]
    slots = slots[:5]
    column_list = [utils.translate_stats_wiki_wfm(x) for x in weapons.columns.tolist()]
    weapons.rename(
        columns=dict(zip(weapons.columns.tolist(), column_list)), inplace=True
    )

    # remove weapons with no disposition
    weapons = weapons[weapons["disposition"] != NaN]
    weapons = correct_kitguns(weapons)
    weapons["weapon_type"] = weapons.apply(
        lambda x: 1
        if (x["class"] == "Shotgun" and x["slot"] == "Primary")
        else (
            slots.index(x["slot"])
            if x["slot"] in slots
            else (5 if x["slot"] in alternatives else (3 if x["class"] != 4 else 4))
        ),
        axis=1,
    )

    weapons = weapons.loc[:, ~weapons.columns.duplicated(keep="last")]
    weapons.to_json("weapons.json", orient="records")
    print("Weapon database updated.")

``````
------ deal_finder.py ------
``````
import src.user_commands as user_commands

user_commands.choose_category()