- Base de datos SQLite con información de vehículos - Dashboard web con Flask y Bootstrap - Scripts de web scraping para RockAuto - Interfaz CLI para consultas - Documentación completa del proyecto Incluye: - 12 marcas de vehículos - 10,923 modelos - 10,919 especificaciones de motores - 12,075 combinaciones modelo-año-motor
193 lines
6.6 KiB
Python
193 lines
6.6 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Simple Query Interface for Vehicle Database
|
|
Provides a command-line interface for searching the vehicle database
|
|
"""
|
|
|
|
import sqlite3
|
|
from typing import List, Tuple
|
|
|
|
|
|
class VehicleQueryInterface:
|
|
def __init__(self, db_path: str = "vehicle_database.db"):
|
|
self.db_path = db_path
|
|
|
|
def search_vehicles(self, brand: str = None, model: str = None, year: int = None,
|
|
engine: str = None, limit: int = 50) -> List[Tuple]:
|
|
"""Search for vehicles based on various criteria"""
|
|
conn = sqlite3.connect(self.db_path)
|
|
conn.row_factory = sqlite3.Row # Enable column access by name
|
|
cursor = conn.cursor()
|
|
|
|
query = """
|
|
SELECT
|
|
b.name AS brand,
|
|
m.name AS model,
|
|
y.year,
|
|
e.name AS engine,
|
|
e.displacement_cc,
|
|
e.cylinders,
|
|
e.fuel_type,
|
|
e.power_hp,
|
|
mye.trim_level,
|
|
mye.drivetrain,
|
|
mye.transmission
|
|
FROM model_year_engine mye
|
|
JOIN models m ON mye.model_id = m.id
|
|
JOIN brands b ON m.brand_id = b.id
|
|
JOIN years y ON mye.year_id = y.id
|
|
JOIN engines e ON mye.engine_id = e.id
|
|
WHERE 1=1
|
|
"""
|
|
|
|
params = []
|
|
if brand:
|
|
query += " AND b.name LIKE ?"
|
|
params.append(f"%{brand}%")
|
|
if model:
|
|
query += " AND m.name LIKE ?"
|
|
params.append(f"%{model}%")
|
|
if year:
|
|
query += " AND y.year = ?"
|
|
params.append(year)
|
|
if engine:
|
|
query += " AND e.name LIKE ?"
|
|
params.append(f"%{engine}%")
|
|
|
|
query += f" ORDER BY b.name, m.name, y.year LIMIT {limit}"
|
|
|
|
cursor.execute(query, params)
|
|
results = cursor.fetchall()
|
|
conn.close()
|
|
|
|
return results
|
|
|
|
def get_all_brands(self) -> List[Tuple]:
|
|
"""Get a list of all brands in the database"""
|
|
conn = sqlite3.connect(self.db_path)
|
|
conn.row_factory = sqlite3.Row
|
|
cursor = conn.cursor()
|
|
|
|
cursor.execute("SELECT DISTINCT name FROM brands ORDER BY name")
|
|
results = cursor.fetchall()
|
|
conn.close()
|
|
|
|
return [row[0] for row in results]
|
|
|
|
def get_models_by_brand(self, brand_name: str) -> List[Tuple]:
|
|
"""Get all models for a specific brand"""
|
|
conn = sqlite3.connect(self.db_path)
|
|
conn.row_factory = sqlite3.Row
|
|
cursor = conn.cursor()
|
|
|
|
cursor.execute("""
|
|
SELECT DISTINCT m.name
|
|
FROM models m
|
|
JOIN brands b ON m.brand_id = b.id
|
|
WHERE b.name = ?
|
|
ORDER BY m.name
|
|
""", (brand_name,))
|
|
results = cursor.fetchall()
|
|
conn.close()
|
|
|
|
return [row[0] for row in results]
|
|
|
|
def get_years_for_model(self, model_name: str) -> List[int]:
|
|
"""Get all years for a specific model"""
|
|
conn = sqlite3.connect(self.db_path)
|
|
conn.row_factory = sqlite3.Row
|
|
cursor = conn.cursor()
|
|
|
|
cursor.execute("""
|
|
SELECT DISTINCT y.year
|
|
FROM model_year_engine mye
|
|
JOIN models m ON mye.model_id = m.id
|
|
JOIN years y ON mye.year_id = y.id
|
|
WHERE m.name = ?
|
|
ORDER BY y.year
|
|
""", (model_name,))
|
|
results = cursor.fetchall()
|
|
conn.close()
|
|
|
|
return [row[0] for row in results]
|
|
|
|
|
|
def main():
|
|
interface = VehicleQueryInterface()
|
|
|
|
print("Vehicle Database Query Interface")
|
|
print("=================================")
|
|
|
|
while True:
|
|
print("\nOptions:")
|
|
print("1. Search vehicles")
|
|
print("2. List all brands")
|
|
print("3. List models for a brand")
|
|
print("4. List years for a model")
|
|
print("5. Exit")
|
|
|
|
choice = input("\nEnter your choice (1-5): ").strip()
|
|
|
|
if choice == "1":
|
|
print("\nSearch for vehicles:")
|
|
brand = input("Brand (optional): ").strip() or None
|
|
model = input("Model (optional): ").strip() or None
|
|
year_input = input("Year (optional): ").strip()
|
|
year = int(year_input) if year_input else None
|
|
engine = input("Engine (optional): ").strip() or None
|
|
|
|
results = interface.search_vehicles(brand=brand, model=model, year=year, engine=engine)
|
|
|
|
if results:
|
|
print(f"\nFound {len(results)} result(s):")
|
|
print("-" * 100)
|
|
for i, vehicle in enumerate(results, 1):
|
|
print(f"{i:2d}. {vehicle['year']} {vehicle['brand']} {vehicle['model']}")
|
|
print(f" Engine: {vehicle['engine']} ({vehicle['power_hp']} HP, {vehicle['displacement_cc']} cc)")
|
|
print(f" Trim: {vehicle['trim_level']}, Drivetrain: {vehicle['drivetrain']}, Transmission: {vehicle['transmission']}")
|
|
print()
|
|
else:
|
|
print("No vehicles found matching your criteria.")
|
|
|
|
elif choice == "2":
|
|
brands = interface.get_all_brands()
|
|
print(f"\nAll brands ({len(brands)}):")
|
|
for i, brand in enumerate(brands, 1):
|
|
print(f"{i:2d}. {brand}")
|
|
|
|
elif choice == "3":
|
|
brand = input("Enter brand name: ").strip()
|
|
if brand:
|
|
models = interface.get_models_by_brand(brand)
|
|
if models:
|
|
print(f"\nModels for {brand} ({len(models)}):")
|
|
for i, model in enumerate(models, 1):
|
|
print(f"{i:2d}. {model}")
|
|
else:
|
|
print(f"No models found for brand: {brand}")
|
|
else:
|
|
print("Please enter a brand name.")
|
|
|
|
elif choice == "4":
|
|
model = input("Enter model name: ").strip()
|
|
if model:
|
|
years = interface.get_years_for_model(model)
|
|
if years:
|
|
print(f"\nYears for {model} ({len(years)}):")
|
|
for i, year in enumerate(years, 1):
|
|
print(f"{i:2d}. {year}")
|
|
else:
|
|
print(f"No years found for model: {model}")
|
|
else:
|
|
print("Please enter a model name.")
|
|
|
|
elif choice == "5":
|
|
print("Thank you for using the Vehicle Database Query Interface!")
|
|
break
|
|
|
|
else:
|
|
print("Invalid choice. Please enter 1-5.")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |