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4 |
+
import sys
|
| 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 |
+
logging.basicConfig(
|
| 18 |
+
level=logging.INFO,
|
| 19 |
+
format="%(asctime)s | %(levelname)s | %(message)s",
|
| 20 |
+
handlers=[logging.StreamHandler(sys.stdout)],
|
| 21 |
+
)
|
| 22 |
+
logger = logging.getLogger("prompt_json_extractor")
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def system_prompt() -> str:
|
| 26 |
+
return """
|
| 27 |
+
You convert messy natural language into clean structured JSON.
|
| 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 |
+
Rules:
|
| 50 |
+
1. task_type must be a short string
|
| 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 |
+
def extract_json(user_text: str) -> dict:
|
| 64 |
+
request_id = str(uuid.uuid4())[:8]
|
| 65 |
+
start = time.time()
|
| 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 |
+
response = client.chat_completion(
|
| 90 |
+
model=MODEL,
|
| 91 |
+
messages=messages,
|
| 92 |
+
max_tokens=MAX_TOKENS,
|
| 93 |
+
temperature=TEMPERATURE,
|
| 94 |
+
top_p=TOP_P,
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
elapsed = time.time() - start
|
| 98 |
+
logger.info("REQUEST %s | response received in %.2fs", request_id, elapsed)
|
| 99 |
+
|
| 100 |
+
content = response.choices[0].message.content
|
| 101 |
+
logger.info("REQUEST %s | raw_response_preview=%r", request_id, content[:500])
|
| 102 |
+
|
| 103 |
+
try:
|
| 104 |
+
parsed = json.loads(content)
|
| 105 |
+
except json.JSONDecodeError as e:
|
| 106 |
+
logger.exception("REQUEST %s | JSON parsing failed", request_id)
|
| 107 |
+
raise RuntimeError("Model returned invalid JSON. Check Space logs.") from e
|
| 108 |
+
|
| 109 |
+
parsed["_meta"] = {
|
| 110 |
+
"request_id": request_id,
|
| 111 |
+
"model": MODEL,
|
| 112 |
+
"elapsed_seconds": round(elapsed, 2),
|
| 113 |
+
"mode": "hosted_llm",
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
logger.info("REQUEST %s | JSON parsed successfully", request_id)
|
| 117 |
+
return parsed
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def pretty_markdown(data: dict) -> str:
|
| 121 |
+
def bullet_list(items):
|
| 122 |
+
if not items:
|
| 123 |
+
return "- None"
|
| 124 |
+
return "\n".join(f"- {item}" for item in items)
|
| 125 |
+
|
| 126 |
+
extracted = data.get("extracted_fields", {})
|
| 127 |
+
schema = data.get("suggested_schema", {})
|
| 128 |
+
meta = data.get("_meta", {})
|
| 129 |
+
|
| 130 |
+
return f"""
|
| 131 |
+
# Structured Extraction
|
| 132 |
+
|
| 133 |
+
## Task Type
|
| 134 |
+
`{data.get("task_type", "")}`
|
| 135 |
+
|
| 136 |
+
## Summary
|
| 137 |
+
{data.get("summary", "")}
|
| 138 |
+
|
| 139 |
+
## Confidence
|
| 140 |
+
**{data.get("confidence", "")}**
|
| 141 |
+
|
| 142 |
+
## Constraints
|
| 143 |
+
{bullet_list(data.get("constraints", []))}
|
| 144 |
+
|
| 145 |
+
## Assumptions
|
| 146 |
+
{bullet_list(data.get("assumptions", []))}
|
| 147 |
+
|
| 148 |
+
## Missing Information
|
| 149 |
+
{bullet_list(data.get("missing_information", []))}
|
| 150 |
+
|
| 151 |
+
## Extracted Fields
|
| 152 |
+
```json
|
| 153 |
+
{json.dumps(extracted, indent=2)}
|