Drbrain0620's picture
Rename main.py to app.py
d99b2d8 verified
import docx
from docx.shared import Pt
import gradio as gr
# Helper to format circled numbers 1-20
CIRCLED = {
i: chr(9311 + i) for i in range(1, 21)
}
def load_pi(path="pi.txt"):
with open(path, "r", encoding="utf-8") as f:
return f.read().strip()
def make_doc(start_seg, end_seg, pi_path="pi.txt"):
# Segments start from 1
pi = load_pi(pi_path)
doc = docx.Document()
style = doc.styles["Normal"]
font = style.font #type: ignore
font.name = "Malgun Gothic"
font.size = Pt(10)
# Calculate the starting offset for the first line
first_offset = (start_seg // 10) * 10
last_offset = ((end_seg - 1) // 10) * 10 # adjust to prevent extra line
for offset in range(first_offset, last_offset + 1, 10):
line_segments = []
line_start = max(offset + 1, start_seg)
line_end = min(offset + 10, end_seg)
for s in range(line_start, line_end + 1):
idx = (s - 1) * 4
if idx + 4 > len(pi):
break
seg = pi[idx:idx+4]
n = s - offset # position in line
circ = CIRCLED.get(n, str(n))
line_segments.append(f"{seg}{circ}")
if line_segments:
p = doc.add_paragraph()
run = p.add_run(str(offset))
run.bold = True
p.add_run(" | " + " ".join(line_segments))
out_name = "pi_segments.docx"
doc.save(out_name)
return out_name
with gr.Blocks() as demo:
gr.Markdown("## π Segment DOCX Generator")
gr.Markdown("This web app generates a DOCX file showing π digits divided into 4-digit segments.\n\n"
"Segments are numbered starting from 1. Each line contains up to 10 segments, and the line starts with the offset (multiple of 10) in bold.\n\n"
"The circled number after each segment indicates its position within the line. You can use them as a checkbox after you memorized it.")
start_in = gr.Number(label="Start Segment (min 1)", value=1)
end_in = gr.Number(label="End Segment (max 250000)", value=100)
out = gr.File(label="Generated DOCX")
def run_app(a, b):
pi_file_path = "pi.txt"
if b > 250000:
raise gr.Error("End segment cannot exceed 250,000.")
return make_doc(int(a), int(b), pi_file_path)
btn = gr.Button("Generate")
btn.click(run_app, [start_in, end_in], out)
if __name__ == "__main__":
demo.launch()