ocrlatex / app.py
seawolf2357's picture
Update app.py
75e6b3e verified
raw
history blame
2.05 kB
import gradio as gr
import requests
import json
import base64
from PIL import Image
import io
import os
app_id = os.getenv("app_id")
app_key = os.getenv("app_key")
app_url = os.getenv("app_url")
# Mathpix์— ์ด๋ฏธ์ง€ ํŒŒ์ผ์„ ๋ณด๋‚ด์–ด ์—ฌ๋Ÿฌ ํฌ๋งท์˜ LaTeX ๋ฌธ์ž์—ด์„ ์ถ”์ถœํ•˜๋Š” ํ•จ์ˆ˜
def get_latex_from_image_all_formats(image):
# PIL ์ด๋ฏธ์ง€๋ฅผ ๋ฐ”์ดํŠธ๋กœ ๋ณ€ํ™˜
buffered = io.BytesIO()
image.save(buffered, format="JPEG")
image_base64 = base64.b64encode(buffered.getvalue()).decode('utf-8')
# Mathpix API ์š”์ฒญ ํ—ค๋”
headers = {
"app_id": app_id,
"app_key": app_key,
"Content-Type": "application/json"
}
# Mathpix API ์š”์ฒญ ๋ฐ”๋””
data = {
"src": f"data:image/jpeg;base64,{image_base64}",
"formats": "text"
}
# Mathpix API ์š”์ฒญ ๋ณด๋‚ด๊ธฐ
response = requests.post(app_url, headers=headers, json=data)
response.raise_for_status() # ์š”์ฒญ ์‹คํŒจ ์‹œ ์˜ˆ์™ธ ๋ฐœ์ƒ
# ์‘๋‹ต์—์„œ ๊ฐ ํฌ๋งท์˜ LaTeX ์ถ”์ถœ
result = response.json()
formats_results = {f: result.get(f, f"{f} ์ถ”์ถœ ์‹คํŒจ") for f in data["formats"]}
return formats_results
def build_gradio_app():
with gr.Blocks() as demo:
with gr.Row():
image_input = gr.Image(type="pil", label="์ด๋ฏธ์ง€ ์—…๋กœ๋“œ")
submit_button = gr.Button("๋ณ€ํ™˜ํ•˜๊ธฐ")
outputs = [gr.Textbox(label=f"{f} ๊ฒฐ๊ณผ") for f in "text"]
latex_iframe = gr.HTML(value='<iframe src="https://www.mathjax.org/#demo" style="width: 100%; height: 700px; border: 2px solid #007bff; border-radius: 8px;"></iframe>', elem_id="latex_iframe")
def process_and_output(image):
latex_result = get_latex_from_image_all_formats(image) # ๋ณ€์ˆ˜๋ช… ์ˆ˜์ •
return [latex_result.get(f) for f in "text"] # ์ˆ˜์ •๋œ ๋ถ€๋ถ„
submit_button.click(fn=process_and_output, inputs=image_input, outputs=outputs)
return demo
if __name__ == "__main__":
app = build_gradio_app()
app.launch()