File size: 16,353 Bytes
28372d0 6952bc9 28372d0 6952bc9 28372d0 6952bc9 28372d0 6952bc9 28372d0 6952bc9 28372d0 6952bc9 28372d0 6952bc9 28372d0 |
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 |
import gradio as gr
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
import warnings
warnings.filterwarnings("ignore")
class LlamaAddressCompletion:
def __init__(self):
self.model_name = "shiprocket-ai/open-llama-1b-address-completion"
self.model = None
self.tokenizer = None
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.load_model()
def load_model(self):
"""Load the Llama model and tokenizer"""
try:
print("Loading Llama 3.2-1B Address Completion model...")
self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)
# Load model with appropriate settings for the space
self.model = AutoModelForCausalLM.from_pretrained(
self.model_name,
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
device_map="auto" if torch.cuda.is_available() else None,
trust_remote_code=True
)
if not torch.cuda.is_available():
self.model = self.model.to(self.device)
self.model.eval()
print("β
Model loaded successfully!")
except Exception as e:
print(f"β Error loading model: {str(e)}")
raise e
def extract_address_components(self, address, max_new_tokens=150):
"""Extract address components using the model"""
if not address.strip():
return "Please provide an address to extract components from."
try:
# Format prompt for Llama 3.2-1B-Instruct
prompt = f"""<|begin_of_text|><|start_header_id|>user<|end_header_id|>
Extract address components from: {address}<|eot_id|><|start_header_id|>assistant<|end_header_id|>
"""
# Tokenize
inputs = self.tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512)
# Move inputs to the same device as the model
device = next(self.model.parameters()).device
inputs = {k: v.to(device) for k, v in inputs.items()}
# Generate
with torch.no_grad():
outputs = self.model.generate(
**inputs,
max_new_tokens=max_new_tokens,
temperature=0.1,
top_p=0.9,
do_sample=True,
pad_token_id=self.tokenizer.eos_token_id,
repetition_penalty=1.05
)
# Decode only the new tokens
input_length = inputs['input_ids'].shape[1]
generated_tokens = outputs[0][input_length:]
response = self.tokenizer.decode(generated_tokens, skip_special_tokens=True)
return response.strip()
except Exception as e:
return f"Error processing address: {str(e)}"
def complete_partial_address(self, partial_address, max_new_tokens=100):
"""Complete a partial address"""
if not partial_address.strip():
return "Please provide a partial address to complete."
try:
# Format prompt for address completion
prompt = f"""<|begin_of_text|><|start_header_id|>user<|end_header_id|>
Complete this partial address: {partial_address}<|eot_id|><|start_header_id|>assistant<|end_header_id|>
"""
# Tokenize
inputs = self.tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512)
# Move inputs to the same device as the model
device = next(self.model.parameters()).device
inputs = {k: v.to(device) for k, v in inputs.items()}
# Generate
with torch.no_grad():
outputs = self.model.generate(
**inputs,
max_new_tokens=max_new_tokens,
temperature=0.2,
top_p=0.9,
do_sample=True,
pad_token_id=self.tokenizer.eos_token_id,
repetition_penalty=1.05
)
# Decode only the new tokens
input_length = inputs['input_ids'].shape[1]
generated_tokens = outputs[0][input_length:]
response = self.tokenizer.decode(generated_tokens, skip_special_tokens=True)
return response.strip()
except Exception as e:
return f"Error completing address: {str(e)}"
def standardize_address(self, address, max_new_tokens=150):
"""Standardize an address format"""
if not address.strip():
return "Please provide an address to standardize."
try:
# Format prompt for address standardization
prompt = f"""<|begin_of_text|><|start_header_id|>user<|end_header_id|>
Standardize this address into proper format: {address}<|eot_id|><|start_header_id|>assistant<|end_header_id|>
"""
# Tokenize
inputs = self.tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512)
# Move inputs to the same device as the model
device = next(self.model.parameters()).device
inputs = {k: v.to(device) for k, v in inputs.items()}
# Generate
with torch.no_grad():
outputs = self.model.generate(
**inputs,
max_new_tokens=max_new_tokens,
temperature=0.1,
top_p=0.9,
do_sample=True,
pad_token_id=self.tokenizer.eos_token_id,
repetition_penalty=1.05
)
# Decode only the new tokens
input_length = inputs['input_ids'].shape[1]
generated_tokens = outputs[0][input_length:]
response = self.tokenizer.decode(generated_tokens, skip_special_tokens=True)
return response.strip()
except Exception as e:
return f"Error standardizing address: {str(e)}"
# Initialize the model
print("Initializing Llama Address Completion system...")
try:
llama_system = LlamaAddressCompletion()
print("System ready!")
except Exception as e:
print(f"Failed to initialize system: {e}")
llama_system = None
def extract_components_interface(address_text):
"""Interface function for component extraction"""
if llama_system is None:
return "β Model not loaded. Please check the logs."
result = llama_system.extract_address_components(address_text)
return f"**Input:** {address_text}\n\n**Extracted Components:**\n{result}"
def complete_address_interface(partial_address):
"""Interface function for address completion"""
if llama_system is None:
return "β Model not loaded. Please check the logs."
result = llama_system.complete_partial_address(partial_address)
return f"**Partial Address:** {partial_address}\n\n**Completed Address:**\n{result}\n\n*β οΈ Note: This feature has limited training data and results may vary in quality.*"
def standardize_address_interface(address_text):
"""Interface function for address standardization"""
if llama_system is None:
return "β Model not loaded. Please check the logs."
result = llama_system.standardize_address(address_text)
return f"**Original:** {address_text}\n\n**Standardized:**\n{result}\n\n*β οΈ Note: This feature has limited training data and results may vary in quality.*"
# Sample data
sample_addresses = [
"C-704, Gayatri Shivam, Thakur Complex, Kandivali East, 400101",
"Villa 141, Geown Oasis, V Kallahalli, Off Sarjapur, Bengaluru, Karnataka, 562125",
"E401 Supertech Icon Indrapam 201301 UP",
"Shop No 123, Sunshine Apartments, Andheri West, Mumbai, 400058",
"Flat 201, MG Road, Bangalore, Karnataka, 560001"
]
partial_addresses = [
"C-704, Gayatri Shivam, Thakur Complex",
"Villa 141, Geown Oasis, V Kallahalli",
"E401 Supertech Icon",
"Shop No 123, Sunshine Apartments",
"Flat 201, MG Road, Bangalore"
]
informal_addresses = [
"c704 gayatri shivam thakur complex kandivali e 400101",
"villa141 geown oasis vkallahalli off sarjapur blr kar 562125",
"e401 supertech icon indrapam up 201301",
"shop123 sunshine apts andheri w mumbai 400058"
]
# Create Gradio interface
with gr.Blocks(title="Llama Address Intelligence", theme=gr.themes.Soft()) as demo:
gr.Markdown("""
# π¦ Llama 3.2-1B Address Intelligence
Powered by a fine-tuned Llama 3.2-1B model specialized for Indian address processing.
**β Best Performance**: Entity extraction from complete addresses
**β οΈ Limited Performance**: Address completion and standardization (limited training data)
**Model:** [shiprocket-ai/open-llama-1b-address-completion](https://huggingface.co/shiprocket-ai/open-llama-1b-address-completion)
""")
with gr.Tab("π Extract Components"):
gr.Markdown("β **BEST PERFORMANCE** - Extract structured components from complete addresses")
with gr.Row():
with gr.Column(scale=1):
extract_input = gr.Textbox(
label="Enter Address",
placeholder="e.g., C-704, Gayatri Shivam, Thakur Complex, Kandivali East, 400101",
lines=3
)
extract_btn = gr.Button("π Extract Components", variant="primary")
gr.Markdown("### Sample Addresses:")
extract_samples = []
for addr in sample_addresses:
btn = gr.Button(addr, size="sm")
btn.click(fn=lambda x=addr: x, outputs=extract_input)
extract_samples.append(btn)
with gr.Column(scale=1):
extract_output = gr.Markdown(
value="Enter an address and click 'Extract Components' to see structured breakdown."
)
extract_btn.click(
fn=extract_components_interface,
inputs=extract_input,
outputs=extract_output
)
extract_input.submit(
fn=extract_components_interface,
inputs=extract_input,
outputs=extract_output
)
with gr.Tab("β¨ Complete Address"):
gr.Markdown("β οΈ **EXPERIMENTAL** - Complete partial addresses (limited training data - results may vary)")
with gr.Row():
with gr.Column(scale=1):
complete_input = gr.Textbox(
label="Enter Partial Address",
placeholder="e.g., C-704, Gayatri Shivam, Thakur Complex",
lines=3
)
complete_btn = gr.Button("π Complete Address", variant="primary")
gr.Markdown("### Sample Partial Addresses:")
complete_samples = []
for addr in partial_addresses:
btn = gr.Button(addr, size="sm")
btn.click(fn=lambda x=addr: x, outputs=complete_input)
complete_samples.append(btn)
with gr.Column(scale=1):
complete_output = gr.Markdown(
value="Enter a partial address and click 'Complete Address' to see the AI completion."
)
complete_btn.click(
fn=complete_address_interface,
inputs=complete_input,
outputs=complete_output
)
complete_input.submit(
fn=complete_address_interface,
inputs=complete_input,
outputs=complete_output
)
with gr.Tab("π Standardize Format"):
gr.Markdown("β οΈ **EXPERIMENTAL** - Convert informal addresses to standardized format (limited training data - results may vary)")
with gr.Row():
with gr.Column(scale=1):
standardize_input = gr.Textbox(
label="Enter Informal Address",
placeholder="e.g., c704 gayatri shivam thakur complex kandivali e 400101",
lines=3
)
standardize_btn = gr.Button("π Standardize Format", variant="primary")
gr.Markdown("### Sample Informal Addresses:")
standardize_samples = []
for addr in informal_addresses:
btn = gr.Button(addr, size="sm")
btn.click(fn=lambda x=addr: x, outputs=standardize_input)
standardize_samples.append(btn)
with gr.Column(scale=1):
standardize_output = gr.Markdown(
value="Enter an informal address and click 'Standardize Format' to see the cleaned version."
)
standardize_btn.click(
fn=standardize_address_interface,
inputs=standardize_input,
outputs=standardize_output
)
standardize_input.submit(
fn=standardize_address_interface,
inputs=standardize_input,
outputs=standardize_output
)
with gr.Tab("βΉοΈ Model Information"):
gr.Markdown("""
## π¦ About Llama 3.2-1B Address Completion
### Model Specifications
- **Base Model**: meta-llama/Llama-3.2-1B-Instruct
- **Parameters**: 1.24B parameters
- **Model Size**: ~2.47GB
- **Architecture**: Causal Language Model (Autoregressive)
- **Max Context**: 131,072 tokens
- **Precision**: FP16 for GPU, FP32 for CPU
### Key Features
- **Lightweight**: Only 1B parameters for fast inference
- **Specialized**: Fine-tuned specifically for Indian addresses
- **Versatile**: Handles extraction, completion, and standardization
- **Efficient**: Optimized for real-time applications
- **Context-Aware**: Understands relationships between address components
### Supported Address Components
- **Building Names**: Apartments, complexes, towers, malls
- **Localities**: Areas, neighborhoods, sectors
- **Pincodes**: 6-digit Indian postal codes
- **Cities**: Major and minor Indian cities
- **States**: All Indian states and union territories
- **Sub-localities**: Sectors, phases, blocks
- **Road Names**: Streets, lanes, main roads
- **Landmarks**: Notable reference points
### Performance Notes
- **β Entity Extraction**: Excellent performance - primary use case
- **β οΈ Address Completion**: Limited training data - experimental feature
- **β οΈ Format Standardization**: Limited training data - experimental feature
**Recommendation**: Use this model primarily for address component extraction.
### Use Cases
- **E-commerce**: Auto-complete checkout addresses
- **Forms**: Intelligent address suggestions
- **Data Cleaning**: Standardize legacy address databases
- **Mobile Apps**: On-device address processing
- **APIs**: Real-time address validation services
### Performance Tips
- Use lower temperatures (0.1-0.3) for factual outputs
- Keep prompts under 512 tokens for optimal speed
- Process in batches for high-throughput scenarios
- Works best with Llama chat format prompts
""")
gr.Markdown("""
---
**Powered by:** [Llama 3.2-1B Address Completion](https://huggingface.co/shiprocket-ai/open-llama-1b-address-completion) |
**License:** Apache 2.0 |
**Developed by:** Shiprocket AI Team
This model demonstrates the power of lightweight LLMs for specialized address intelligence tasks.
""")
if __name__ == "__main__":
demo.launch() |