Skip to content

Instantly share code, notes, and snippets.

@graylan0
Created August 16, 2023 15:07
Show Gist options
  • Save graylan0/49ea8c43dbc451be102166968750400a to your computer and use it in GitHub Desktop.
Save graylan0/49ea8c43dbc451be102166968750400a to your computer and use it in GitHub Desktop.
QML parking detection
import pennylane as qml
import sqlite3
import time
import openai
import json
from google.cloud import vision_v1
from google.cloud.vision_v1 import types
from pennylane import numpy as np
import cv2
# Quantum Language Model
class QuantumLanguageModel:
def __init__(self, num_qubits):
self.num_qubits = num_qubits
self.dev = qml.device('default.qubit', wires=self.num_qubits)
def quantum_layer(self, params):
for i in range(self.num_qubits):
qml.RY(params[i], wires=i)
for i in range(self.num_qubits - 1):
qml.CNOT(wires=[i, i+1])
def quantum_model(self, params):
for _ in range(len(params)):
self.quantum_layer(params)
# Database Manager
class DatabaseManager:
def __init__(self, db_name):
self.conn = sqlite3.connect(db_name)
self.cursor = self.conn.cursor()
def create_tables(self):
self.cursor.execute("""
CREATE TABLE IF NOT EXISTS illegal_parking_signs (
location TEXT,
sign_details TEXT
)
""")
self.cursor.execute("""
CREATE TABLE IF NOT EXISTS illegal_parking_log (
license_plate TEXT,
location TEXT,
timestamp TEXT,
tag_status TEXT
)
""")
self.conn.commit()
def insert_illegal_parking(self, license_plate, location, timestamp, tag_status):
self.cursor.execute("INSERT INTO illegal_parking_log (license_plate, location, timestamp, tag_status) VALUES (?, ?, ?, ?)", (license_plate, location, timestamp, tag_status))
self.conn.commit()
def get_last_illegal_parkings(self, count=5):
self.cursor.execute("SELECT license_plate, location, timestamp FROM illegal_parking_log ORDER BY ROWID DESC LIMIT ?", (count,))
return self.cursor.fetchall()
def close(self):
self.conn.close()
# Illegal Parking Detector
class IllegalParkingDetector:
def __init__(self, db_name="parking.db"):
self.qml_model = QuantumLanguageModel(2)
self.db_manager = DatabaseManager(db_name)
self.db_manager.create_tables()
self.client = vision_v1.ImageAnnotatorClient()
def extract_license_plate(self, image_path):
with open(image_path, 'rb') as image_file:
content = image_file.read()
image = types.Image(content=content)
response = self.client.text_detection(image=image)
texts = response.text_annotations
license_plate = texts[0].description if texts else None
return license_plate
def map_license_plate_to_qml_parameters(self, license_plate):
prompt = f"Map the license plate '{license_plate}' to Quantum Language Model parameters."
system_message = {'role': 'system', 'content': 'Map the license plate to QML parameters.'}
response = openai.ChatCompletion.create(
model='gpt-3.5-turbo',
messages=[system_message, {'role': 'user', 'content': prompt}],
)
user_reply = response['choices'][0]['message']['content']
params = json.loads(user_reply).get("parameters", [])
return [float(val) for val in params]
def encode_parking_info_into_qml(self, parking_params):
np.random.seed(42)
@qml.qnode(self.qml_model.dev)
def circuit(params):
self.qml_model.quantum_model(params)
return [qml.expval(qml.PauliZ(wires=i)) for i in range(self.qml_model.num_qubits)]
return circuit(parking_params)
def check_active_tag_stickers(self, license_plate):
prompt = f"Check if the license plate '{license_plate}' has active tag stickers."
system_message = {'role': 'system', 'content': 'Check for active tag stickers.'}
response = openai.ChatCompletion.create(
model='gpt-3.5-turbo',
messages=[system_message, {'role': 'user', 'content': prompt}],
)
user_reply = response['choices'][0]['message']['content']
return user_reply
def detect_illegal_parking(self, input_image):
location = self.get_current_location()
location_str = f"{location[0]}, {location[1]}"
timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
license_plate = self.extract_license_plate(input_image)
if license_plate:
parking_params = self.map_license_plate_to_qml_parameters(license_plate)
qml_results = self.encode_parking_info_into_qml(parking_params)
legal_score, illegal_score = qml_results
tag_status = self.check_active_tag_stickers(license_plate)
if illegal_score > legal_score:
self.db_manager.insert_illegal_parking(license_plate, location_str, timestamp, tag_status)
return "Illegal Parking Detected"
else:
return "Legal Parking"
else:
return "License Plate Not Found"
# TUI Interface
class ParkingTUI:
def __init__(self, detector):
self.detector = detector
self.camera = cv2.VideoCapture(0)
def main_menu(self):
while True:
print("\nIllegal Parking Detector")
print("1. Detect Illegal Parking")
print("2. View Last 5 Illegally Parked Vehicles")
print("3. Exit")
choice = input("Please choose an option (1-3): ")
if choice == '1':
self.detect_parking()
elif choice == '2':
self.view_last_parkings()
elif choice == '3':
print("Exiting...")
break
else:
print("Invalid choice. Please try again.")
def detect_parking(self):
print("Detecting illegal parking...")
ret, frame = self.camera.read()
if ret:
image_path = "temp_image.jpg"
cv2.imwrite(image_path, frame)
result = self.detector.detect_illegal_parking(image_path)
print("Result:", result)
else:
print("Error: Unable to capture image from camera.")
def view_last_parkings(self):
print("\nLast 5 Illegally Parked Vehicles:")
last_parkings = self.detector.db_manager.get_last_illegal_parkings()
for parking in last_parkings:
print(f"License Plate: {parking[0]}, Location: {parking[1]}, Time: {parking[2]}")
# Main function
def main():
detector = IllegalParkingDetector()
tui = ParkingTUI(detector)
tui.main_menu()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment