Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,216 +1,646 @@
|
|
| 1 |
-
|
| 2 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
import os
|
| 4 |
-
import
|
| 5 |
import time
|
| 6 |
import uuid
|
|
|
|
|
|
|
| 7 |
|
| 8 |
import gradio as gr
|
| 9 |
from huggingface_hub import InferenceClient
|
| 10 |
|
| 11 |
-
MODEL = os.getenv("HF_MODEL", "Qwen/Qwen2.5-72B-Instruct")
|
| 12 |
-
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 13 |
-
MAX_TOKENS = int(os.getenv("MAX_TOKENS", "1200"))
|
| 14 |
-
TEMPERATURE = float(os.getenv("TEMPERATURE", "0.2"))
|
| 15 |
-
TOP_P = float(os.getenv("TOP_P", "0.9"))
|
| 16 |
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
handlers=[logging.StreamHandler(sys.stdout)],
|
| 21 |
-
)
|
| 22 |
-
logger = logging.getLogger("prompt_json_extractor")
|
| 23 |
|
|
|
|
|
|
|
| 24 |
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
Return ONLY valid JSON.
|
| 30 |
-
Do not wrap it in markdown.
|
| 31 |
-
Do not include explanations outside JSON.
|
| 32 |
-
|
| 33 |
-
Your job:
|
| 34 |
-
- infer the user's intent
|
| 35 |
-
- extract entities, attributes, dates, constraints, preferences, priorities, and action items
|
| 36 |
-
- preserve ambiguity rather than inventing false certainty
|
| 37 |
-
- normalize obvious fields where possible
|
| 38 |
-
|
| 39 |
-
Return JSON with exactly these top-level keys:
|
| 40 |
-
- task_type
|
| 41 |
-
- summary
|
| 42 |
-
- extracted_fields
|
| 43 |
-
- constraints
|
| 44 |
-
- assumptions
|
| 45 |
-
- missing_information
|
| 46 |
-
- confidence
|
| 47 |
-
- suggested_schema
|
| 48 |
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
2. summary must be a concise string
|
| 52 |
-
3. extracted_fields must be an object/dictionary
|
| 53 |
-
4. constraints must be an array of strings
|
| 54 |
-
5. assumptions must be an array of strings
|
| 55 |
-
6. missing_information must be an array of strings
|
| 56 |
-
7. confidence must be a number between 0 and 1
|
| 57 |
-
8. suggested_schema must be an object showing a cleaner target structure
|
| 58 |
-
9. If something is unclear, put it under missing_information or assumptions
|
| 59 |
-
10. Be useful, practical, and conservative
|
| 60 |
-
""".strip()
|
| 61 |
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
logger.info("REQUEST %s | extraction started", request_id)
|
| 68 |
-
logger.info("REQUEST %s | model=%s", request_id, MODEL)
|
| 69 |
-
logger.info("REQUEST %s | hf_token_present=%s", request_id, bool(HF_TOKEN))
|
| 70 |
-
logger.info("REQUEST %s | input_preview=%r", request_id, user_text[:500])
|
| 71 |
-
|
| 72 |
-
if not HF_TOKEN:
|
| 73 |
-
logger.error("REQUEST %s | HF_TOKEN missing", request_id)
|
| 74 |
-
raise RuntimeError("HF_TOKEN is missing in Space Secrets.")
|
| 75 |
-
|
| 76 |
-
client = InferenceClient(token=HF_TOKEN)
|
| 77 |
-
|
| 78 |
-
messages = [
|
| 79 |
-
{"role": "system", "content": system_prompt()},
|
| 80 |
-
{
|
| 81 |
-
"role": "user",
|
| 82 |
-
"content": (
|
| 83 |
-
"Convert the following messy natural language into structured JSON.\n\n"
|
| 84 |
-
f"{user_text}"
|
| 85 |
-
),
|
| 86 |
-
},
|
| 87 |
-
]
|
| 88 |
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
)
|
| 96 |
|
| 97 |
-
elapsed = time.time() - start
|
| 98 |
-
logger.info("REQUEST %s | response received in %.2fs", request_id, elapsed)
|
| 99 |
|
| 100 |
-
|
| 101 |
-
logger.info("REQUEST %s | raw_response_preview=%r", request_id, content[:500])
|
| 102 |
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
logger.exception("REQUEST %s | JSON parsing failed", request_id)
|
| 107 |
-
raise RuntimeError("Model returned invalid JSON. Check Space logs.") from e
|
| 108 |
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
"
|
| 114 |
-
|
| 115 |
|
| 116 |
-
logger.info("REQUEST %s | JSON parsed successfully", request_id)
|
| 117 |
-
return parsed
|
| 118 |
|
|
|
|
|
|
|
|
|
|
| 119 |
|
| 120 |
-
def
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
return "- None"
|
| 124 |
-
return "\n".join(f"- {item}" for item in items)
|
| 125 |
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
|
| 130 |
-
return f"""
|
| 131 |
-
# Structured Extraction
|
| 132 |
|
| 133 |
-
|
| 134 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
|
| 136 |
-
|
| 137 |
-
{
|
| 138 |
|
| 139 |
-
|
| 140 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
|
| 142 |
-
|
| 143 |
-
|
| 144 |
|
| 145 |
-
|
| 146 |
-
{
|
|
|
|
| 147 |
|
| 148 |
-
## Missing Information
|
| 149 |
-
{bullet_list(data.get("missing_information", []))}
|
| 150 |
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
|
| 155 |
-
|
| 156 |
-
|
|
|
|
|
|
|
| 157 |
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
""".strip()
|
| 162 |
|
| 163 |
-
def run_extraction(user_text: str):
|
| 164 |
-
if not user_text or not user_text.strip():
|
| 165 |
-
raise gr.Error("Please paste some natural language input.")
|
| 166 |
|
| 167 |
-
|
| 168 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
|
| 199 |
-
|
| 200 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
|
|
|
| 206 |
|
| 207 |
-
run_btn.click(
|
| 208 |
-
fn=run_extraction,
|
| 209 |
-
inputs=[input_text],
|
| 210 |
-
outputs=[output_md, output_json],
|
| 211 |
-
)
|
| 212 |
|
| 213 |
-
|
| 214 |
-
|
|
|
|
| 215 |
|
| 216 |
-
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
app.py
|
| 3 |
+
------
|
| 4 |
+
Hugging Face Space: Prompt -> JSON Extractor
|
| 5 |
+
|
| 6 |
+
Purpose
|
| 7 |
+
-------
|
| 8 |
+
This Gradio app accepts messy natural language input and converts it into
|
| 9 |
+
structured JSON using a strong instruction-tuned model.
|
| 10 |
+
|
| 11 |
+
Key features
|
| 12 |
+
------------
|
| 13 |
+
- Clean single-file Gradio app
|
| 14 |
+
- Extensive inline comments and documentation
|
| 15 |
+
- Robust logging to server console only (visible in Space logs, not in UI)
|
| 16 |
+
- Strong system prompt for reliable JSON-only extraction
|
| 17 |
+
- Optional user-provided extraction schema / field hints
|
| 18 |
+
- JSON validation and repair pass
|
| 19 |
+
- Friendly error handling
|
| 20 |
+
- Examples included
|
| 21 |
+
|
| 22 |
+
Expected environment
|
| 23 |
+
--------------------
|
| 24 |
+
This app is designed for Hugging Face Spaces.
|
| 25 |
+
|
| 26 |
+
Recommended secrets / environment variables:
|
| 27 |
+
- HF_TOKEN
|
| 28 |
+
or
|
| 29 |
+
- HUGGINGFACEHUB_API_TOKEN
|
| 30 |
+
|
| 31 |
+
Recommended requirements.txt (example)
|
| 32 |
+
--------------------------------------
|
| 33 |
+
gradio>=5.0.0
|
| 34 |
+
huggingface_hub>=0.24.0
|
| 35 |
+
|
| 36 |
+
Notes
|
| 37 |
+
-----
|
| 38 |
+
- The UI shows only the extracted JSON and status information.
|
| 39 |
+
- Internal logs are written using Python logging and are not displayed to end users.
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
import os
|
| 43 |
+
import json
|
| 44 |
import time
|
| 45 |
import uuid
|
| 46 |
+
import logging
|
| 47 |
+
from typing import Any, Dict, Optional, Tuple
|
| 48 |
|
| 49 |
import gradio as gr
|
| 50 |
from huggingface_hub import InferenceClient
|
| 51 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
+
# =============================================================================
|
| 54 |
+
# Configuration
|
| 55 |
+
# =============================================================================
|
|
|
|
|
|
|
|
|
|
| 56 |
|
| 57 |
+
# Strong instruct model as requested by the user.
|
| 58 |
+
MODEL_NAME = "Qwen/Qwen2.5-72B-Instruct"
|
| 59 |
|
| 60 |
+
# Maximum characters accepted from the user for the source text.
|
| 61 |
+
# This helps avoid accidental overload from extremely large pastes.
|
| 62 |
+
MAX_INPUT_CHARS = 20000
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
|
| 64 |
+
# Optional upper bound for schema / extraction guidance text.
|
| 65 |
+
MAX_SCHEMA_CHARS = 8000
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
+
# Generation settings.
|
| 68 |
+
TEMPERATURE = 0.1
|
| 69 |
+
MAX_NEW_TOKENS = 1800
|
| 70 |
|
| 71 |
+
# Logging configuration.
|
| 72 |
+
# Logs go to the Space/server logs and are not shown in the Gradio interface.
|
| 73 |
+
LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO").upper()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
|
| 75 |
+
|
| 76 |
+
# =============================================================================
|
| 77 |
+
# Logging setup
|
| 78 |
+
# =============================================================================
|
| 79 |
+
|
| 80 |
+
logger = logging.getLogger("prompt_to_json_extractor")
|
| 81 |
+
logger.setLevel(LOG_LEVEL)
|
| 82 |
+
|
| 83 |
+
# Avoid duplicate handlers if Spaces reloads the app.
|
| 84 |
+
if not logger.handlers:
|
| 85 |
+
handler = logging.StreamHandler()
|
| 86 |
+
formatter = logging.Formatter(
|
| 87 |
+
fmt="%(asctime)s | %(levelname)s | %(name)s | %(message)s"
|
| 88 |
+
)
|
| 89 |
+
handler.setFormatter(formatter)
|
| 90 |
+
logger.addHandler(handler)
|
| 91 |
+
|
| 92 |
+
logger.info("Starting Prompt -> JSON Extractor app")
|
| 93 |
+
logger.info("Configured model: %s", MODEL_NAME)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
# =============================================================================
|
| 97 |
+
# Hugging Face client setup
|
| 98 |
+
# =============================================================================
|
| 99 |
+
|
| 100 |
+
def get_hf_token() -> Optional[str]:
|
| 101 |
+
"""
|
| 102 |
+
Fetch an HF API token from common environment variable names.
|
| 103 |
+
|
| 104 |
+
Returns
|
| 105 |
+
-------
|
| 106 |
+
Optional[str]
|
| 107 |
+
Token string if found, otherwise None.
|
| 108 |
+
"""
|
| 109 |
+
return (
|
| 110 |
+
os.getenv("HF_TOKEN")
|
| 111 |
+
or os.getenv("HUGGINGFACEHUB_API_TOKEN")
|
| 112 |
+
or os.getenv("HUGGING_FACE_HUB_TOKEN")
|
| 113 |
)
|
| 114 |
|
|
|
|
|
|
|
| 115 |
|
| 116 |
+
HF_TOKEN = get_hf_token()
|
|
|
|
| 117 |
|
| 118 |
+
# Initialize the inference client.
|
| 119 |
+
# If no token is present, some models/endpoints may fail depending on access.
|
| 120 |
+
client = InferenceClient(token=HF_TOKEN)
|
|
|
|
|
|
|
| 121 |
|
| 122 |
+
if HF_TOKEN:
|
| 123 |
+
logger.info("HF token detected")
|
| 124 |
+
else:
|
| 125 |
+
logger.warning(
|
| 126 |
+
"No HF token detected. If the model requires authenticated access, calls may fail."
|
| 127 |
+
)
|
| 128 |
|
|
|
|
|
|
|
| 129 |
|
| 130 |
+
# =============================================================================
|
| 131 |
+
# Prompt helpers
|
| 132 |
+
# =============================================================================
|
| 133 |
|
| 134 |
+
def build_system_prompt() -> str:
|
| 135 |
+
"""
|
| 136 |
+
Build the core system prompt that instructs the model to output strict JSON.
|
|
|
|
|
|
|
| 137 |
|
| 138 |
+
Design goals
|
| 139 |
+
------------
|
| 140 |
+
- JSON only, no markdown, no explanations
|
| 141 |
+
- Extract as much structure as reasonably possible
|
| 142 |
+
- Preserve uncertainty explicitly using null / arrays / notes when needed
|
| 143 |
+
- Avoid inventing facts
|
| 144 |
+
"""
|
| 145 |
+
return """
|
| 146 |
+
You are a precise information extraction engine.
|
| 147 |
+
|
| 148 |
+
Your task:
|
| 149 |
+
Convert messy natural language into a clean, structured JSON object.
|
| 150 |
+
|
| 151 |
+
Critical rules:
|
| 152 |
+
1. Output valid JSON only.
|
| 153 |
+
2. Do not wrap the JSON in markdown fences.
|
| 154 |
+
3. Do not include any explanation before or after the JSON.
|
| 155 |
+
4. Do not invent facts that are not supported by the input.
|
| 156 |
+
5. If something is missing or unclear, use null, an empty array, or a brief uncertainty note.
|
| 157 |
+
6. Preserve important details faithfully.
|
| 158 |
+
7. Normalize values where reasonable:
|
| 159 |
+
- dates -> ISO-like strings if clear, otherwise keep original text
|
| 160 |
+
- numbers -> numeric types where clear
|
| 161 |
+
- booleans -> true/false where clearly supported
|
| 162 |
+
8. If the user provides a target schema, follow it closely.
|
| 163 |
+
9. If no schema is provided, infer a sensible schema from the content.
|
| 164 |
+
10. Return a single top-level JSON object, not multiple objects.
|
| 165 |
+
|
| 166 |
+
Preferred behavior when no schema is given:
|
| 167 |
+
- Create semantically meaningful keys.
|
| 168 |
+
- Group related fields into nested objects where appropriate.
|
| 169 |
+
- Use arrays for repeated items.
|
| 170 |
+
- Keep the structure concise but useful.
|
| 171 |
+
|
| 172 |
+
Never output anything except raw valid JSON.
|
| 173 |
+
""".strip()
|
| 174 |
|
|
|
|
|
|
|
| 175 |
|
| 176 |
+
def build_user_prompt(source_text: str, schema_hint: str) -> str:
|
| 177 |
+
"""
|
| 178 |
+
Build the user message supplied to the model.
|
| 179 |
+
|
| 180 |
+
Parameters
|
| 181 |
+
----------
|
| 182 |
+
source_text : str
|
| 183 |
+
The messy natural language input from the user.
|
| 184 |
+
schema_hint : str
|
| 185 |
+
Optional schema or extraction guidance.
|
| 186 |
+
|
| 187 |
+
Returns
|
| 188 |
+
-------
|
| 189 |
+
str
|
| 190 |
+
User prompt content.
|
| 191 |
+
"""
|
| 192 |
+
if schema_hint.strip():
|
| 193 |
+
return f"""
|
| 194 |
+
Extract structured JSON from the following text.
|
| 195 |
|
| 196 |
+
Target schema / extraction guidance:
|
| 197 |
+
{schema_hint.strip()}
|
| 198 |
|
| 199 |
+
Source text:
|
| 200 |
+
{source_text.strip()}
|
| 201 |
+
""".strip()
|
| 202 |
+
|
| 203 |
+
return f"""
|
| 204 |
+
Extract structured JSON from the following text.
|
| 205 |
|
| 206 |
+
No fixed schema was provided.
|
| 207 |
+
Infer a sensible structure based on the content.
|
| 208 |
|
| 209 |
+
Source text:
|
| 210 |
+
{source_text.strip()}
|
| 211 |
+
""".strip()
|
| 212 |
|
|
|
|
|
|
|
| 213 |
|
| 214 |
+
def build_repair_prompt(bad_output: str) -> str:
|
| 215 |
+
"""
|
| 216 |
+
Build a fallback repair prompt used if the first model response is not valid JSON.
|
| 217 |
|
| 218 |
+
Parameters
|
| 219 |
+
----------
|
| 220 |
+
bad_output : str
|
| 221 |
+
The invalid or messy model output.
|
| 222 |
|
| 223 |
+
Returns
|
| 224 |
+
-------
|
| 225 |
+
str
|
| 226 |
+
Repair prompt content.
|
| 227 |
+
"""
|
| 228 |
+
return f"""
|
| 229 |
+
The following content is intended to be JSON but is invalid or contains extra text.
|
| 230 |
+
|
| 231 |
+
Repair it into a single valid JSON object.
|
| 232 |
+
Rules:
|
| 233 |
+
- Output valid JSON only.
|
| 234 |
+
- Do not include markdown fences.
|
| 235 |
+
- Do not include explanations.
|
| 236 |
+
- Preserve the original meaning as closely as possible.
|
| 237 |
+
|
| 238 |
+
Content to repair:
|
| 239 |
+
{bad_output}
|
| 240 |
""".strip()
|
| 241 |
|
|
|
|
|
|
|
|
|
|
| 242 |
|
| 243 |
+
# =============================================================================
|
| 244 |
+
# Utility helpers
|
| 245 |
+
# =============================================================================
|
| 246 |
+
|
| 247 |
+
def safe_trim(text: str, max_chars: int) -> str:
|
| 248 |
+
"""
|
| 249 |
+
Trim text to a maximum length safely.
|
| 250 |
+
|
| 251 |
+
Parameters
|
| 252 |
+
----------
|
| 253 |
+
text : str
|
| 254 |
+
Input text.
|
| 255 |
+
max_chars : int
|
| 256 |
+
Maximum allowed characters.
|
| 257 |
+
|
| 258 |
+
Returns
|
| 259 |
+
-------
|
| 260 |
+
str
|
| 261 |
+
Trimmed text.
|
| 262 |
+
"""
|
| 263 |
+
if len(text) <= max_chars:
|
| 264 |
+
return text
|
| 265 |
+
return text[:max_chars]
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def extract_text_from_response(response: Any) -> str:
|
| 269 |
+
"""
|
| 270 |
+
Extract text content from Hugging Face chat completion responses.
|
| 271 |
+
|
| 272 |
+
Because API client response formats can vary slightly by version/model,
|
| 273 |
+
this function tries a few common access patterns.
|
| 274 |
+
|
| 275 |
+
Parameters
|
| 276 |
+
----------
|
| 277 |
+
response : Any
|
| 278 |
+
Response returned by InferenceClient.chat_completion(...)
|
| 279 |
+
|
| 280 |
+
Returns
|
| 281 |
+
-------
|
| 282 |
+
str
|
| 283 |
+
Extracted text content.
|
| 284 |
+
|
| 285 |
+
Raises
|
| 286 |
+
------
|
| 287 |
+
ValueError
|
| 288 |
+
If text content cannot be extracted.
|
| 289 |
+
"""
|
| 290 |
+
logger.debug("Raw response type: %s", type(response))
|
| 291 |
+
|
| 292 |
+
# Common object-style access:
|
| 293 |
+
try:
|
| 294 |
+
content = response.choices[0].message.content
|
| 295 |
+
if isinstance(content, str):
|
| 296 |
+
return content
|
| 297 |
+
except Exception:
|
| 298 |
+
pass
|
| 299 |
+
|
| 300 |
+
# Common dict-style access:
|
| 301 |
+
try:
|
| 302 |
+
content = response["choices"][0]["message"]["content"]
|
| 303 |
+
if isinstance(content, str):
|
| 304 |
+
return content
|
| 305 |
+
except Exception:
|
| 306 |
+
pass
|
| 307 |
+
|
| 308 |
+
# Last-resort string cast.
|
| 309 |
+
try:
|
| 310 |
+
as_text = str(response)
|
| 311 |
+
if as_text:
|
| 312 |
+
return as_text
|
| 313 |
+
except Exception:
|
| 314 |
+
pass
|
| 315 |
+
|
| 316 |
+
raise ValueError("Could not extract text content from model response.")
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def parse_json_strict(text: str) -> Dict[str, Any]:
|
| 320 |
+
"""
|
| 321 |
+
Parse JSON strictly, expecting a top-level object.
|
| 322 |
+
|
| 323 |
+
Parameters
|
| 324 |
+
----------
|
| 325 |
+
text : str
|
| 326 |
+
Raw text expected to be JSON.
|
| 327 |
+
|
| 328 |
+
Returns
|
| 329 |
+
-------
|
| 330 |
+
Dict[str, Any]
|
| 331 |
+
Parsed JSON object.
|
| 332 |
+
|
| 333 |
+
Raises
|
| 334 |
+
------
|
| 335 |
+
ValueError
|
| 336 |
+
If parsing fails or the top level is not a JSON object.
|
| 337 |
+
"""
|
| 338 |
+
data = json.loads(text)
|
| 339 |
+
if not isinstance(data, dict):
|
| 340 |
+
raise ValueError("Model returned JSON, but top level is not an object.")
|
| 341 |
+
return data
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
def pretty_json(data: Dict[str, Any]) -> str:
|
| 345 |
+
"""
|
| 346 |
+
Format a Python dictionary as pretty JSON.
|
| 347 |
+
|
| 348 |
+
Parameters
|
| 349 |
+
----------
|
| 350 |
+
data : Dict[str, Any]
|
| 351 |
+
Parsed JSON object.
|
| 352 |
+
|
| 353 |
+
Returns
|
| 354 |
+
-------
|
| 355 |
+
str
|
| 356 |
+
Pretty-printed JSON string.
|
| 357 |
+
"""
|
| 358 |
+
return json.dumps(data, indent=2, ensure_ascii=False)
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
# =============================================================================
|
| 362 |
+
# Model calling logic
|
| 363 |
+
# =============================================================================
|
| 364 |
+
|
| 365 |
+
def call_model_for_json(source_text: str, schema_hint: str, request_id: str) -> Tuple[Dict[str, Any], str]:
|
| 366 |
+
"""
|
| 367 |
+
Call the model to extract JSON from source text, with a repair fallback if needed.
|
| 368 |
+
|
| 369 |
+
Flow
|
| 370 |
+
----
|
| 371 |
+
1. Send extraction request
|
| 372 |
+
2. Attempt strict JSON parse
|
| 373 |
+
3. If parsing fails, run a repair pass
|
| 374 |
+
4. Parse repaired output
|
| 375 |
+
5. Return parsed dict and a status string
|
| 376 |
+
|
| 377 |
+
Parameters
|
| 378 |
+
----------
|
| 379 |
+
source_text : str
|
| 380 |
+
User input to structure.
|
| 381 |
+
schema_hint : str
|
| 382 |
+
Optional extraction schema or guidance.
|
| 383 |
+
request_id : str
|
| 384 |
+
Unique request identifier for logging.
|
| 385 |
+
|
| 386 |
+
Returns
|
| 387 |
+
-------
|
| 388 |
+
Tuple[Dict[str, Any], str]
|
| 389 |
+
Parsed JSON object and status string.
|
| 390 |
+
|
| 391 |
+
Raises
|
| 392 |
+
------
|
| 393 |
+
RuntimeError
|
| 394 |
+
If model output cannot be repaired into valid JSON.
|
| 395 |
+
"""
|
| 396 |
+
system_prompt = build_system_prompt()
|
| 397 |
+
user_prompt = build_user_prompt(source_text, schema_hint)
|
| 398 |
+
|
| 399 |
+
logger.info("[%s] Sending primary extraction request to model", request_id)
|
| 400 |
+
logger.debug("[%s] Source length: %d chars", request_id, len(source_text))
|
| 401 |
+
logger.debug("[%s] Schema length: %d chars", request_id, len(schema_hint))
|
| 402 |
+
|
| 403 |
+
response = client.chat_completion(
|
| 404 |
+
model=MODEL_NAME,
|
| 405 |
+
messages=[
|
| 406 |
+
{"role": "system", "content": system_prompt},
|
| 407 |
+
{"role": "user", "content": user_prompt},
|
| 408 |
+
],
|
| 409 |
+
temperature=TEMPERATURE,
|
| 410 |
+
max_tokens=MAX_NEW_TOKENS,
|
| 411 |
+
)
|
| 412 |
+
|
| 413 |
+
raw_output = extract_text_from_response(response).strip()
|
| 414 |
+
logger.info("[%s] Received primary response (%d chars)", request_id, len(raw_output))
|
| 415 |
+
logger.debug("[%s] Primary raw output: %s", request_id, raw_output)
|
| 416 |
+
|
| 417 |
+
# First attempt: strict JSON parse.
|
| 418 |
+
try:
|
| 419 |
+
parsed = parse_json_strict(raw_output)
|
| 420 |
+
logger.info("[%s] Primary response parsed successfully as JSON", request_id)
|
| 421 |
+
return parsed, "Success"
|
| 422 |
+
except Exception as first_error:
|
| 423 |
+
logger.warning("[%s] Primary parse failed: %s", request_id, first_error)
|
| 424 |
+
|
| 425 |
+
# Second attempt: repair invalid JSON / extra text.
|
| 426 |
+
logger.info("[%s] Sending repair request to model", request_id)
|
| 427 |
+
repair_response = client.chat_completion(
|
| 428 |
+
model=MODEL_NAME,
|
| 429 |
+
messages=[
|
| 430 |
+
{"role": "system", "content": build_system_prompt()},
|
| 431 |
+
{"role": "user", "content": build_repair_prompt(raw_output)},
|
| 432 |
+
],
|
| 433 |
+
temperature=0.0,
|
| 434 |
+
max_tokens=MAX_NEW_TOKENS,
|
| 435 |
+
)
|
| 436 |
+
|
| 437 |
+
repaired_output = extract_text_from_response(repair_response).strip()
|
| 438 |
+
logger.info("[%s] Received repair response (%d chars)", request_id, len(repaired_output))
|
| 439 |
+
logger.debug("[%s] Repaired raw output: %s", request_id, repaired_output)
|
| 440 |
+
|
| 441 |
+
try:
|
| 442 |
+
parsed = parse_json_strict(repaired_output)
|
| 443 |
+
logger.info("[%s] Repair response parsed successfully as JSON", request_id)
|
| 444 |
+
return parsed, "Success (repaired invalid initial output)"
|
| 445 |
+
except Exception as repair_error:
|
| 446 |
+
logger.error("[%s] Repair parse failed: %s", request_id, repair_error)
|
| 447 |
+
raise RuntimeError(
|
| 448 |
+
"The model response could not be converted into valid JSON."
|
| 449 |
+
) from repair_error
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
# =============================================================================
|
| 453 |
+
# Gradio-facing function
|
| 454 |
+
# =============================================================================
|
| 455 |
+
|
| 456 |
+
def extract_json(source_text: str, schema_hint: str) -> Tuple[str, str]:
|
| 457 |
+
"""
|
| 458 |
+
Main Gradio callback.
|
| 459 |
+
|
| 460 |
+
Parameters
|
| 461 |
+
----------
|
| 462 |
+
source_text : str
|
| 463 |
+
Raw user text to extract from.
|
| 464 |
+
schema_hint : str
|
| 465 |
+
Optional schema or desired fields.
|
| 466 |
+
|
| 467 |
+
Returns
|
| 468 |
+
-------
|
| 469 |
+
Tuple[str, str]
|
| 470 |
+
pretty_json_output, status_text
|
| 471 |
+
"""
|
| 472 |
+
request_id = str(uuid.uuid4())[:8]
|
| 473 |
+
start_time = time.time()
|
| 474 |
+
|
| 475 |
+
logger.info("[%s] New extraction request started", request_id)
|
| 476 |
+
|
| 477 |
+
try:
|
| 478 |
+
source_text = (source_text or "").strip()
|
| 479 |
+
schema_hint = (schema_hint or "").strip()
|
| 480 |
+
|
| 481 |
+
# Basic validation.
|
| 482 |
+
if not source_text:
|
| 483 |
+
logger.warning("[%s] Empty source text submitted", request_id)
|
| 484 |
+
return "", "Please provide some source text."
|
| 485 |
+
|
| 486 |
+
if len(source_text) > MAX_INPUT_CHARS:
|
| 487 |
+
logger.warning(
|
| 488 |
+
"[%s] Source text exceeded limit (%d > %d), trimming",
|
| 489 |
+
request_id,
|
| 490 |
+
len(source_text),
|
| 491 |
+
MAX_INPUT_CHARS,
|
| 492 |
+
)
|
| 493 |
+
source_text = safe_trim(source_text, MAX_INPUT_CHARS)
|
| 494 |
+
|
| 495 |
+
if len(schema_hint) > MAX_SCHEMA_CHARS:
|
| 496 |
+
logger.warning(
|
| 497 |
+
"[%s] Schema hint exceeded limit (%d > %d), trimming",
|
| 498 |
+
request_id,
|
| 499 |
+
len(schema_hint),
|
| 500 |
+
MAX_SCHEMA_CHARS,
|
| 501 |
+
)
|
| 502 |
+
schema_hint = safe_trim(schema_hint, MAX_SCHEMA_CHARS)
|
| 503 |
+
|
| 504 |
+
# Run extraction.
|
| 505 |
+
parsed, status = call_model_for_json(
|
| 506 |
+
source_text=source_text,
|
| 507 |
+
schema_hint=schema_hint,
|
| 508 |
+
request_id=request_id,
|
| 509 |
+
)
|
| 510 |
+
|
| 511 |
+
# Pretty-print for UI output.
|
| 512 |
+
output_json = pretty_json(parsed)
|
| 513 |
+
|
| 514 |
+
elapsed = time.time() - start_time
|
| 515 |
+
logger.info("[%s] Request completed successfully in %.2fs", request_id, elapsed)
|
| 516 |
+
|
| 517 |
+
return output_json, f"{status} | Request ID: {request_id} | Time: {elapsed:.2f}s"
|
| 518 |
+
|
| 519 |
+
except Exception as e:
|
| 520 |
+
elapsed = time.time() - start_time
|
| 521 |
+
logger.exception("[%s] Request failed after %.2fs", request_id, elapsed)
|
| 522 |
+
return "", f"Error: {str(e)} | Request ID: {request_id}"
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
# =============================================================================
|
| 526 |
+
# Example content
|
| 527 |
+
# =============================================================================
|
| 528 |
|
| 529 |
EXAMPLES = [
|
| 530 |
+
[
|
| 531 |
+
"""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.""",
|
| 532 |
+
"""{
|
| 533 |
+
"customer_name": "",
|
| 534 |
+
"company": "",
|
| 535 |
+
"contact": {
|
| 536 |
+
"email": "",
|
| 537 |
+
"phone": ""
|
| 538 |
+
},
|
| 539 |
+
"order": {
|
| 540 |
+
"items": [],
|
| 541 |
+
"delivery_address": "",
|
| 542 |
+
"delivery_deadline": "",
|
| 543 |
+
"budget_gbp": null
|
| 544 |
+
},
|
| 545 |
+
"notes": ""
|
| 546 |
+
}"""
|
| 547 |
+
],
|
| 548 |
+
[
|
| 549 |
+
"""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.""",
|
| 550 |
+
""
|
| 551 |
+
],
|
| 552 |
+
[
|
| 553 |
+
"""Meeting notes:
|
| 554 |
+
- Project Phoenix delayed because API vendor still hasn't delivered auth docs
|
| 555 |
+
- Sam to chase vendor Monday
|
| 556 |
+
- Priya to update timeline
|
| 557 |
+
- New target launch maybe end of Q3
|
| 558 |
+
- Risks: security review, client sign-off, payment integration
|
| 559 |
+
- Budget pressure but no exact numbers yet""",
|
| 560 |
+
"""{
|
| 561 |
+
"project_name": "",
|
| 562 |
+
"status": "",
|
| 563 |
+
"blockers": [],
|
| 564 |
+
"actions": [],
|
| 565 |
+
"target_launch": "",
|
| 566 |
+
"risks": [],
|
| 567 |
+
"budget": {
|
| 568 |
+
"status": "",
|
| 569 |
+
"amount": null
|
| 570 |
+
}
|
| 571 |
+
}"""
|
| 572 |
+
],
|
| 573 |
]
|
| 574 |
|
| 575 |
+
|
| 576 |
+
# =============================================================================
|
| 577 |
+
# Gradio UI
|
| 578 |
+
# =============================================================================
|
| 579 |
+
|
| 580 |
with gr.Blocks(title="Prompt → JSON Extractor") as demo:
|
| 581 |
+
gr.Markdown(
|
| 582 |
+
"""
|
| 583 |
+
# Prompt → JSON Extractor
|
|
|
|
| 584 |
|
| 585 |
+
Paste messy natural language and convert it into structured JSON.
|
| 586 |
+
Optionally provide a target schema or field hints.
|
| 587 |
+
""".strip()
|
| 588 |
+
)
|
|
|
|
| 589 |
|
| 590 |
+
with gr.Row():
|
| 591 |
+
with gr.Column(scale=1):
|
| 592 |
+
source_input = gr.Textbox(
|
| 593 |
+
label="Messy natural language input",
|
| 594 |
+
placeholder="Paste notes, emails, chat logs, order requests, meeting notes, etc.",
|
| 595 |
+
lines=16,
|
| 596 |
+
max_lines=24,
|
| 597 |
+
)
|
| 598 |
+
|
| 599 |
+
schema_input = gr.Textbox(
|
| 600 |
+
label="Optional schema / desired fields",
|
| 601 |
+
placeholder='Example: {"name":"","email":"","order":{"items":[],"budget":null}}',
|
| 602 |
+
lines=10,
|
| 603 |
+
max_lines=16,
|
| 604 |
+
)
|
| 605 |
+
|
| 606 |
+
with gr.Row():
|
| 607 |
+
extract_btn = gr.Button("Extract JSON", variant="primary")
|
| 608 |
+
clear_btn = gr.Button("Clear")
|
| 609 |
+
|
| 610 |
+
with gr.Column(scale=1):
|
| 611 |
+
json_output = gr.Code(
|
| 612 |
+
label="Extracted JSON",
|
| 613 |
+
language="json",
|
| 614 |
+
lines=24,
|
| 615 |
+
interactive=False,
|
| 616 |
+
)
|
| 617 |
+
|
| 618 |
+
status_output = gr.Textbox(
|
| 619 |
+
label="Status",
|
| 620 |
+
interactive=False,
|
| 621 |
+
)
|
| 622 |
+
|
| 623 |
+
gr.Examples(
|
| 624 |
+
examples=EXAMPLES,
|
| 625 |
+
inputs=[source_input, schema_input],
|
| 626 |
+
)
|
| 627 |
|
| 628 |
+
# Button actions.
|
| 629 |
+
extract_btn.click(
|
| 630 |
+
fn=extract_json,
|
| 631 |
+
inputs=[source_input, schema_input],
|
| 632 |
+
outputs=[json_output, status_output],
|
| 633 |
+
)
|
| 634 |
|
| 635 |
+
clear_btn.click(
|
| 636 |
+
fn=lambda: ("", "", "", ""),
|
| 637 |
+
inputs=[],
|
| 638 |
+
outputs=[source_input, schema_input, json_output, status_output],
|
| 639 |
+
)
|
| 640 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 641 |
|
| 642 |
+
# =============================================================================
|
| 643 |
+
# Launch
|
| 644 |
+
# =============================================================================
|
| 645 |
|
| 646 |
+
demo.launch(ssr_mode=False)
|