From bba099209472f056d2c59b9388fd080e773b7c00 Mon Sep 17 00:00:00 2001 From: Heet Patel Date: Sun, 31 Dec 2023 13:36:35 +0000 Subject: [PATCH] Refactor code and fix formatting issues --- API/main.py | 36 ++++++++------- FormulaForge/Extensions/latex.py | 51 ++++++++++----------- FormulaForge/Extensions/unit_convert.py | 59 ++++++++++++++++++++----- FormulaForge/Models/url.py | 2 +- FormulaForge/bot.py | 4 +- FormulaForge/utils/convert_energy.py | 16 +++---- FormulaForge/utils/convert_length.py | 10 ++--- FormulaForge/utils/convert_mass.py | 8 ++-- FormulaForge/utils/convert_speed.py | 10 ++--- FormulaForge/utils/convert_temp.py | 18 ++++---- 10 files changed, 128 insertions(+), 86 deletions(-) diff --git a/API/main.py b/API/main.py index f017f7d..7a53e25 100644 --- a/API/main.py +++ b/API/main.py @@ -1,31 +1,37 @@ -from fastapi import FastAPI -import matplotlib.pyplot as plt -import matplotlib -import io import base64 +import io + +import matplotlib +import matplotlib.pyplot as plt +from fastapi import FastAPI matplotlib.rcParams["mathtext.fontset"] = "cm" app = FastAPI() + @app.get("/") async def root(): return {"message": "Hello World"} + @app.get("/latex_formula/{formula}") -async def generate_latex_formula(formula: str, transparent: bool = False, rect_or_square: str = "square", background_color: str = "gray", text_color: str = "white", font_size: int = 16): +async def generate_latex_formula( + formula: str, + transparent: bool = False, + rect_or_square: str = "square", + background_color: str = "gray", + text_color: str = "white", + font_size: int = 16, +): if rect_or_square.lower() == "rectangle": - fig = plt.figure( - dpi=300, - facecolor=background_color, - figsize=(4, 1) - ) + fig = plt.figure(dpi=300, facecolor=background_color, figsize=(4, 1)) else: fig = plt.figure( dpi=300, facecolor=background_color, ) - + multiline_formula = r"""{}""".format(formula) fig.text( x=0.5, @@ -36,11 +42,11 @@ async def generate_latex_formula(formula: str, transparent: bool = False, rect_o verticalalignment="center", color=text_color, ) - + image_bytes = io.BytesIO() plt.savefig(image_bytes, format="png", transparent=transparent) plt.close() - + image_bytes64 = base64.b64encode(image_bytes.getvalue()).decode("utf-8") - - return {'image': image_bytes64, 'formula': formula} \ No newline at end of file + + return {"image": image_bytes64, "formula": formula} diff --git a/FormulaForge/Extensions/latex.py b/FormulaForge/Extensions/latex.py index e2368af..401c97a 100644 --- a/FormulaForge/Extensions/latex.py +++ b/FormulaForge/Extensions/latex.py @@ -5,15 +5,16 @@ from FormulaForge.bot import MyModal from FormulaForge.bot import modal_client -from FormulaForge.Models.url import (URLBuilder, - convert_new_line_to_url_encoding) - +from FormulaForge.Models.url import URLBuilder, convert_new_line_to_url_encoding latex_images = arc.RESTPlugin("latex_images") + @latex_images.include -@arc.slash_command(name="latex_to_image", description="Convert LaTeX (Math Mode) to an image.") +@arc.slash_command( + name="latex_to_image", description="Convert LaTeX (Math Mode) to an image." +) async def latex_to_image( ctx: arc.RESTContext, is_transparent: arc.Option[ @@ -52,17 +53,18 @@ async def latex_to_image( arc.IntParams( name="fontsize", description="The fontsize of the formula image. Defaults to 16px", - choices={"8px": 8, - "12px": 12, - "16px": 16, - "20px": 20, - "24px": 24, - "28px": 28, - "32px": 32,}, + choices={ + "8px": 8, + "12px": 12, + "16px": 16, + "20px": 20, + "24px": 24, + "28px": 28, + "32px": 32, + }, ), ] = 16, ) -> None: - if is_transparent: is_transparent = True else: @@ -71,20 +73,19 @@ async def latex_to_image( bg_color = bg_color text_color = text_color font_size = fontsize - - + modal = MyModal(title="FormulaForge") builder = modal.build_response(modal_client) await ctx.respond_with_builder(builder) modal_client.start_modal(modal) - + await modal.wait() - + if modal.last_context is None: return - - formula = convert_new_line_to_url_encoding(modal.formula.value) # type: ignore - + + formula = convert_new_line_to_url_encoding(modal.formula.value) # type: ignore + paramless_url = URLBuilder(f"http://0.0.0.0:80/latex_formula/{formula}") final_url = paramless_url( transparent=is_transparent, @@ -93,13 +94,13 @@ async def latex_to_image( text_color=text_color, font_size=font_size, ) - + async with aiohttp.ClientSession() as session: - async with session.get(url=final_url) as resp: - response = await resp.json() - + async with session.get(url=final_url) as resp: + response = await resp.json() + image_bytes = base64.b64decode(response["image"]) - + await modal.last_context.edit_response(content=None, attachment=image_bytes) @@ -110,4 +111,4 @@ def load(client: arc.RESTClient) -> None: @arc.unloader def unload(client: arc.RESTClient) -> None: - client.remove_plugin(latex_images) \ No newline at end of file + client.remove_plugin(latex_images) diff --git a/FormulaForge/Extensions/unit_convert.py b/FormulaForge/Extensions/unit_convert.py index 42d1efa..2ab63fe 100644 --- a/FormulaForge/Extensions/unit_convert.py +++ b/FormulaForge/Extensions/unit_convert.py @@ -8,10 +8,12 @@ from FormulaForge.utils.convert_temp import convert_temperature - unit_converter = arc.RESTPlugin("unit_converter") -unit_convert_group = unit_converter.include_slash_group("unit_convert", "Unit Converter Commands. (Temperature, Speed, Mass, Energy, Length)") +unit_convert_group = unit_converter.include_slash_group( + "unit_convert", + "Unit Converter Commands. (Temperature, Speed, Mass, Energy, Length)", +) dict_of_unit_symbols = { "Celsius": "°C", @@ -37,6 +39,7 @@ "Nautical Miles": "nmi", } + def get_unit_symbol(unit: str) -> str: return dict_of_unit_symbols[unit] @@ -78,8 +81,15 @@ async def temperature( ), ], ) -> None: - await ctx.respond(embed=embed_builder(temperature, from_unit, to_unit, convert_temperature(temperature, from_unit, to_unit))) - + await ctx.respond( + embed=embed_builder( + temperature, + from_unit, + to_unit, + convert_temperature(temperature, from_unit, to_unit), + ) + ) + @unit_convert_group.include @arc.slash_subcommand(name="speed", description="Convert speed.") @@ -97,7 +107,12 @@ async def speed( arc.StrParams( name="from_unit", description="The unit to convert from.", - choices=["Meters Per Second", "Kilometers Per Hour", "Miles Per Hour", "Knots"], + choices=[ + "Meters Per Second", + "Kilometers Per Hour", + "Miles Per Hour", + "Knots", + ], ), ], to_unit: arc.Option[ @@ -105,11 +120,20 @@ async def speed( arc.StrParams( name="to_unit", description="The unit to convert to.", - choices=["Meters Per Second", "Kilometers Per Hour", "Miles Per Hour", "Knots"], + choices=[ + "Meters Per Second", + "Kilometers Per Hour", + "Miles Per Hour", + "Knots", + ], ), ], ) -> None: - await ctx.respond(embed=embed_builder(speed, from_unit, to_unit, convert_speed(speed, from_unit, to_unit))) + await ctx.respond( + embed=embed_builder( + speed, from_unit, to_unit, convert_speed(speed, from_unit, to_unit) + ) + ) @unit_convert_group.include @@ -140,7 +164,11 @@ async def mass( ), ], ) -> None: - await ctx.respond(embed=embed_builder(mass, from_unit, to_unit, convert_mass(mass, from_unit, to_unit))) + await ctx.respond( + embed=embed_builder( + mass, from_unit, to_unit, convert_mass(mass, from_unit, to_unit) + ) + ) @unit_convert_group.include @@ -171,7 +199,11 @@ async def energy( ), ], ) -> None: - await ctx.respond(embed=embed_builder(energy, from_unit, to_unit, convert_energy(energy, from_unit, to_unit))) + await ctx.respond( + embed=embed_builder( + energy, from_unit, to_unit, convert_energy(energy, from_unit, to_unit) + ) + ) @unit_convert_group.include @@ -202,13 +234,18 @@ async def length( ), ], ) -> None: - await ctx.respond(embed=embed_builder(length, from_unit, to_unit, convert_length(length, from_unit, to_unit))) + await ctx.respond( + embed=embed_builder( + length, from_unit, to_unit, convert_length(length, from_unit, to_unit) + ) + ) @arc.loader def load(client: arc.RESTClient) -> None: client.add_plugin(unit_converter) + @arc.unloader def unload(client: arc.RESTClient) -> None: - client.remove_plugin(unit_converter) \ No newline at end of file + client.remove_plugin(unit_converter) diff --git a/FormulaForge/Models/url.py b/FormulaForge/Models/url.py index fdef2b1..6a92603 100644 --- a/FormulaForge/Models/url.py +++ b/FormulaForge/Models/url.py @@ -20,4 +20,4 @@ def __call__(self, *args, **kwargs) -> str: def convert_new_line_to_url_encoding(formula_without_newline_encoding: str) -> str: """Converts \n to %0A""" - return formula_without_newline_encoding.replace("\n", "%0A") \ No newline at end of file + return formula_without_newline_encoding.replace("\n", "%0A") diff --git a/FormulaForge/bot.py b/FormulaForge/bot.py index 24533c3..ea0629f 100644 --- a/FormulaForge/bot.py +++ b/FormulaForge/bot.py @@ -6,19 +6,17 @@ class MyModal(miru.Modal[miru.REST]): - formula = miru.TextInput[miru.REST]( label="Formula", placeholder="Remember to add $ in Math Mode https://www1.cmc.edu/pages/faculty/aaksoy/latex/latexthree.html", required=True, style=hikari.TextInputStyle.PARAGRAPH, ) - + async def callback(self, context: miru.ModalContext[miru.REST]) -> None: await context.respond("Processing...") - TOKEN = os.environ["TOKEN"] bot = hikari.RESTBot(token=TOKEN, logs="DEBUG") diff --git a/FormulaForge/utils/convert_energy.py b/FormulaForge/utils/convert_energy.py index 40e0c03..5bf8cb9 100644 --- a/FormulaForge/utils/convert_energy.py +++ b/FormulaForge/utils/convert_energy.py @@ -5,7 +5,7 @@ def convert_energy( ) -> float: """ Converts energy from one unit to another. (Joules, Calories, Foot-Pound, Electronvolts) - + Parameters ---------- energy : float @@ -14,20 +14,20 @@ def convert_energy( The unit to convert from. to_unit : str The unit to convert to. - + Returns ------- float The converted energy. """ - + if from_unit == "Joules": if to_unit == "Calories": converted_energy = energy * 0.239006 elif to_unit == "Foot-Pound": converted_energy = energy * 0.737562 elif to_unit == "Electronvolts": - converted_energy = energy * 6.2415e+18 + converted_energy = energy * 6.2415e18 else: converted_energy = energy elif from_unit == "Calories": @@ -36,7 +36,7 @@ def convert_energy( elif to_unit == "Foot-Pound": converted_energy = energy * 3.08596 elif to_unit == "Electronvolts": - converted_energy = energy * 2.6132e+19 + converted_energy = energy * 2.6132e19 else: converted_energy = energy elif from_unit == "Foot-Pound": @@ -45,7 +45,7 @@ def convert_energy( elif to_unit == "Calories": converted_energy = energy * 0.324048 elif to_unit == "Electronvolts": - converted_energy = energy * 8.462e+18 + converted_energy = energy * 8.462e18 else: converted_energy = energy else: @@ -57,5 +57,5 @@ def convert_energy( converted_energy = energy * 1.1817e-19 else: converted_energy = energy - - return converted_energy \ No newline at end of file + + return converted_energy diff --git a/FormulaForge/utils/convert_length.py b/FormulaForge/utils/convert_length.py index 3179724..ac65281 100644 --- a/FormulaForge/utils/convert_length.py +++ b/FormulaForge/utils/convert_length.py @@ -5,7 +5,7 @@ def convert_length( ) -> float: """ Converts length from one unit to another. (Meters, Yards, Feet, Miles, Inches, Nautical Miles) - + Parameters ---------- length : float @@ -14,13 +14,13 @@ def convert_length( The unit to convert from. to_unit : str The unit to convert to. - + Returns ------- float The converted length. """ - + if from_unit == "Meters": if to_unit == "Yards": converted_length = length * 1.09361 @@ -99,5 +99,5 @@ def convert_length( converted_length = length * 72913.4 else: converted_length = length - - return converted_length \ No newline at end of file + + return converted_length diff --git a/FormulaForge/utils/convert_mass.py b/FormulaForge/utils/convert_mass.py index 23ae177..d2f529d 100644 --- a/FormulaForge/utils/convert_mass.py +++ b/FormulaForge/utils/convert_mass.py @@ -5,7 +5,7 @@ def convert_mass( ) -> float: """ Converts mass from one unit to another. (Kilograms, Grams, Pounds, Ounces) - + Parameters ---------- mass : float @@ -14,13 +14,13 @@ def convert_mass( The unit to convert from. to_unit : str The unit to convert to. - + Returns ------- float The converted mass. """ - + if from_unit == "Kilograms": if to_unit == "Grams": converted_mass = mass * 1000 @@ -57,5 +57,5 @@ def convert_mass( converted_mass = mass / 16 else: converted_mass = mass - + return converted_mass diff --git a/FormulaForge/utils/convert_speed.py b/FormulaForge/utils/convert_speed.py index 53e84f9..59b81ca 100644 --- a/FormulaForge/utils/convert_speed.py +++ b/FormulaForge/utils/convert_speed.py @@ -5,7 +5,7 @@ def convert_speed( ) -> float: """ Converts speed from one unit to another. (Kilometers per hour, Miles per hour, Meters per second, Knots) - + Parameters ---------- speed : float @@ -14,13 +14,13 @@ def convert_speed( The unit to convert from. to_unit : str The unit to convert to. - + Returns ------- float The converted speed. """ - + if from_unit == "Kilometers per hour": if to_unit == "Miles per hour": converted_speed = speed * 0.621371 @@ -57,5 +57,5 @@ def convert_speed( converted_speed = speed * 0.514444 else: converted_speed = speed - - return converted_speed \ No newline at end of file + + return converted_speed diff --git a/FormulaForge/utils/convert_temp.py b/FormulaForge/utils/convert_temp.py index f3e5c75..c6faaaf 100644 --- a/FormulaForge/utils/convert_temp.py +++ b/FormulaForge/utils/convert_temp.py @@ -5,7 +5,7 @@ def convert_temperature( ) -> float: """ Converts temperature from one unit to another. (Celsius, Fahrenheit, Kelvin) - + Parameters ---------- temperature : float @@ -14,33 +14,33 @@ def convert_temperature( The unit to convert from. to_unit : str The unit to convert to. - + Returns ------- float The converted temperature. """ - + if from_unit == "Celsius": if to_unit == "Fahrenheit": - converted_temperature = (temperature * 9/5) + 32 + converted_temperature = (temperature * 9 / 5) + 32 elif to_unit == "Kelvin": converted_temperature = temperature + 273.15 else: converted_temperature = temperature elif from_unit == "Fahrenheit": if to_unit == "Celsius": - converted_temperature = (temperature - 32) * 5/9 + converted_temperature = (temperature - 32) * 5 / 9 elif to_unit == "Kelvin": - converted_temperature = (temperature - 32) * 5/9 + 273.15 + converted_temperature = (temperature - 32) * 5 / 9 + 273.15 else: converted_temperature = temperature else: if to_unit == "Celsius": converted_temperature = temperature - 273.15 elif to_unit == "Fahrenheit": - converted_temperature = (temperature - 273.15) * 9/5 + 32 + converted_temperature = (temperature - 273.15) * 9 / 5 + 32 else: converted_temperature = temperature - - return converted_temperature \ No newline at end of file + + return converted_temperature