Skip to content

Commit

Permalink
Refactor code and fix formatting issues
Browse files Browse the repository at this point in the history
  • Loading branch information
patelheet30 committed Dec 31, 2023
1 parent ad3ff41 commit bba0992
Show file tree
Hide file tree
Showing 10 changed files with 128 additions and 86 deletions.
36 changes: 21 additions & 15 deletions API/main.py
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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}

return {"image": image_bytes64, "formula": formula}
51 changes: 26 additions & 25 deletions FormulaForge/Extensions/latex.py
Original file line number Diff line number Diff line change
Expand Up @@ -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[
Expand Down Expand Up @@ -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:
Expand All @@ -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,
Expand All @@ -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)


Expand All @@ -110,4 +111,4 @@ def load(client: arc.RESTClient) -> None:

@arc.unloader
def unload(client: arc.RESTClient) -> None:
client.remove_plugin(latex_images)
client.remove_plugin(latex_images)
59 changes: 48 additions & 11 deletions FormulaForge/Extensions/unit_convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -37,6 +39,7 @@
"Nautical Miles": "nmi",
}


def get_unit_symbol(unit: str) -> str:
return dict_of_unit_symbols[unit]

Expand Down Expand Up @@ -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.")
Expand All @@ -97,19 +107,33 @@ 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[
str,
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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
client.remove_plugin(unit_converter)
2 changes: 1 addition & 1 deletion FormulaForge/Models/url.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
return formula_without_newline_encoding.replace("\n", "%0A")
4 changes: 1 addition & 3 deletions FormulaForge/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
16 changes: 8 additions & 8 deletions FormulaForge/utils/convert_energy.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ def convert_energy(
) -> float:
"""
Converts energy from one unit to another. (Joules, Calories, Foot-Pound, Electronvolts)
Parameters
----------
energy : float
Expand All @@ -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":
Expand All @@ -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":
Expand All @@ -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:
Expand All @@ -57,5 +57,5 @@ def convert_energy(
converted_energy = energy * 1.1817e-19
else:
converted_energy = energy
return converted_energy

return converted_energy
Loading

0 comments on commit bba0992

Please sign in to comment.