Download app.py from asror-z/humanizer: direct link, hf CLI and curl.
- Browser
- Download file 13.5 kB
-
https://huggingface.co/spaces/asror-z/humanizer/resolve/main/app.py
- Command line
-
hf download hf://spaces/asror-z/humanizer/app.py
-
curl -L -o app.py https://huggingface.co/spaces/asror-z/humanizer/resolve/main/app.py
13.5 kB
| import hashlib | |
| import json | |
| import threading | |
| import gradio as gr | |
| import spaces | |
| import torch | |
| from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer | |
| MODEL_ID = "jialinyyzz/humanizer" | |
| # Exact prompt format required by humanizer | |
| FMT_INSTR = ( | |
| "Rewrite the text below so it reads like a person wrote it, not a language model.\n\n" | |
| "Reorganize it as you see fit. Vary sentence length on purpose. Cut hedging,\n" | |
| "throat-clearing, and any sentence that only announces what comes next.\n" | |
| "Prefer the concrete word over the abstract one. It is fine to sound uneven.\n\n" | |
| "Every fact, number, unit, date, name and quotation must survive unchanged." | |
| ) | |
| FMT_SEP = "\n\n### Rewritten:\n\n" | |
| def build_prompt(draft: str) -> str: | |
| return FMT_INSTR + "\n\n" + draft.strip() + FMT_SEP | |
| # Assert prompt fingerprint (matches release repo AGENTS.md requirement) | |
| _fp = hashlib.sha256(build_prompt("X").encode("utf-8")).hexdigest()[:16] | |
| assert _fp == "cc51d66b4c593fbe", f"Prompt fingerprint mismatch: {_fp}" | |
| # Load tokenizer and model eagerly to cuda at module scope (ZeroGPU best practice) | |
| tokenizer = AutoTokenizer.from_pretrained(MODEL_ID) | |
| model = AutoModelForCausalLM.from_pretrained(MODEL_ID, dtype=torch.bfloat16) | |
| model.to("cuda").eval() | |
| EOS = tokenizer.eos_token_id | |
| def get_slot_duration(draft: str, temperature: float = 1.0, top_p: float = 0.95) -> int: | |
| """Dynamically size the ZeroGPU slot to minimize visitor quota consumption.""" | |
| if not draft: | |
| return 20 | |
| # Sized for optimal queue priority and tight quota: between 20 and 60 seconds | |
| return min(60, max(20, round(len(draft) / 30) + 15)) | |
| def rewrite_stream( | |
| draft: str, | |
| temperature: float = 1.0, | |
| top_p: float = 0.95, | |
| ): | |
| """Rewrite AI-written drafts into natural human prose while preserving factual integrity. | |
| Args: | |
| draft: Input text (English or Chinese). | |
| temperature: Sampling temperature (default 1.0). | |
| top_p: Nucleus sampling probability (default 0.95). | |
| """ | |
| draft = (draft or "").strip() | |
| if not draft: | |
| yield "Please enter an AI draft to humanize." | |
| return | |
| prompt = build_prompt(draft) | |
| enc = tokenizer(prompt, return_tensors="pt").to(model.device) | |
| # Estimate draft length and set budget | |
| draft_tokens = len(tokenizer(draft)["input_ids"]) | |
| max_new_tokens = max(256, min(2048, round(2.5 * draft_tokens))) | |
| streamer = TextIteratorStreamer( | |
| tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=60 | |
| ) | |
| generation_kwargs = dict( | |
| **enc, | |
| streamer=streamer, | |
| max_new_tokens=max_new_tokens, | |
| do_sample=True, | |
| temperature=float(temperature), | |
| top_p=float(top_p), | |
| top_k=0, # top_k must be 0 (off) per official eval settings | |
| repetition_penalty=1.0, | |
| pad_token_id=tokenizer.pad_token_id, | |
| eos_token_id=EOS, | |
| ) | |
| thread = threading.Thread(target=model.generate, kwargs=generation_kwargs) | |
| thread.start() | |
| accumulated = "" | |
| for chunk in streamer: | |
| accumulated += chunk | |
| yield accumulated | |
| thread.join() | |
| def humanize( | |
| draft: str, | |
| temperature: float = 1.0, | |
| top_p: float = 0.95, | |
| ) -> str: | |
| """Rewrite an AI draft into natural human-sounding text with facts preserved. | |
| API and MCP endpoint for programmatic invocation. | |
| """ | |
| res = "" | |
| for piece in rewrite_stream(draft, temperature, top_p): | |
| res = piece | |
| return res | |
| # Sample examples from the official humanizer evaluation benchmark | |
| EXAMPLES = [ | |
| [ | |
| ( | |
| "Hi Maya,\n\n" | |
| "Thank you again for joining our software demo on January 20. I appreciated the thoughtful " | |
| "questions from you and the Northstar Operations team, especially around user permissions, " | |
| "reporting, and integration with Salesforce.\n\n" | |
| "I wanted to follow up and see whether your team needs a detailed pricing breakdown as you " | |
| "evaluate next steps. We can provide costs by license type, implementation services, training, " | |
| "and optional add-ons, along with estimates for 25, 50, or 100 users. I’d also be happy to outline " | |
| "the differences between our Professional and Enterprise plans.\n\n" | |
| "If helpful, I can send the breakdown by Friday, January 24, or schedule a brief 20-minute call " | |
| "to walk through it. Please let me know what would be most useful as you prepare for your February " | |
| "budget review.\n\n" | |
| "Best,\n" | |
| "Jordan Lee" | |
| ), | |
| 1.0, | |
| 0.95, | |
| ], | |
| [ | |
| ( | |
| "Picked up the Logitech M240 Silent ($24.99, Best Buy, checkout Sept 2) to replace an MX " | |
| "Anywhere 3 ($79.99) that's been my daily driver for two years. Three weeks in, verdict: for most " | |
| "people, save the $55.\n\n" | |
| "The M240 pairs over Bluetooth only — no Logi Bolt receiver — and connected to my M2 MacBook Air " | |
| "in about four seconds. Scroll wheel is a basic notched mechanism, not the MX's free-spin " | |
| "hyper-fast option, so flying through a 2,000-row spreadsheet takes noticeably longer. Side buttons: " | |
| "two, same as the MX, and both remap fine in Logi Options+. Sensor tops out at 4000 DPI versus 8000 on " | |
| "the MX Anywhere 3, which I never noticed on a desk but did on my lap using my knee as a mousepad.\n\n" | |
| "Where the M240 actually wins: battery. Logitech rates it at 18 months on a single AA; I'm one month " | |
| "in and the app still shows 100%." | |
| ), | |
| 1.0, | |
| 0.95, | |
| ], | |
| [ | |
| ( | |
| "The oven (or better, a toaster oven / air fryer) beats the microwave every time — microwaving " | |
| "turns crust into rubbery cardboard because it just heats the moisture trapped in the breading.\n\n" | |
| "Here's what actually works:\n\n" | |
| "1. Let the chicken come to room temp for about 20-30 minutes before reheating. Cold-to-hot straight " | |
| "from the fridge cooks unevenly and you end up overshooting the outside to get the center warm.\n\n" | |
| "2. Preheat oven to 400°F (200°C). Set a wire rack inside a sheet pan — this is the part people skip " | |
| "and it matters most. Air circulating underneath keeps the bottom from steaming and going soggy.\n\n" | |
| "3. Bake bone-in pieces 15-20 minutes, boneless/tenders 10-12 minutes, flipping once halfway through. " | |
| "Aim for an internal temp of 165°F (74°C)." | |
| ), | |
| 1.0, | |
| 0.95, | |
| ], | |
| [ | |
| ( | |
| "林晓,你好:\n\n" | |
| "近期产品部计划针对新版本迭代前的设计质量把控,成立\"产品设计评审小组\",负责对各条线的原型稿、交互流程及视觉规范进行统一评审。经和王涛总监商量,我们都觉得你在用户体验和交互细节上的把控一直很到位,特别是上个月\"订单中心\"改版时提出的几处优化建议非常关键,所以想邀请你正式加入这个小组,一起把关后续的设计输出。\n\n" | |
| "第一次会议安排在9月25日(周五)下午3点,在3楼B会议室进行,预计时长1小时。麻烦你提前看下附件中的原型稿,期待你的加入!\n\n" | |
| "Daniel" | |
| ), | |
| 1.0, | |
| 0.95, | |
| ], | |
| [ | |
| ( | |
| "从深圳回长沙定居整整一年了,今天翻账本算了一笔账,跟大家聊聊长沙的真实物价。\n\n" | |
| "先说住的。2023年9月,我们在梅溪湖附近租了个两室一厅,月租2300,同样的钱在深圳宝安只能租个单间。今年3月咬牙买了套二手房,单价1万2,比深圳便宜了整整六倍。\n\n" | |
| "吃的方面真的幸福感拉满。小区楼下的粉店,一碗肉丝粉8块钱,加个蛋10块,老板娘认识我以后还经常多给一勺码子。周末去四方坪夜市,两个人吃小龙虾加烧烤,150块吃到扶墙出。交通方面地铁起步价2块,一个月通勤不到150。这个账,怎么算都不亏。" | |
| ), | |
| 1.0, | |
| 0.95, | |
| ], | |
| ] | |
| custom_css = """ | |
| .container { max-width: 1100px; margin: auto; padding-top: 1.5rem; } | |
| .header-box { text-align: center; margin-bottom: 1.5rem; } | |
| .header-box h1 { font-size: 2.2rem; font-weight: 700; margin-bottom: 0.5rem; } | |
| .header-box p { font-size: 1.05rem; opacity: 0.85; max-width: 750px; margin: auto; } | |
| .badge-row { display: flex; justify-content: center; gap: 0.5rem; flex-wrap: wrap; margin-top: 0.8rem; } | |
| .badge { display: inline-block; padding: 0.25rem 0.65rem; border-radius: 9999px; font-size: 0.82rem; background: rgba(16, 185, 129, 0.15); border: 1px solid rgba(16, 185, 129, 0.3); } | |
| """ | |
| theme = gr.themes.Soft( | |
| primary_hue="emerald", | |
| neutral_hue="slate", | |
| font=[gr.themes.GoogleFont("Inter"), "sans-serif"], | |
| ) | |
| with gr.Blocks() as demo: | |
| with gr.Column(elem_classes=["container"]): | |
| gr.HTML( | |
| """ | |
| <div class="header-box"> | |
| <h1>✍️ humanizer: AI-to-Human Text Rewriter</h1> | |
| <p>Rewrites robotic AI drafts into natural human prose with authentic sentence cadence, while strictly preserving numbers, dates, units, names, and facts.</p> | |
| <div class="badge-row"> | |
| <span class="badge">Model: jialinyyzz/humanizer</span> | |
| <span class="badge">Architecture: Gemma 4 12B</span> | |
| <span class="badge">Hardware: ZeroGPU (RTX 6000 Ada/Blackwell)</span> | |
| <span class="badge">English & Chinese</span> | |
| <span class="badge">MCP Enabled</span> | |
| </div> | |
| </div> | |
| """ | |
| ) | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| draft_input = gr.Textbox( | |
| label="AI-written Draft", | |
| placeholder="Paste your AI-generated text here (work email, essay, forum post, product review, or report)...", | |
| lines=13, | |
| buttons=["copy"], | |
| ) | |
| with gr.Accordion("⚙️ Sampling Settings (Evaluated Defaults)", open=False): | |
| temp_slider = gr.Slider( | |
| minimum=0.1, | |
| maximum=1.5, | |
| value=1.0, | |
| step=0.05, | |
| label="Temperature (1.0 recommended)", | |
| info="humanizer was trained and benchmarked at temperature 1.0", | |
| ) | |
| topp_slider = gr.Slider( | |
| minimum=0.1, | |
| maximum=1.0, | |
| value=0.95, | |
| step=0.05, | |
| label="Top-P (0.95 recommended)", | |
| info="Nucleus sampling probability", | |
| ) | |
| with gr.Row(): | |
| clear_btn = gr.ClearButton([draft_input], value="Clear Draft") | |
| submit_btn = gr.Button("✨ Rewrite (Humanize)", variant="primary", scale=2) | |
| with gr.Column(scale=1): | |
| humanized_output = gr.Textbox( | |
| label="Humanized Output", | |
| placeholder="Rewritten text will stream here...", | |
| lines=16, | |
| interactive=False, | |
| buttons=["copy"], | |
| ) | |
| submit_btn.click( | |
| fn=rewrite_stream, | |
| inputs=[draft_input, temp_slider, topp_slider], | |
| outputs=[humanized_output], | |
| ) | |
| gr.Examples( | |
| examples=EXAMPLES, | |
| inputs=[draft_input, temp_slider, topp_slider], | |
| outputs=[humanized_output], | |
| fn=rewrite_stream, | |
| cache_examples=False, | |
| label="📝 Try Example AI Drafts", | |
| ) | |
| with gr.Accordion("ℹ️ Model Architecture & Usage Details", open=False): | |
| gr.Markdown( | |
| """ | |
| ### About humanizer | |
| - **Model**: [`jialinyyzz/humanizer`](https://huggingface.co/jialinyyzz/humanizer) | |
| - **Base**: Fine-tuned from Google's `gemma-4-12B`. | |
| - **Text Completion**: It is a pure text-completion model (not a chat model). Prompts are formatted with exact training separators: | |
| `INSTR + "\\n\\n" + draft.strip() + "\\n\\n### Rewritten:\\n\\n"`. | |
| - **Sampling**: Evaluated at `temperature=1.0`, `top_p=0.95`, `top_k=0`, and stop only at `<eos>`. | |
| - **Factual Integrity**: Designed specifically to avoid changing numbers, dates, formulas, or quotes. | |
| ### Programmatic API & MCP | |
| This Space exposes the `/humanize` endpoint for client SDKs and MCP agents: | |
| ```python | |
| from gradio_client import Client | |
| client = Client("asror-z/humanizer") | |
| result = client.predict( | |
| draft="Your AI draft...", | |
| temperature=1.0, | |
| top_p=0.95, | |
| api_name="/humanize" | |
| ) | |
| print(result) | |
| ``` | |
| """ | |
| ) | |
| # Expose API endpoint | |
| gr.api(humanize, api_name="humanize") | |
| if __name__ == "__main__": | |
| demo.launch(theme=theme, css=custom_css, mcp_server=True) | |