Spaces:
Sleeping

File size: 18,605 Bytes
fc2da7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1eea330
fc2da7c
1eea330
 
fc2da7c
 
1eea330
 
 
 
 
fc2da7c
 
 
1eea330
fc2da7c
 
1eea330
fc2da7c
 
 
1eea330
fc2da7c
 
1eea330
fc2da7c
 
 
1eea330
fc2da7c
 
 
1eea330
fc2da7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1eea330
 
 
fc2da7c
1eea330
fc2da7c
 
 
1eea330
fc2da7c
 
 
 
 
 
1eea330
 
fc2da7c
 
 
1eea330
fc2da7c
 
 
1eea330
fc2da7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1eea330
 
fc2da7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1eea330
fc2da7c
 
1eea330
fc2da7c
 
 
 
 
 
1eea330
fc2da7c
 
1eea330
fc2da7c
 
 
1eea330
 
fc2da7c
 
 
b82113c
fc2da7c
 
 
 
b82113c
fc2da7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b82113c
 
 
fc2da7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b82113c
 
fc2da7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b82113c
 
fc2da7c
 
 
 
 
b82113c
fc2da7c
 
 
b82113c
fc2da7c
 
 
 
b82113c
fc2da7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b82113c
fc2da7c
 
 
 
 
 
b82113c
fc2da7c
 
 
 
 
b82113c
 
fc2da7c
 
 
b82113c
fc2da7c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
"""
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)