Spaces:
Sleeping
Sleeping
Download app.py from RinatMalik/JSON-Generator: direct link, hf CLI and curl.
- Browser
- Download file 18.6 kB
-
https://huggingface.co/spaces/RinatMalik/JSON-Generator/resolve/main/app.py
- Command line
-
hf download hf://spaces/RinatMalik/JSON-Generator/app.py
-
curl -L -o app.py https://huggingface.co/spaces/RinatMalik/JSON-Generator/resolve/main/app.py
18.6 kB
| """ | |
| app.py | |
| ------ | |
| Hugging Face Space: Prompt -> JSON Extractor | |
| Purpose | |
| ------- | |
| This Gradio app accepts messy natural language input and converts it into | |
| structured JSON using a strong instruction-tuned model. | |
| Key features | |
| ------------ | |
| - Clean single-file Gradio app | |
| - Extensive inline comments and documentation | |
| - Robust logging to server console only (visible in Space logs, not in UI) | |
| - Strong system prompt for reliable JSON-only extraction | |
| - Optional user-provided extraction schema / field hints | |
| - JSON validation and repair pass | |
| - Friendly error handling | |
| - Examples included | |
| Expected environment | |
| -------------------- | |
| This app is designed for Hugging Face Spaces. | |
| Recommended secrets / environment variables: | |
| - HF_TOKEN | |
| or | |
| - HUGGINGFACEHUB_API_TOKEN | |
| Recommended requirements.txt (example) | |
| -------------------------------------- | |
| gradio>=5.0.0 | |
| huggingface_hub>=0.24.0 | |
| Notes | |
| ----- | |
| - The UI shows only the extracted JSON and status information. | |
| - Internal logs are written using Python logging and are not displayed to end users. | |
| """ | |
| import os | |
| import json | |
| import time | |
| import uuid | |
| import logging | |
| from typing import Any, Dict, Optional, Tuple | |
| import gradio as gr | |
| from huggingface_hub import InferenceClient | |
| # ============================================================================= | |
| # Configuration | |
| # ============================================================================= | |
| # Strong instruct model as requested by the user. | |
| MODEL_NAME = "Qwen/Qwen2.5-72B-Instruct" | |
| # Maximum characters accepted from the user for the source text. | |
| # This helps avoid accidental overload from extremely large pastes. | |
| MAX_INPUT_CHARS = 20000 | |
| # Optional upper bound for schema / extraction guidance text. | |
| MAX_SCHEMA_CHARS = 8000 | |
| # Generation settings. | |
| TEMPERATURE = 0.1 | |
| MAX_NEW_TOKENS = 1800 | |
| # Logging configuration. | |
| # Logs go to the Space/server logs and are not shown in the Gradio interface. | |
| LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO").upper() | |
| # ============================================================================= | |
| # Logging setup | |
| # ============================================================================= | |
| logger = logging.getLogger("prompt_to_json_extractor") | |
| logger.setLevel(LOG_LEVEL) | |
| # Avoid duplicate handlers if Spaces reloads the app. | |
| if not logger.handlers: | |
| handler = logging.StreamHandler() | |
| formatter = logging.Formatter( | |
| fmt="%(asctime)s | %(levelname)s | %(name)s | %(message)s" | |
| ) | |
| handler.setFormatter(formatter) | |
| logger.addHandler(handler) | |
| logger.info("Starting Prompt -> JSON Extractor app") | |
| logger.info("Configured model: %s", MODEL_NAME) | |
| # ============================================================================= | |
| # Hugging Face client setup | |
| # ============================================================================= | |
| def get_hf_token() -> Optional[str]: | |
| """ | |
| Fetch an HF API token from common environment variable names. | |
| Returns | |
| ------- | |
| Optional[str] | |
| Token string if found, otherwise None. | |
| """ | |
| return ( | |
| os.getenv("HF_TOKEN") | |
| or os.getenv("HUGGINGFACEHUB_API_TOKEN") | |
| or os.getenv("HUGGING_FACE_HUB_TOKEN") | |
| ) | |
| HF_TOKEN = get_hf_token() | |
| # Initialize the inference client. | |
| # If no token is present, some models/endpoints may fail depending on access. | |
| client = InferenceClient(token=HF_TOKEN) | |
| if HF_TOKEN: | |
| logger.info("HF token detected") | |
| else: | |
| logger.warning( | |
| "No HF token detected. If the model requires authenticated access, calls may fail." | |
| ) | |
| # ============================================================================= | |
| # Prompt helpers | |
| # ============================================================================= | |
| def build_system_prompt() -> str: | |
| """ | |
| Build the core system prompt that instructs the model to output strict JSON. | |
| Design goals | |
| ------------ | |
| - JSON only, no markdown, no explanations | |
| - Extract as much structure as reasonably possible | |
| - Preserve uncertainty explicitly using null / arrays / notes when needed | |
| - Avoid inventing facts | |
| """ | |
| return """ | |
| You are a precise information extraction engine. | |
| Your task: | |
| Convert messy natural language into a clean, structured JSON object. | |
| Critical rules: | |
| 1. Output valid JSON only. | |
| 2. Do not wrap the JSON in markdown fences. | |
| 3. Do not include any explanation before or after the JSON. | |
| 4. Do not invent facts that are not supported by the input. | |
| 5. If something is missing or unclear, use null, an empty array, or a brief uncertainty note. | |
| 6. Preserve important details faithfully. | |
| 7. Normalize values where reasonable: | |
| - dates -> ISO-like strings if clear, otherwise keep original text | |
| - numbers -> numeric types where clear | |
| - booleans -> true/false where clearly supported | |
| 8. If the user provides a target schema, follow it closely. | |
| 9. If no schema is provided, infer a sensible schema from the content. | |
| 10. Return a single top-level JSON object, not multiple objects. | |
| Preferred behavior when no schema is given: | |
| - Create semantically meaningful keys. | |
| - Group related fields into nested objects where appropriate. | |
| - Use arrays for repeated items. | |
| - Keep the structure concise but useful. | |
| Never output anything except raw valid JSON. | |
| """.strip() | |
| def build_user_prompt(source_text: str, schema_hint: str) -> str: | |
| """ | |
| Build the user message supplied to the model. | |
| Parameters | |
| ---------- | |
| source_text : str | |
| The messy natural language input from the user. | |
| schema_hint : str | |
| Optional schema or extraction guidance. | |
| Returns | |
| ------- | |
| str | |
| User prompt content. | |
| """ | |
| if schema_hint.strip(): | |
| return f""" | |
| Extract structured JSON from the following text. | |
| Target schema / extraction guidance: | |
| {schema_hint.strip()} | |
| Source text: | |
| {source_text.strip()} | |
| """.strip() | |
| return f""" | |
| Extract structured JSON from the following text. | |
| No fixed schema was provided. | |
| Infer a sensible structure based on the content. | |
| Source text: | |
| {source_text.strip()} | |
| """.strip() | |
| def build_repair_prompt(bad_output: str) -> str: | |
| """ | |
| Build a fallback repair prompt used if the first model response is not valid JSON. | |
| Parameters | |
| ---------- | |
| bad_output : str | |
| The invalid or messy model output. | |
| Returns | |
| ------- | |
| str | |
| Repair prompt content. | |
| """ | |
| return f""" | |
| The following content is intended to be JSON but is invalid or contains extra text. | |
| Repair it into a single valid JSON object. | |
| Rules: | |
| - Output valid JSON only. | |
| - Do not include markdown fences. | |
| - Do not include explanations. | |
| - Preserve the original meaning as closely as possible. | |
| Content to repair: | |
| {bad_output} | |
| """.strip() | |
| # ============================================================================= | |
| # Utility helpers | |
| # ============================================================================= | |
| def safe_trim(text: str, max_chars: int) -> str: | |
| """ | |
| Trim text to a maximum length safely. | |
| Parameters | |
| ---------- | |
| text : str | |
| Input text. | |
| max_chars : int | |
| Maximum allowed characters. | |
| Returns | |
| ------- | |
| str | |
| Trimmed text. | |
| """ | |
| if len(text) <= max_chars: | |
| return text | |
| return text[:max_chars] | |
| def extract_text_from_response(response: Any) -> str: | |
| """ | |
| Extract text content from Hugging Face chat completion responses. | |
| Because API client response formats can vary slightly by version/model, | |
| this function tries a few common access patterns. | |
| Parameters | |
| ---------- | |
| response : Any | |
| Response returned by InferenceClient.chat_completion(...) | |
| Returns | |
| ------- | |
| str | |
| Extracted text content. | |
| Raises | |
| ------ | |
| ValueError | |
| If text content cannot be extracted. | |
| """ | |
| logger.debug("Raw response type: %s", type(response)) | |
| # Common object-style access: | |
| try: | |
| content = response.choices[0].message.content | |
| if isinstance(content, str): | |
| return content | |
| except Exception: | |
| pass | |
| # Common dict-style access: | |
| try: | |
| content = response["choices"][0]["message"]["content"] | |
| if isinstance(content, str): | |
| return content | |
| except Exception: | |
| pass | |
| # Last-resort string cast. | |
| try: | |
| as_text = str(response) | |
| if as_text: | |
| return as_text | |
| except Exception: | |
| pass | |
| raise ValueError("Could not extract text content from model response.") | |
| def parse_json_strict(text: str) -> Dict[str, Any]: | |
| """ | |
| Parse JSON strictly, expecting a top-level object. | |
| Parameters | |
| ---------- | |
| text : str | |
| Raw text expected to be JSON. | |
| Returns | |
| ------- | |
| Dict[str, Any] | |
| Parsed JSON object. | |
| Raises | |
| ------ | |
| ValueError | |
| If parsing fails or the top level is not a JSON object. | |
| """ | |
| data = json.loads(text) | |
| if not isinstance(data, dict): | |
| raise ValueError("Model returned JSON, but top level is not an object.") | |
| return data | |
| def pretty_json(data: Dict[str, Any]) -> str: | |
| """ | |
| Format a Python dictionary as pretty JSON. | |
| Parameters | |
| ---------- | |
| data : Dict[str, Any] | |
| Parsed JSON object. | |
| Returns | |
| ------- | |
| str | |
| Pretty-printed JSON string. | |
| """ | |
| return json.dumps(data, indent=2, ensure_ascii=False) | |
| # ============================================================================= | |
| # Model calling logic | |
| # ============================================================================= | |
| def call_model_for_json(source_text: str, schema_hint: str, request_id: str) -> Tuple[Dict[str, Any], str]: | |
| """ | |
| Call the model to extract JSON from source text, with a repair fallback if needed. | |
| Flow | |
| ---- | |
| 1. Send extraction request | |
| 2. Attempt strict JSON parse | |
| 3. If parsing fails, run a repair pass | |
| 4. Parse repaired output | |
| 5. Return parsed dict and a status string | |
| Parameters | |
| ---------- | |
| source_text : str | |
| User input to structure. | |
| schema_hint : str | |
| Optional extraction schema or guidance. | |
| request_id : str | |
| Unique request identifier for logging. | |
| Returns | |
| ------- | |
| Tuple[Dict[str, Any], str] | |
| Parsed JSON object and status string. | |
| Raises | |
| ------ | |
| RuntimeError | |
| If model output cannot be repaired into valid JSON. | |
| """ | |
| system_prompt = build_system_prompt() | |
| user_prompt = build_user_prompt(source_text, schema_hint) | |
| logger.info("[%s] Sending primary extraction request to model", request_id) | |
| logger.debug("[%s] Source length: %d chars", request_id, len(source_text)) | |
| logger.debug("[%s] Schema length: %d chars", request_id, len(schema_hint)) | |
| response = client.chat_completion( | |
| model=MODEL_NAME, | |
| messages=[ | |
| {"role": "system", "content": system_prompt}, | |
| {"role": "user", "content": user_prompt}, | |
| ], | |
| temperature=TEMPERATURE, | |
| max_tokens=MAX_NEW_TOKENS, | |
| ) | |
| raw_output = extract_text_from_response(response).strip() | |
| logger.info("[%s] Received primary response (%d chars)", request_id, len(raw_output)) | |
| logger.debug("[%s] Primary raw output: %s", request_id, raw_output) | |
| # First attempt: strict JSON parse. | |
| try: | |
| parsed = parse_json_strict(raw_output) | |
| logger.info("[%s] Primary response parsed successfully as JSON", request_id) | |
| return parsed, "Success" | |
| except Exception as first_error: | |
| logger.warning("[%s] Primary parse failed: %s", request_id, first_error) | |
| # Second attempt: repair invalid JSON / extra text. | |
| logger.info("[%s] Sending repair request to model", request_id) | |
| repair_response = client.chat_completion( | |
| model=MODEL_NAME, | |
| messages=[ | |
| {"role": "system", "content": build_system_prompt()}, | |
| {"role": "user", "content": build_repair_prompt(raw_output)}, | |
| ], | |
| temperature=0.0, | |
| max_tokens=MAX_NEW_TOKENS, | |
| ) | |
| repaired_output = extract_text_from_response(repair_response).strip() | |
| logger.info("[%s] Received repair response (%d chars)", request_id, len(repaired_output)) | |
| logger.debug("[%s] Repaired raw output: %s", request_id, repaired_output) | |
| try: | |
| parsed = parse_json_strict(repaired_output) | |
| logger.info("[%s] Repair response parsed successfully as JSON", request_id) | |
| return parsed, "Success (repaired invalid initial output)" | |
| except Exception as repair_error: | |
| logger.error("[%s] Repair parse failed: %s", request_id, repair_error) | |
| raise RuntimeError( | |
| "The model response could not be converted into valid JSON." | |
| ) from repair_error | |
| # ============================================================================= | |
| # Gradio-facing function | |
| # ============================================================================= | |
| def extract_json(source_text: str, schema_hint: str) -> Tuple[str, str]: | |
| """ | |
| Main Gradio callback. | |
| Parameters | |
| ---------- | |
| source_text : str | |
| Raw user text to extract from. | |
| schema_hint : str | |
| Optional schema or desired fields. | |
| Returns | |
| ------- | |
| Tuple[str, str] | |
| pretty_json_output, status_text | |
| """ | |
| request_id = str(uuid.uuid4())[:8] | |
| start_time = time.time() | |
| logger.info("[%s] New extraction request started", request_id) | |
| try: | |
| source_text = (source_text or "").strip() | |
| schema_hint = (schema_hint or "").strip() | |
| # Basic validation. | |
| if not source_text: | |
| logger.warning("[%s] Empty source text submitted", request_id) | |
| return "", "Please provide some source text." | |
| if len(source_text) > MAX_INPUT_CHARS: | |
| logger.warning( | |
| "[%s] Source text exceeded limit (%d > %d), trimming", | |
| request_id, | |
| len(source_text), | |
| MAX_INPUT_CHARS, | |
| ) | |
| source_text = safe_trim(source_text, MAX_INPUT_CHARS) | |
| if len(schema_hint) > MAX_SCHEMA_CHARS: | |
| logger.warning( | |
| "[%s] Schema hint exceeded limit (%d > %d), trimming", | |
| request_id, | |
| len(schema_hint), | |
| MAX_SCHEMA_CHARS, | |
| ) | |
| schema_hint = safe_trim(schema_hint, MAX_SCHEMA_CHARS) | |
| # Run extraction. | |
| parsed, status = call_model_for_json( | |
| source_text=source_text, | |
| schema_hint=schema_hint, | |
| request_id=request_id, | |
| ) | |
| # Pretty-print for UI output. | |
| output_json = pretty_json(parsed) | |
| elapsed = time.time() - start_time | |
| logger.info("[%s] Request completed successfully in %.2fs", request_id, elapsed) | |
| return output_json, f"{status} | Request ID: {request_id} | Time: {elapsed:.2f}s" | |
| except Exception as e: | |
| elapsed = time.time() - start_time | |
| logger.exception("[%s] Request failed after %.2fs", request_id, elapsed) | |
| return "", f"Error: {str(e)} | Request ID: {request_id}" | |
| # ============================================================================= | |
| # Example content | |
| # ============================================================================= | |
| EXAMPLES = [ | |
| [ | |
| """John from Acme called me yesterday around 4pm. He wants 12 blue widgets and maybe 3 red ones if stock is available. Deliver to 18 High Street, Manchester, M1 2AB by next Friday. Budget around £450. His email is john@acme.com and phone is 07123 456789.""", | |
| """{ | |
| "customer_name": "", | |
| "company": "", | |
| "contact": { | |
| "email": "", | |
| "phone": "" | |
| }, | |
| "order": { | |
| "items": [], | |
| "delivery_address": "", | |
| "delivery_deadline": "", | |
| "budget_gbp": null | |
| }, | |
| "notes": "" | |
| }""" | |
| ], | |
| [ | |
| """Need to book travel for Sarah. Flying from London to Dubai on 12 April, returning 19 April. Prefers morning departure, aisle seat, 1 checked bag, hotel near Marina if under £180/night. She is vegetarian and the passport expires in November 2027.""", | |
| "" | |
| ], | |
| [ | |
| """Meeting notes: | |
| - Project Phoenix delayed because API vendor still hasn't delivered auth docs | |
| - Sam to chase vendor Monday | |
| - Priya to update timeline | |
| - New target launch maybe end of Q3 | |
| - Risks: security review, client sign-off, payment integration | |
| - Budget pressure but no exact numbers yet""", | |
| """{ | |
| "project_name": "", | |
| "status": "", | |
| "blockers": [], | |
| "actions": [], | |
| "target_launch": "", | |
| "risks": [], | |
| "budget": { | |
| "status": "", | |
| "amount": null | |
| } | |
| }""" | |
| ], | |
| ] | |
| # ============================================================================= | |
| # Gradio UI | |
| # ============================================================================= | |
| with gr.Blocks(title="Prompt → JSON Extractor") as demo: | |
| gr.Markdown( | |
| """ | |
| # Prompt → JSON Extractor | |
| Paste messy natural language and convert it into structured JSON. | |
| Optionally provide a target schema or field hints. | |
| """.strip() | |
| ) | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| source_input = gr.Textbox( | |
| label="Messy natural language input", | |
| placeholder="Paste notes, emails, chat logs, order requests, meeting notes, etc.", | |
| lines=16, | |
| max_lines=24, | |
| ) | |
| schema_input = gr.Textbox( | |
| label="Optional schema / desired fields", | |
| placeholder='Example: {"name":"","email":"","order":{"items":[],"budget":null}}', | |
| lines=10, | |
| max_lines=16, | |
| ) | |
| with gr.Row(): | |
| extract_btn = gr.Button("Extract JSON", variant="primary") | |
| clear_btn = gr.Button("Clear") | |
| with gr.Column(scale=1): | |
| json_output = gr.Code( | |
| label="Extracted JSON", | |
| language="json", | |
| lines=24, | |
| interactive=False, | |
| ) | |
| status_output = gr.Textbox( | |
| label="Status", | |
| interactive=False, | |
| ) | |
| gr.Examples( | |
| examples=EXAMPLES, | |
| inputs=[source_input, schema_input], | |
| ) | |
| # Button actions. | |
| extract_btn.click( | |
| fn=extract_json, | |
| inputs=[source_input, schema_input], | |
| outputs=[json_output, status_output], | |
| ) | |
| clear_btn.click( | |
| fn=lambda: ("", "", "", ""), | |
| inputs=[], | |
| outputs=[source_input, schema_input, json_output, status_output], | |
| ) | |
| # ============================================================================= | |
| # Launch | |
| # ============================================================================= | |
| demo.launch(ssr_mode=False) |