Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,82 +2,149 @@ import gradio as gr
|
|
| 2 |
import json
|
| 3 |
import spaces
|
| 4 |
import torch
|
| 5 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 6 |
from peft import PeftModel
|
| 7 |
|
| 8 |
# ββ Load model once at startup ββββββββββββββββββββββββββββββ
|
| 9 |
BASE_MODEL = "Qwen/Qwen2.5-1.5B-Instruct"
|
| 10 |
-
LORA_MODEL = "suneeldk/json-extract"
|
| 11 |
|
| 12 |
tokenizer = AutoTokenizer.from_pretrained(LORA_MODEL)
|
| 13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
base_model = AutoModelForCausalLM.from_pretrained(
|
| 15 |
BASE_MODEL,
|
| 16 |
-
|
| 17 |
device_map="auto",
|
| 18 |
)
|
|
|
|
| 19 |
model = PeftModel.from_pretrained(base_model, LORA_MODEL)
|
|
|
|
| 20 |
model.eval()
|
| 21 |
|
| 22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
# ββ Inference function ββββββββββββββββββββββββββββββββββββββ
|
| 24 |
@spaces.GPU
|
| 25 |
-
def extract(text,
|
| 26 |
if not text.strip():
|
| 27 |
-
return "
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
|
|
|
|
|
|
| 37 |
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
|
| 38 |
|
| 39 |
with torch.no_grad():
|
| 40 |
outputs = model.generate(
|
| 41 |
**inputs,
|
| 42 |
-
max_new_tokens=
|
| 43 |
-
|
| 44 |
-
do_sample=True,
|
| 45 |
pad_token_id=tokenizer.eos_token_id,
|
| 46 |
)
|
| 47 |
|
| 48 |
-
|
| 49 |
-
|
|
|
|
| 50 |
|
| 51 |
try:
|
| 52 |
parsed = json.loads(output_part)
|
| 53 |
-
return json.dumps(parsed, indent=2, ensure_ascii=False)
|
| 54 |
except json.JSONDecodeError:
|
| 55 |
-
return output_part
|
| 56 |
|
| 57 |
|
| 58 |
# ββ Example inputs ββββββββββββββββββββββββββββββββββββββββββ
|
| 59 |
examples = [
|
| 60 |
-
[
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
],
|
| 64 |
-
[
|
| 65 |
-
|
| 66 |
-
'{"person": "string", "time": "string", "topic": "string", "budget": "number|null"}',
|
| 67 |
-
],
|
| 68 |
-
[
|
| 69 |
-
"Bought 3 kg of rice from Krishna Stores for 250 rupees on March 10",
|
| 70 |
-
'{"item": "string", "quantity": "string", "store": "string", "amount": "number", "date": "ISO date|null"}',
|
| 71 |
-
],
|
| 72 |
]
|
| 73 |
|
| 74 |
# ββ Gradio UI βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 75 |
-
with gr.Blocks(title="json-extract"
|
| 76 |
gr.Markdown(
|
| 77 |
"""
|
| 78 |
# json-extract
|
| 79 |
Extract structured JSON from natural language text.
|
| 80 |
-
|
|
|
|
| 81 |
"""
|
| 82 |
)
|
| 83 |
|
|
@@ -88,22 +155,25 @@ with gr.Blocks(title="json-extract", theme=gr.themes.Soft()) as demo:
|
|
| 88 |
placeholder="e.g. Paid 500 to Ravi for lunch on Jan 5",
|
| 89 |
lines=3,
|
| 90 |
)
|
| 91 |
-
schema_input = gr.Textbox(
|
| 92 |
-
label="JSON Schema",
|
| 93 |
-
placeholder='e.g. {"amount": "number", "person": "string|null"}',
|
| 94 |
-
lines=3,
|
| 95 |
-
)
|
| 96 |
btn = gr.Button("Extract", variant="primary")
|
| 97 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
with gr.Column():
|
| 99 |
output = gr.Textbox(label="Extracted JSON", lines=10)
|
|
|
|
| 100 |
|
| 101 |
gr.Examples(
|
| 102 |
examples=examples,
|
| 103 |
-
inputs=[text_input
|
| 104 |
)
|
| 105 |
|
| 106 |
-
btn.click(fn=extract, inputs=[text_input, schema_input], outputs=output)
|
| 107 |
-
text_input.submit(fn=extract, inputs=[text_input, schema_input], outputs=output)
|
| 108 |
|
| 109 |
demo.launch()
|
|
|
|
| 2 |
import json
|
| 3 |
import spaces
|
| 4 |
import torch
|
| 5 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
|
| 6 |
from peft import PeftModel
|
| 7 |
|
| 8 |
# ββ Load model once at startup ββββββββββββββββββββββββββββββ
|
| 9 |
BASE_MODEL = "Qwen/Qwen2.5-1.5B-Instruct"
|
| 10 |
+
LORA_MODEL = "suneeldk/json-extract"
|
| 11 |
|
| 12 |
tokenizer = AutoTokenizer.from_pretrained(LORA_MODEL)
|
| 13 |
|
| 14 |
+
# Load in 4-bit for faster inference
|
| 15 |
+
bnb_config = BitsAndBytesConfig(
|
| 16 |
+
load_in_4bit=True,
|
| 17 |
+
bnb_4bit_quant_type="nf4",
|
| 18 |
+
bnb_4bit_compute_dtype=torch.float16,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
base_model = AutoModelForCausalLM.from_pretrained(
|
| 22 |
BASE_MODEL,
|
| 23 |
+
quantization_config=bnb_config,
|
| 24 |
device_map="auto",
|
| 25 |
)
|
| 26 |
+
|
| 27 |
model = PeftModel.from_pretrained(base_model, LORA_MODEL)
|
| 28 |
+
model = model.merge_and_unload() # Merge LoRA into base β removes adapter overhead
|
| 29 |
model.eval()
|
| 30 |
|
| 31 |
|
| 32 |
+
# ββ Auto-detect schema from text ββββββββββββββββββββββββββββ
|
| 33 |
+
def auto_schema(text):
|
| 34 |
+
text_lower = text.lower()
|
| 35 |
+
schema = {}
|
| 36 |
+
|
| 37 |
+
money_keywords = ["paid", "sent", "received", "cost", "price", "rupees", "rs",
|
| 38 |
+
"βΉ", "$", "bought", "sold", "charged", "fee", "salary",
|
| 39 |
+
"budget", "owes", "owe", "lent", "borrowed", "fare", "rent"]
|
| 40 |
+
if any(k in text_lower for k in money_keywords) or any(c.isdigit() for c in text):
|
| 41 |
+
schema["amount"] = "number|null"
|
| 42 |
+
|
| 43 |
+
person_keywords = ["to", "from", "with", "for", "by", "told", "asked",
|
| 44 |
+
"met", "called", "emailed", "messaged", "owes", "owe"]
|
| 45 |
+
if any(k in text_lower for k in person_keywords):
|
| 46 |
+
schema["person"] = "string|null"
|
| 47 |
+
|
| 48 |
+
date_keywords = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug",
|
| 49 |
+
"sep", "oct", "nov", "dec", "monday", "tuesday", "wednesday",
|
| 50 |
+
"thursday", "friday", "saturday", "sunday", "today", "tomorrow",
|
| 51 |
+
"yesterday", "morning", "evening", "night", "on", "at", "pm", "am"]
|
| 52 |
+
if any(k in text_lower for k in date_keywords):
|
| 53 |
+
schema["date"] = "ISO date|null"
|
| 54 |
+
if any(k in text_lower for k in ["pm", "am", "morning", "evening", "night", "at"]):
|
| 55 |
+
schema["time"] = "string|null"
|
| 56 |
+
|
| 57 |
+
item_keywords = ["bought", "ordered", "purchased", "delivered", "shipped",
|
| 58 |
+
"kg", "litre", "pieces", "items", "pack", "bottle"]
|
| 59 |
+
if any(k in text_lower for k in item_keywords):
|
| 60 |
+
schema["item"] = "string|null"
|
| 61 |
+
schema["quantity"] = "string|null"
|
| 62 |
+
|
| 63 |
+
location_keywords = ["from", "to", "at", "in", "store", "shop", "restaurant",
|
| 64 |
+
"station", "airport", "hotel", "office", "train", "flight", "bus"]
|
| 65 |
+
if any(k in text_lower for k in location_keywords):
|
| 66 |
+
schema["location"] = "string|null"
|
| 67 |
+
|
| 68 |
+
travel_keywords = ["train", "flight", "bus", "booked", "ticket", "pnr",
|
| 69 |
+
"travel", "trip", "journey"]
|
| 70 |
+
if any(k in text_lower for k in travel_keywords):
|
| 71 |
+
schema["from_location"] = "string|null"
|
| 72 |
+
schema["to_location"] = "string|null"
|
| 73 |
+
schema.pop("location", None)
|
| 74 |
+
|
| 75 |
+
meeting_keywords = ["meeting", "call", "discuss", "review", "presentation",
|
| 76 |
+
"interview", "appointment", "schedule"]
|
| 77 |
+
if any(k in text_lower for k in meeting_keywords):
|
| 78 |
+
schema["topic"] = "string|null"
|
| 79 |
+
|
| 80 |
+
schema["note"] = "string|null"
|
| 81 |
+
|
| 82 |
+
if len(schema) <= 1:
|
| 83 |
+
schema = {
|
| 84 |
+
"amount": "number|null",
|
| 85 |
+
"person": "string|null",
|
| 86 |
+
"date": "ISO date|null",
|
| 87 |
+
"note": "string|null",
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
return schema
|
| 91 |
+
|
| 92 |
+
|
| 93 |
# ββ Inference function ββββββββββββββββββββββββββββββββββββββ
|
| 94 |
@spaces.GPU
|
| 95 |
+
def extract(text, custom_schema):
|
| 96 |
if not text.strip():
|
| 97 |
+
return "", ""
|
| 98 |
+
|
| 99 |
+
if custom_schema and custom_schema.strip():
|
| 100 |
+
try:
|
| 101 |
+
schema = json.loads(custom_schema)
|
| 102 |
+
except json.JSONDecodeError:
|
| 103 |
+
return "Invalid JSON schema.", ""
|
| 104 |
+
else:
|
| 105 |
+
schema = auto_schema(text)
|
| 106 |
+
|
| 107 |
+
schema_str = json.dumps(schema)
|
| 108 |
+
prompt = f"### Input: {text}\n### Schema: {schema_str}\n### Output:"
|
| 109 |
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
|
| 110 |
|
| 111 |
with torch.no_grad():
|
| 112 |
outputs = model.generate(
|
| 113 |
**inputs,
|
| 114 |
+
max_new_tokens=128, # JSON output is short, no need for 512
|
| 115 |
+
do_sample=False, # Greedy decoding β faster than sampling
|
|
|
|
| 116 |
pad_token_id=tokenizer.eos_token_id,
|
| 117 |
)
|
| 118 |
|
| 119 |
+
# Decode only the new tokens, skip the prompt
|
| 120 |
+
new_tokens = outputs[0][inputs["input_ids"].shape[1]:]
|
| 121 |
+
output_part = tokenizer.decode(new_tokens, skip_special_tokens=True).strip()
|
| 122 |
|
| 123 |
try:
|
| 124 |
parsed = json.loads(output_part)
|
| 125 |
+
return json.dumps(parsed, indent=2, ensure_ascii=False), json.dumps(schema, indent=2)
|
| 126 |
except json.JSONDecodeError:
|
| 127 |
+
return output_part, json.dumps(schema, indent=2)
|
| 128 |
|
| 129 |
|
| 130 |
# ββ Example inputs ββββββββββββββββββββββββββββββββββββββββββ
|
| 131 |
examples = [
|
| 132 |
+
["Paid 500 to Ravi for lunch on Jan 5"],
|
| 133 |
+
["Meeting with Sarah at 3pm tomorrow to discuss the project budget of $10,000"],
|
| 134 |
+
["Bought 3 kg of rice from Krishna Stores for 250 rupees on March 10"],
|
| 135 |
+
["Booked a train from Chennai to Bangalore on April 10 for 750 rupees"],
|
| 136 |
+
["Ravi owes me 300 for last week's dinner"],
|
| 137 |
+
["Ordered 2 pizzas and 1 coke from Dominos for 850 rupees"],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
]
|
| 139 |
|
| 140 |
# ββ Gradio UI βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 141 |
+
with gr.Blocks(title="json-extract") as demo:
|
| 142 |
gr.Markdown(
|
| 143 |
"""
|
| 144 |
# json-extract
|
| 145 |
Extract structured JSON from natural language text.
|
| 146 |
+
|
| 147 |
+
Just type a sentence β the model auto-detects the right schema and extracts clean JSON.
|
| 148 |
"""
|
| 149 |
)
|
| 150 |
|
|
|
|
| 155 |
placeholder="e.g. Paid 500 to Ravi for lunch on Jan 5",
|
| 156 |
lines=3,
|
| 157 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
btn = gr.Button("Extract", variant="primary")
|
| 159 |
|
| 160 |
+
with gr.Accordion("Advanced: Custom Schema (optional)", open=False):
|
| 161 |
+
schema_input = gr.Textbox(
|
| 162 |
+
label="Custom JSON Schema",
|
| 163 |
+
placeholder='Leave empty for auto-detect, or enter e.g. {"amount": "number", "person": "string|null"}',
|
| 164 |
+
lines=3,
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
with gr.Column():
|
| 168 |
output = gr.Textbox(label="Extracted JSON", lines=10)
|
| 169 |
+
detected_schema = gr.Textbox(label="Schema Used", lines=5)
|
| 170 |
|
| 171 |
gr.Examples(
|
| 172 |
examples=examples,
|
| 173 |
+
inputs=[text_input],
|
| 174 |
)
|
| 175 |
|
| 176 |
+
btn.click(fn=extract, inputs=[text_input, schema_input], outputs=[output, detected_schema])
|
| 177 |
+
text_input.submit(fn=extract, inputs=[text_input, schema_input], outputs=[output, detected_schema])
|
| 178 |
|
| 179 |
demo.launch()
|