Spaces:
Sleeping
Sleeping
#!/usr/bin/env python | |
""" | |
nexa-prompts β Gradio Space to craft JSON instruction / template bundles | |
for scientificβML prompt engineering. | |
Author: Allan (Nexa Ecosystem) β Apacheβ2.0 | |
""" | |
import json, re, tempfile, gradio as gr | |
# βββββββββββββββββββββββββ helper functions ββββββββββββββββββββββββββ | |
def clean_author_block(tex: str) -> str: | |
"""Remove any \author{ β¦ } block (including embedded newlines).""" | |
return re.sub(r"\\author\{.*?\}", "", tex, flags=re.DOTALL) | |
def swap_topic(text: str, old: str, new: str) -> str: | |
pat = re.compile(re.escape(old), flags=re.IGNORECASE) | |
return pat.sub(new, text) | |
def build_json(system_instr: str, | |
user_template: str, | |
topic_swap: str, | |
strip_author: bool) -> str: | |
if strip_author: | |
user_template = clean_author_block(user_template) | |
if topic_swap.strip(): | |
user_template = swap_topic(user_template, "black holes", topic_swap) | |
system_instr = swap_topic(system_instr, "black holes", topic_swap) | |
payload = [ | |
{"role": "system", "content": system_instr.strip()}, | |
{"role": "user", "content": user_template.strip()} | |
] | |
return json.dumps(payload, indent=2) | |
def to_tmp_file(text: str) -> str: | |
"""Persist text to a temp .json file so Gradio can serve it.""" | |
f = tempfile.NamedTemporaryFile(delete=False, suffix=".json", mode="w") | |
f.write(text); f.close() | |
return f.name | |
# ββββββββββββββββββββββββββ Gradio UI ββββββββββββββββββββββββββββββββ | |
with gr.Blocks(title="Nexaβ―Prompts") as demo: | |
gr.Markdown( | |
""" | |
# Nexaβ―Prompts | |
Quickly build **roleβbased JSON conversations** for SciML agents. | |
1. Edit the **System** and **User** boxes | |
2. (Optional) swap topic or strip the `\\author{}` block | |
3. Click **Generate** β copy or download your JSON | |
""" | |
) | |
with gr.Row(): | |
sys_box = gr.Textbox(lines=10, label="System Instruction") | |
usr_box = gr.Textbox(lines=20, label="User Template (LaTeX, etc.)") | |
with gr.Row(): | |
topic_box = gr.Textbox(label="Swap topic (optional)", placeholder="e.g. quantum computing") | |
strip_chk = gr.Checkbox(label="Strip \\author{...} block", value=True) | |
gen_btn = gr.Button("Generate JSON") | |
json_box = gr.Textbox(lines=20, label="Generated JSON", interactive=False) | |
dl_btn = gr.DownloadButton(label="β¬οΈΒ Download .json") | |
def run(system_instr, user_template, topic_swap, strip_author): | |
js = build_json(system_instr, user_template, topic_swap, strip_author) | |
path = to_tmp_file(js) | |
return js, path | |
gen_btn.click( | |
run, | |
inputs=[sys_box, usr_box, topic_box, strip_chk], | |
outputs=[json_box, dl_btn], | |
) | |
if __name__ == "__main__": | |
demo.launch() | |