{ "cells": [ { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "#!pip install -r requirements.txt" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import warnings\n", "warnings.filterwarnings(\"ignore\")\n", "\n", "import os \n", "import numpy as np\n", "import pinecone\n", "from PyPDF2 import PdfFileReader, PdfReader # To read the PDF file\n", "import langchain_core.documents.base as doc_base\n", "#from langchain.embeddings import OpenAIEmbeddings # To convert the text chunks into tokens (or vectors or embeddings)\n", "from langchain_google_genai import GoogleGenerativeAIEmbeddings # To convert the text chunks into tokens (or vectors or embeddings)\n", "from langchain.vectorstores import Pinecone # To store the vectors in Pinecode Vector DB\n", "from langchain_pinecone import PineconeVectorStore # To retive data from existing pinecone indexes\n", "#from langchain.llms import OpenAI # The LLm model used\n", "# from langchain.chat_models import ChatOpenAI\n", "# import openapi\n", "from langchain_google_genai import ChatGoogleGenerativeAI # The LLm model used to build the application\n", "import google.generativeai as genai # Google's genai library to configure Gemini " ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n" ] } ], "source": [ "# load the API keys from .evn and configure Google GenAI\n", "\n", "from dotenv import load_dotenv\n", "print(load_dotenv())\n", "genai.configure(api_key=os.getenv(\"GOOGLE_API_KEY\"))" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "24\n" ] }, { "data": { "text/plain": [ "[Document(page_content=\"The following te xts outlines Colorado's driving regulations, including requirements for \\nobtaining a driver's license, notifying the DMV of changes, and details about written and \\ndriving tests. It also provides guidance on maneuvers and behaviours evaluated during the \\ndriving skills test, emphasizing adherence to safety and legal driving practices. \\nAnyone who operates a motor vehicle, motor -driven cycle or moped on Colorado’s public \\nstreets and highways must be 16 or older and have a valid driver license. If you are a resident of \\nColorado (for example if you own or operate a business in Colorado or h ave resided within the \\nstate continuously for 90 days or have gainful employment within this state), you must get a \\nColorado driver license within 30 days of becoming a resident unless you are serving on active \\nduty in the U.S. military, the dependent of a n active duty military service member or residing in \\nColorado for the principal purpose of furthering your education. If you have a change to your \\naddress or name you must notify the Division of Motor Vehicles within 30 days. Identification \\nrequirements fo r U.S. citizens and permanent residents can be found at \\nDMV.Colorado.gov/documents. Driving Knowledge Tests (written tests): This test covers driving \\nknowledge and safety. The test questions cover the contents of this handbook including road \\nsigns, driving under the influence, driving rules, safety rules and legal items. Practice quizzes \\nare available online and through the myColorado app. Note: Written tests are not given within 30 \\nminutes of an office’s scheduled closing time. Please plan your visit with this in mind. Name & \\nAddress Changes You have 30 days to notify the DMV of a name or address change. Instruction \\npermits: After passing a written test, you are eligible for an instruction permit. An instruction \\npermit allows limited driving privileges for people learning to drive. When you are driving with an \\ninstruction permit, you must have a person who is 21 years or older who has a valid Colorado \\nlicense in the front passenger seat. Driving Skills Test (drive test): This test covers practical \\ndriving sk ills and abilities. This is the most important part of the licensing process because it \\nallows you to show that you can drive safely. You cannot schedule a drive test at a State driver \\nlicense office at this time. However, this could change and you are enc ouraged to visit the DMV \\nwebsite to see if we are currently offering drive tests. Some county\\x02operated offices offer drive \\ntests, please refer to your county website for updated information on testing. Drive tests are \\nprimarily being given by Certified Com mercial Driving Schools. A link to the current list of \\nschools conducting drive tests can be found here (or at the website listed below). More \\ninformation can also be found on the DMV website DMV.Colorado.gov/drivereducation. When \\nyou take the drive test a t a state-approved, certified commercial driving school, the school may \\nprovide a vehicle for you to drive or it may require you to provide a vehicle that has current \\ninsurance and registration. Regardless of who provides the vehicle, the examiner will che ck the \\nvehicle for safety including brake lights, turn signals, seat belts, the windshield and tires. \\nExaminers will also check whether the vehicle’s doors and windows open from inside the \\nautomobile. For safety reasons, only the driver and the examiner ar e allowed in the vehicle \\nduring the test. Interpreters/Translators, family, friends or pets are not allowed. Remove \\nweapons from your vehicle before taking the drive test. Turn off any electronic devices in your \\nvehicle, including the radio and your cell p hone. Remove objects from the dashboard and the \\nrearview mirror. If you fail the drive test, you must wait until the next business day before \\nretaking the test. The drive test measures your skill and knowledge of legal and safe driving \\npractices. You will not be asked to do anything illegal. You may ask the examiner questions \\nbefore the test begins. After that, any unnecessary talking will only interfere with the test. You \\nwill be scored during the entire test. The drive test will be administered using guid elines from \\nthe American Association of Motor Vehicle Administrators (AAMVA). The skills measured will be \\nan assessment of all three of the following categories: Perceptual: The ability to perceive characteristics of the many highway traffic environments in a way that permits safe vehicle \\noperation, e.g. judging gaps or identifying hazards. Motor: The ability to manipulate controls in \\norder to maneuver the vehicle, e.g. ability to rotate the steering wheel in relation to the motion of \\nthe vehicle and intended path when turning a corner. Attentional: The ability to focus and shift \\nattention, e.g. to monitor traffic ahead and the side in a merge. Your drive test score will be \\nbased upon how well you per form the following maneuvers: ● Left and right turns ● Stopping at \\nintersections ● Through intersections ● Lane changes in traffic ● General driving behavior ● \\nMerging into and leaving traffic Specific maneuvers have grading factors that are associated \\nwith the performance requirements. These are: Lane selection: Enter/exit traffic from the proper \\nlane, approach intersections in the proper lane, end the maneuver in the proper lane. Lane \\nmanagement: Remain entirely within the turning lane, keep both hands on the wheel. Use \\napproved method of steering control (hand -over-hand or push -pull\\x02slide). Choose the correct \\nportion of the lane for making your turn (when turning right, always turn from the right\\x02most \\nportion of your lane or when turning left, always turn Colorado Driver Handbook 2 from the left -\\nmost portion of your lane). After completing the turn, ensure the vehicle is centered in the \\nappropriate lane. Start/finish the turn in the proper lane, do not drive over lane markings or over \\ncurbs. Turn Signals: Turn signal is turned on continuously 100 feet before turning or changing \\nlanes in urban areas and 200 feet before turning or changing lanes on 4 -lane highways. Turn \\nsignal is cancelled within 3 seconds of turning or changing lanes. Speed control: Smooth \\ndeceleration does not hold up traffic, adjust speed to react to traffic or conditions, maintain \\nsteady speed during lane change, approach intersection at a speed that allows the turn to be \\nmade without stopping or braking during the turn. Stopping: Come to a complete stop, no \\nforward motion of the vehicle. Do not encroach over the stop line and, crosswalk; keep the \\nvehicle’s wheels pointed straight ahead while stopped, do not turn the wheels until beginning to \\nmake the turn and maintain an adequate distance between vehicles (If you can see the rear \\nwheels touching the ground of the vehicle in front of you, you are at an adequate distance). \\nAcceleration: Accelerates smoothly without jerking, doesn’t lug the engine, coast, impede \\ntraffic, clash gears or stall t he vehicle. Searching: Observes the traffic environment, looks over \\nshoulder before changing lanes, uses mirrors, scans for traffic when approaching an \\nintersection, looks left, right, left before entering intersections, looks behind after each turn. \\nDuring the test, use of safety -critical technologies such as back -up cameras, and blind spot \\nand lane departure warnings are allowed but do not take the place of physical searching skills. \\nGeneral driving behavior: Steering, braking, acceleration, searching, la ne usage, and obeying all \\ntraffic laws, signs and signals. \\n \"),\n", " Document(page_content='The following text delineates regulations and procedures for minors obtaining driver \\npermits and licenses in Colorado, including requirements for instruction permits, liability \\naffidavits, driving experience, passenger restrictions, and curfew limitations, highlighting \\nlegal responsibilities and exceptions for minors. \\nMinor instruction permits: Requirements to obtain and restrictions on an instruction permit vary \\nby age. Affidavit of Liability and Guardianship: If you are under 18, your application must be \\naccompanied by an Affidavit of Liability (DR2460) signed and ver ified by your parent, \\nstepparent, grandparent with power of attorney, legal guardian, spouse older than 18, or any \\nother responsible adult willing to accept legal liability. The affidavit must be signed in front of \\nthe driver license office employee or a n otary public. Whoever signs the affidavit agrees to take \\nlegal responsibility for your actions as a driver. If the signer decides to no longer accept \\nresponsibility for your driving, that person may withdraw their signature and your permit/license \\nwill be canceled. Minors in foster care are exempt from this requirement, provided certain \\nconditions are met, additional information can be found at DMV.Colorado.gov/foster -children-\\ndriver-licenses. Application for driver license: Colorado law requires minors to have an \\ninstruction permit for 12 months before applying for a driver license and to submit a completed \\nand signed driving log showing 50 hours of driving experience (10 of which must have been at \\nnight). If younger than 16 and 6 months, you must also comp lete 6 hours of behind -the-wheel \\ntraining with an approved driver education instructor. If there is not an approved driving school \\noffering at least 20 hours of behind -the\\x02wheel training per week within 30 miles of your \\nresidence, 12 additional hours of dr iving with your parent/guardian/ alternate permit supervisor \\nmay be substituted for the 6 hours of behind the wheel training with a driver education \\ninstructor. If you live more than 30 miles from the nearest commercial driving school you must \\nbring a prin ted map of the route from your home to the driving school when you go to the driver \\nlicense office. Passenger restrictions: While you are younger than 18, you have passenger \\nrestrictions based on how long you have had your driver license. For the first six months after \\nyour license is issued, you cannot have any passengers under 21, unless a parent or another \\nlicensed adult driver is in the vehicle. After 6 months, you may have one passenger younger than \\n21. Siblings and passengers with medical emergencies are exceptions. After 1 year, you may \\ncarry as many passengers as there are seat belts in the vehicle. Curfew: For your first year as a \\nlicensed driver, driving between midnight and 5 a.m. is not allowed unless you are accompanied \\nby an instructor, parent or legal guardian. Exceptions include driving to and from school or work \\n(with a signed statement from school or work), medical emergencies and emancipated minors. '),\n", " Document(page_content=\"The following text outlines various reasons for potential suspension, revocation, or \\ncancellation of a driver's license in Colorado, such as accumulating excessive points, DUI \\nconvictions, failure to report accidents, and providing false information. Additionally, it \\ndiscusses seat belt laws, emphasizing mandatory usage for drivers, front -seat passengers, \\nand children under 16, with exceptions for specific situations and age -appropriate child \\nrestraint requirements. \\nHaving a driver license is a privilege. Protect that privilege by driving with care and consideration \\nfor others. Some examples of ways your driving privilege may be suspended, revoked or \\ncanceled are: ● Meet or exceed the minimum point accumulation for su spension. ● Are \\nconvicted of driving while under the influence of alcohol or drugs. ● Refuse to be tested for \\nalcohol or drug content. ● Are convicted of failing to report a crash or leaving the scene of a \\ncrash without stopping, exchanging information and rendering aid. ● Fail to report a crash to the \\nDivision of Motor Vehicles according to the Financial Responsibility Law. ● Give false \\ninformation on your driver license application. ● Fail to settle a judgment against you as a result \\nof a crash while oper ating a vehicle. ● Lend your license to someone else or misuse it. ● Fail to \\nappear for a re -examination requested by the Division of Motor Vehicles. ● Are convicted of \\nvehicular homicide as a result of a motor vehicle crash. 3 Colorado Driver Handbook ● F ail to \\npay ordered child support. ● Fail to provide valid evidence of insurance when requested by a \\nlaw enforcement officer. Drivers are required to have proof of insurance while operating a \\nvehicle. ● Are convicted of purchasing or possessing alcohol whil e you are younger than 21. \\nSEAT BELT LAWS Colorado law requires a fastened seat belt to be worn in all motor vehicles with \\na factory-equipped seat belt system while in operation on public roadways by: ● The driver ● \\nFront seat passengers ● Children under 1 6 The only exceptions are: ● Emergency personnel ● \\nPassenger buses and school buses ● Farm equipment ● The driver of delivery vans while on the \\njob ● Anyone carrying a written medical statement from a physician stating they are not \\nphysically or psychologi cally required to wear seat belts The Colorado child passenger \\nprotection law requires children to be properly fastened into an appropriate child restraint \\nsystem. If a parent is not in the motor vehicle, it is the driver’s responsibility to ensure that ea ch \\nchild is properly fastened into one of the following: ● Children less than 1 year old and weighing \\nless than 20 pounds: properly secured in a rear -facing child restraint system in a rear seat of the \\nvehicle. ● Children ages 1 to 4 and weighing 20 to 40 pounds: properly secured in a rear -facing \\nor forward -facing child restraint system. ● Children up to 8 years old: properly secured in a child \\nrestraint system, such as a booster seat, according to the manufacturer’s instructions. ● \\nChildren between 8 and 1 5 years old: properly restrained in a seat belt or child restraint system \\naccording to the manufacturer’s instructions. Passengers in motor vehicles driven by anyone \\nyounger than 18 must be properly restrained or wear seat belts. The number of passengers i n \\nvehicles driven by persons younger than 18 must not exceed the number of seats belts. \\n \"),\n", " Document(page_content='The following text emphasizes the dangers of driving under the influence of alcohol or \\ndrugs, detailing the impairments it causes and the legal consequences. It discusses the \\ndifferences between Driving While Ability is Impaired (DWAI) and Driving Under the \\nInfluence (D UI), including the associated penalties based on blood alcohol content levels \\nfor individuals aged 21 and older, and highlights the potential revocation of driving \\nprivileges for those under 21 convicted of impaired driving or alcohol -related offenses. \\nDriving while impaired by alcohol, other drugs, or drug combinations is one of the greatest \\nfactors in roadway crashes and fatalities. Every year, tens of thousands of people are killed by \\nimpaired drivers. But the facts and statistics do not tell the whol e story. Behind the numbers are \\nthousands of lives cut short, permanent or disabling injuries, and families devastated because \\nsomeone drove while under the influence of alcohol or drugs. When you drive while impaired, \\nsafe driving is not possible and you are more likely to take risks such as speeding or turning \\nabruptly. Alcohol is a depressant drug that reduces brain function, which impairs thinking, \\nreasoning, and muscle coordination. Depressants may slow reflexes and reaction times while \\nreducing your a bility to make the decisions necessary to safely operate a motor vehicle. As the \\namount of drugs in your body increases, your judgment worsens and skills decrease. It is \\nunlawful for someone to either possess an open container of alcohol or possess an open \\ncontainer of marijuana while in the passenger area of a motor vehicle that is on a public road. A \\ndriver may be convicted of either DWAI (Driving While Ability is Impaired) or DUI (Driving Under \\nthe Influence) depending on the level of the driver’s mental or physical impairment. DWAI \\nmeans the driver is impaired to the slightest degree. DUI means the driver is substantially \\nincapable of safe driving. Impaired driving convictions are not proven only by the driver’s Blood \\nAlcohol Concentration (BAC), but by the impaired driving behavior and a totality of \\ncircumstance. This is usually documented by the driver’s operation of the vehicle and/or \\nobserved impairment during the law enforcement officer’s contact with the driver and the \\ndriver’s performance on Standa rdized Field Sobriety Tests. A driver may also be convicted of DUI \\nper se if the driver’s BAC is greater than 0.08%. Licenses may be revoked if the driver refuses a \\ntoxicological test, set forth in Colorado Statute, or based on a BAC over .08 or over .02 i f the \\ndriver is under 21, or over .04 for a CDL driver. Alcohol in the body affects people differently, \\neven if they have consumed the same amount of alcohol over the same time period. A person’s \\nBAC depends on several factors: ● The amount of alcohol cons umed ● Body weight ● The \\nperiod of time in which the alcohol was consumed ● The amount of time since the last drink \\nwas consumed ● The person’s sex It does not make a difference whether a drink is beer, wine or \\nliquor. Standard servings of each contain abo ut the same amount of alcohol. A standard drink is \\ndefined as 12 ounces of beer, 5 ounces of wine, or 1.5 ounces of distilled spirits, all of which \\ncontain the same amount of alcohol. Once alcohol is in the bloodstream, only the passage of \\ntime will make p erson sober as the body eliminates it through normal bodily processes. On \\naverage, a person’s BAC will drop by 0.015% per hour. Driving under the influence while younger \\nthan 21: Any driver younger than 21, convicted of DUI or DWAI, is subject to revocation of their \\ndriver license for the first conviction if they fail to complete a court -ordered evaluation or \\nprogram. A second or t hird conviction is a mandatory revocation of their license. Colorado \\nDriver Handbook 4 Anyone younger than 21 is convicted of buying or possessing alcohol is \\nsubject to revocation of their driving privilege even if driving is not a factor . \\nDrugs and driving: Driving while impaired by drugs, including illicit drugs, marijuana, \\nprescription medications and over the counter medications, is illegal and subject to the same \\npenalties as driving while impaired by alcohol. They can have effects simi lar to alcohol or even worse. The fact that marijuana or other drugs were used for medicinal purposes is not a defense \\nfor DUI or DWAI. \\nBesides alcohol, other drugs can affect a person’s ability to safely operate a vehicle. Like \\nalcohol, impairment from these drugs is dose dependent and varies among individuals. \\nPrescription drugs, such as tranquilizers, pain killers and over -the-counter m edications for \\nallergies and colds can impair safe driving skills. Drivers must check medication labels for \\nwarnings about the medication’s effects before driving. If the label is missing or unclear, check \\nwith your doctor or pharmacist about any possible side effects. \\nThe National Safety Council advises that the active ingredients in marijuana cause changes in \\ncognitive effects (knowing, thinking, judging, evaluating and planning) and psychomotor effects \\n(coordination, reaction time, motor skills, and tracking). It is u nsafe to operate a vehicle while \\nimpaired by marijuana due to the increased risk of death or injury to the operator and the public. \\nLike with alcohol, the degree of marijuana impairment depends upon the dose consumed, time \\nsince consumption, and differences between individuals. The degree and duration of marijuana \\nimpairment depends upon the method of consumption. Unlike with alcohol, there is no \\ncorrelation Table 1 Conviction Blood Alcohol Content Points Toward Suspension Fine Jail Public \\nService 1st Driving While Ability Impaired (DWAI) 0.05% 8 $200 -$500 2-180 days 24 -48 hours 1st \\nDriving Under the Influence (DUI) 0.08% Revocation: 9 months $600 -$1,000 5-365 days 48 -96 \\nhours 2nd DWAI or DUI 0.08% Revocation: 1 year $600 - $1,500 10 -365 days 48 -120 hours 3rd or \\nsubsequent DWAI or DUI Revocation: 2 years $600 - $1,500 60 -365 days 48 -120 hours DRIVING \\nUNDER THE INFLUENCE ISN’T WORTH IT 5 Co lorado Driver Handbook between levels of Delta -\\n9-Tetrahydrocannabinol (THC) in the blood, breath or oral fluid (or saliva sample) and the degree \\nof individual impairment. \\nThere is a permissible inference that a driver was DUI if the driver’s blood contained 5 \\nnanograms of THC per milliliter (ng/ml) of blood. There is no THC permissible inference level for \\nDWAI. Most marijuana impaired drivers are convicted based upon behavi oral symptoms, as well \\nas blood THC levels. \\nPolydrug Impairment: Polydrug impairment is caused by using two or more drugs \\nsimultaneously, including using alcohol, marijuana, prescription medications, over -the-counter \\nmedications or any other drugs in any combination. Mixing drugs can increase the su bstance’s \\neffects. Colorado’s data shows that polydrug impairment is more common than impairment by \\nany single drug other than alcohol, and also more dangerous. \\nIllegal drugs such as LSD, methamphetamine and heroin also affect a person’s reflexes, \\njudgment and alertness along with their many other dangerous side effects. These drugs can \\ngive a false sense of alertness and self confidence or make you drowsy and una ble to react to \\nsimple situations. \\nLaw enforcement officers are trained to identify, document and testify to the impairment of \\ndriving skills, regardless of cause, including medical issues, alcohol, marijuana, prescription \\ndrugs, over -the-counter drugs, illegal drugs or any combination of t hese. Drivers are routinely \\nconvicted of Colorado’s impaired driving laws regardless of the drug or drugs causing the \\nimpairment and regardless of the level of any drug that may be found in the blood or saliva. Express Consent Law (C.R.S. 42 -4-1301.1): Colorado has an express consent law, which means \\nwhen you operate a motor vehicle in the Centennial State, you agree to take a chemical test to \\ndetermine the presence of alcohol and/or drugs in your blood. \\nIf you are suspected of driving while impaired or under the influence of alcohol and/or drugs, \\nlaw enforcement officers can require you to take a chemical test of your blood, breath, saliva or \\nurine. \\nIf you refuse to take the test or do not comply with being tested, your driver license will be \\nrevoked for one year and you will be required to install an ignition interlock device on any motor \\nvehicle you drive for two years. \\nAn ignition interlock is is a device that is installed on motor vehicles to prohibits you from \\noperating a vehicle while under the influence of alcohol. It requires your breath sample before \\nthe engine will start, and you are periodically required to provi de breath samples while driving. If \\nthe device detects an elevated alcohol concentration level, the vehicle will not start. \\nIf other suspensions or revocations come about from t his same incident, they will be added \\nonto the end of the revocation (consecutively). Because driving under the influence is \\nexceedingly dangerous, penalties for alcohol or drug related violations are very tough and can \\ninclude jail, fines and suspension o f driving privileges. Colorado law does not allow you to plea \\nbargain out of an alcohol or drug related driving offense. The only sure way to avoid the \\nconsequences is not to use alcohol or drugs at all when driving. \\nThe follow ing are the p ossible Penalties for Impaired Driving for 21 and Older in a table for mat: \\nConviction - Blood Alcohol Content - Points Toward Suspension - Fine - Jail - Public Service \\n1st Driving While Ability Impaired (DWAI) - 0.05% - 8 - $200 to $500 – 2 to180 days – 24 to 48 \\nhours. \\n1st Driving Under the Influence (DUI) - 0.08%- Revocation : 9 months - $600 to $1,000 – 5 to 365 \\ndays – 48 to 96 hours. \\n2nd DWAI or DUI - 0.08% - Revocation: 1 year - $600 to $1,500 – 10 to 365 days - 48 to120 hours \\n3rd or subsequent DWAI or DUI - Revocation: 2 years - $600 to $1,500 – 60 to 365 days – 48 to \\n120 hours '),\n", " Document(page_content='The following text provides comprehensive guidance on factors to consider before driving, \\nemphasizing the importance of clear vision, alertness, physical and mental fitness, and \\nminimizing distractions. It covers aspects such as vision and hearing requirements, the \\nimpact of fatigue and health conditions, emotional states, and the significance of \\nmaintaining a distraction -free environment. Additionally, it stresses the importance of \\nvehicle maintenance and safety checks to ensure safe driving conditions, highlighting \\nvarious components such as brakes, lights, tires, steering, and exhaust systems. \\nBEFORE YOU DRIVE Being a safe driver depends on being able to see clearly, not being overly \\ntired, not driving under the influence of alcohol or drugs, being generally healthy, and being \\nmentally and emotionally fit to drive. There are many environmental s ights and sounds to be \\naware of while driving such as weather, time of the day, lighting conditions, honking, sirens, \\nscreeching tires, people shouting, etc. Using all of your available senses to assist you with \\nalertness and awareness of one’s surrounding s can help warn you of danger. Vision: Good vision \\nis a must for safe driving. You drive based on what you see. If you cannot see clearly without \\ncorrective lenses, you may have trouble identifying traffic and road conditions, spotting \\npotential hazards, r ecognizing smaller road users like pedestrians or bicyclists and reacting in a \\ntimely manner. It is important to have your eyes checked every year or two by an eye specialist. \\nIf you have a corrective lens restriction on your license, you need to wear glas ses or contact \\nlenses while driving. Hearing: While your hearing levels can be helpful to alert you to your \\nsurroundings, it must be noted the ability to hear (or not) does not guarantee you will hear \\nenvironmental sounds. Music may be playing, passengers may be talking, and/or the car may be \\nso well-insulated to the outside world that environmental sounds are muted. It is also common \\nfor people to experience declines in their hearing levels as they age and/or due to exposure to \\nloud noises. These declines can happen so slowly that a person may not immediately notice an \\nissue. If you suspect that your hearing levels have declined, it is recommended you have your \\nhearing tested by an audiologist. Note — You may not operate a motor vehicle while wearing \\nearphones. The definition of earphones include any device or headset which covers all or a \\nportion of both ears. Earphones do not include hearing aids, cochlear implants, assistive \\nlistening devices, speakers or other listening devices that are built into protec tive headgear or a \\ndevice that only covers all or a portion of one ear and that is connected to a wireless device. \\nFatigue: When you are tired, you cannot drive as safely as when you are rested. Your reactions \\nand decision making skills are greatly reduced . Break long driving periods into two -hour \\nsegments. If you become drowsy, pull off the road and rest. Health: Many health problems, such \\nas a bad cold, infection or a virus, can affect your driving. Even little problems such as a stiff \\nneck, cough or sore leg can affect your driving. Some conditions, such as epilepsy, diabetes and \\nheart conditions can pose risks that make it unsafe to drive a vehicle. Check with your doctor if \\nyou think your health condition could affect your driving. Emotions: Emotions ca n greatly affect \\nsafe driving. You may not drive well if you are overly worried, excited, afraid or angry. Do not give \\nin to road rage. Colorado Driver Handbook 6 Distractions: Distractions are the leading cause of \\ndriver error. A distraction is anything t hat takes away your attention, even momentarily, from the \\ntask of driving. Driving requires your full attention. Before beginning a trip, adjust your seat, \\nmirrors, radio, temperature and secure any loose objects in the car. Be sure everyone in the \\nvehicle, particularly children, are wearing age -appropriate restraint devices. Do not allow \\nyourself to become distracted by your cell phone, conversations with passengers, children or \\nrubbernecking (staring at something of interest). Safely pull over to address distracting or urgent \\nsituations. Vehicle: The vehicle you drive impacts your ability to drive safely. Motorists are \\nresponsible to ensure the vehicles they drive are safe to operate. A vehicle in poor operating condition is unsafe, costs more to drive and can cause an emergency situation, such as a \\nbreakdown or wreck. It can also result in a citation from law enforcement. Follow your vehicle \\nowner’s manual for routine maintenance. A few simple checks will prevent trouble on the road \\nand ensure your vehicle complies with Colorado motor vehicle laws: ● Braking system: If the \\nbrakes do not seem to be working properly, have a mechanic check them immediately. ● Lights: \\nMake sure turn signals, brake lights, tail lights and headlights are operating properly. ● \\nWindshield and wipers: Get your windshield replaced if the glass is damaged because damaged \\nglass can break easily or obstruct vision. Windshield wipers keep the rain and snow off the \\nwindshield. Make sure they are in good operating condition. If the blades have not been working \\nwell, replace them. Keep the windshield clean inside and out, and keep your window washer \\nfluid tank full. Clear snow, ice or frost from all windows. ● Tires: Worn or bald tires can increase \\nyour stopping distance, make turning more difficult, can cause hydroplaning when the road is \\nwet, and increase the chance of having a flat tire. Unbalanced wheels and low tire pressure \\nincrease tire wear, reduce fuel economy and make the vehicle harder to steer and stop. If the \\nvehicle bounces, the steering wheel shakes, or the vehicle pulls to one side, have a mechanic \\ncheck your tires. ● Steering system: If the vehicle is hard to turn, have the steering checked by a \\nmechanic. ● Suspension system: If the v ehicle bounces excessively, keeps bouncing after a \\nbump or after you stop, you may need new shocks or other suspension parts. Have a mechanic \\ncheck it out. ● Exhaust system: Fumes from a leaky exhaust system can cause death in a very \\nshort time. Never run the motor in your garage or sit in the car with the motor running without \\nopening a window. Most exhaust problems are easily heard; have them repaired. ● Engine: A \\npoorly tuned engine can lose power needed for normal driving and emergencies, may not start, \\nget poor fuel economy, pollute the air, and could stall on you when you are on the road, causing \\nproblems for you and other traffic. ● Horn: The horn should be checked regularly. ● Mirrors: \\nAdjust your rear view mirror and side mirrors before you begin to drive. To adjust the driver’s side \\nmirror place your head against the left side window and set the mirror so you can barely see the \\nside of the car in the left side of the mirror. To adjust the passenger’s side mirror position your \\nhead so that it is cent ered under the inside rearview mirror or just above the center console. Set \\nthe mirror so you can just see the side of the car in the right side of the mirror. ● Loose objects: \\nMake sure there are no objects on the rear shelf or back seat that could injure someone during a \\nsudden stop or crash. Ensure there are no objects on the floor that could roll under the brake \\npedal or accelerator and interfere with your safe driving. ● Head rests: They should be adjusted \\nso the head restraint touches the back of your head. ')]" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Read the document\n", "\n", "def read_pdf_files(directory):\n", " \"\"\"\n", " Function to load all PDF files in the mentioned dierectory. Groups the text by document and converts them to langchain_core.documents format.\n", " \"\"\"\n", " texts = [] # List to store text content of all PDF files\n", " docs = [] # List to store the converted langchain_core.documents \n", " \n", " # Iterate over all files in the directory\n", " for filename in os.listdir(directory):\n", " if filename.endswith('.pdf'): # Check if the file is a PDF\n", " file_path = os.path.join(directory, filename) # Get the full file path\n", " with open(file_path, 'rb') as file: # Open the PDF file in binary mode\n", " pdf_reader = PdfReader(file) # Create a PdfFileReader object\n", " num_pages = len(pdf_reader.pages) # Get the number of pages in the PDF\n", " pdf_text = '' # Variable to store text content of the PDF\n", " # Iterate over each page and extract text\n", " for page_num in range(num_pages):\n", " page = pdf_reader.pages[page_num] # Get the current page\n", " pdf_text += page.extract_text() # Extract text from the page and append to pdf_text\n", " texts.append(pdf_text) # Append the text content of the PDF to the list\n", " \n", " # Convert the texts to langchain_core.documents format\n", " for doc_text in texts:\n", " docs.append(doc_base.Document(doc_text))\n", " return docs\n", "\n", "docs= read_pdf_files(r\"resources\\input_files\")\n", "print(len(docs))\n", "docs[:5]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Loaded all the 24 documents generated from the handbook." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "768" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Initialze the embedder to create embeddings for the chunked documents\n", "\n", "#embedder= OpenAIEmbeddings(api_key=os.environ['OPENAPI_API_KEY'])\n", "embedder= GoogleGenerativeAIEmbeddings(model=\"models/embedding-001\")\n", "len(embedder.embed_query(\"Testing the length of embedded vector to be used in initializing the vector db?\"))" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "# Initialize and store the vector embeddings of the chunked audio into Pinecone\n", "\n", "pinecone.Pinecone(api_key= os.environ['PINECONE_API_KEY'], environment= os.environ['PINECONE_ENV']) # Initialize the pinecone with API Key \n", "index= Pinecone.from_documents(docs, embedder, index_name= os.environ['PINECONE_INDEX_NAME']) # Convert the chunked docs to vectors and stores them in Pinecone" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The Following text provides comprehensive information about traffic controls, including \n", "traffic signals, traffic signs, and pavement markings. It explains the meaning of different \n", "traffic signal lights and how to respond to them, such as steady red, yellow, and green \n", "lights, as well as green, red, and yellow arrows. It also covers the significance of flashing \n", "lights and HAWK signals. Furthermore, it details various types of traffic signs, such as \n", "regulatory signs, speed limit signs, stop signs, yield signs, and warning signs. It explains \n", "the importance of each sign and how drivers should respond to them to ensure safety on \n", "the road. Ad ditionally, it includes information about railroad crossings, work zone signs, \n", "guide signs, service/recreation signs, route signs, bicycle and pedestrian crossing signs, \n", "and disabled parking signs. \n", "TRAFFIC CONTROLS Traffic controls include traffic signals, traffic signs, and pavement \n", "markings. Traffic control also can be provided by law enforcement, highway personnel, or \n", "school crossing guards. You must obey directions from these persons. TRAFFIC SIG NALS Traffic \n", "signals are lights that tell you when or where to stop and go. Traffic lights are usually at \n", "intersections and are (from top to bottom) red, yellow, and green. There are intersections and \n", "other locations where there are single green, yellow or red lights. If the traffic signal is not \n", "operating or is malfunctioning, treat the intersection as a four way stop. Steady red light: Stop \n", "until a green light appears. After stopping and yielding to pedestrians and other traffic, and if not \n", "prohibited by a traffic sign, you may turn right while the light is red. Also, you may turn left on a \n", "red light if you are turning from a one\u0002way street onto another one -way street, unless prohibited \n", "by a sign. Steady yellow light: A red light is about to appear. Stop u nless you are already in the \n", "intersection. Steady green light: After yielding to any vehicle or pedestrian within the \n", "intersection or adjacent crosswalk, you may proceed straight through or turn right or left unless \n", "a sign prohibits such turns. Red Arrow: A lighted red arrow means you must stop and may not \n", "turn in the direction shown. Green arrow: A lighted green arrow, by itself or along with a red, \n", "green or yellow light means you may turn in the direction shown by the arrow. If the green arrow \n", "goes off, b ut the circular green is on, you may still turn after yielding to through vehicles and \n", "pedestrians, unless prohibited by a sign or red arrow. Yellow arrow: A lighted red arrow is about \n", "to appear. Stop if you are not already in the intersection. Flashing ye llow arrow: A flashing yellow \n", "arrow means the driver turning left should proceed with caution and must yield to oncoming \n", "traffic and pedestrians. Never rush through a flashing yellow arrow, take the time to check for a \n", "clear path through the intersection. The signal will then switch to solid yellow, telling the driver \n", "the light is about to turn red and to not enter the intersection if they can stop safely. Finally the \n", "signal will turn red, which means the driver must stop. Flashing red light: A flashing red light \n", "means the same as a STOP sign. Stop; then go only after yielding to pedestrians and other \n", "traffic. Flashing yellow light: A flashing yellow light is a warning of a hazard. Slow down and \n", "proceed with caution. HAWK signals (High Intensity Activated Cr osswalk): HAWK signals are \n", "traffic signals that allow pedestrians to cross the road safely. HAWK signals operate in a yellow \n", "red flashing sequence to alert motorists that pedestrians need to cross the road. TRAFFIC \n", "SIGNS Traffic signs tell you about traffi c rules, hazards, and your current location. They can also \n", "give directions and help you to locate services. The shapes and colors of these signs indicate \n", "the type of information they provide. Regulatory signs: These signs tell you of laws and \n", "regulations t hat apply at a location. They are black or red on a white background. Failure to obey \n", "these signs is a traffic violation. Speed limit signs: These signs show the maximum or minimum \n", "speed that is allowed. The maximum limits are for ideal conditions and you must reduce your \n", "speed when conditions require it. Stop signs: These signs mean you must come to a complete \n", "stop. You must stop at a clearly marked stop line, but if none, before entering the crosswalk on the near side of the intersection, or if none, then at the point nearest the intersecting roadway \n", "where the driver has a view of approaching traffic. Yield signs: These signs indicate you must \n", "slow or stop to yield to all pedestrians and any vehicle with r ight of way. Do Not Enter/Wrong \n", "Way signs: These signs warn and redirect drivers who are heading the wrong way on streets or \n", "freeway ramps. Do not proceed past one of these signs. Colorado Driver Handbook 8 One Way \n", "signs: These signs indicate you may only travel in the direction indicated by the sign’s arrow. \n", "Lane control signs: These signs give direction and information about where you can turn and \n", "often use an arrow symbol. The signs are along the side of the road or hang over the road. \n", "Sometimes arrows m ay be painted on the road. Prohibited signs: These signs indicate you \n", "cannot do something, for example, no U -turn or no left turn. Warning signs: These signs are \n", "yellow or fluorescent green with black symbols, school zone, curves, slippery surfaces, mergin g \n", "traffic, or pedestrian -dense areas. For instance, a merging traffic sign warns of vehicles entering \n", "from a side street. Advisory speed signs: These cautionary signs show the safe speed around \n", "curves, corners and off -ramps in ideal conditions. Railroad cr ossings: These signs show \n", "information about railroad crossings and can be a variety of shapes. Never try to beat a train \n", "across the tracks. Never start to cross the tracks until there is enough room for your vehicle to \n", "clear the tracks on the other side. D o not shift gears when crossing the railroad tracks in case \n", "your vehicle stalls. Railroad emergency notification system (ENS) Signs: These blue signs are at \n", "every highway -rail grade crossing and provide the public with a telephone number to report \n", "problems or emergencies at these railroad locations. Directly below the dispatch number on the \n", "ENS sign is a Department of Transportation number that identifies the exact location of the \n", "crossing in question. Work zone signs: These signs have an orange background with black \n", "letters or symbols. They are used with other traffic control devices or flag persons to help direct \n", "traffic safely through work areas and to protect roadway workers. Guide signs: These signs have \n", "a green background and provide directional and mi leage information to specific destinations. \n", "Service/recreation signs: These signs have blue or brown backgrounds. Signs with blue \n", "backgrounds provide directions to service facilities. Signs with brown backgrounds indicate \n", "recreational, historic or cultural areas. Route signs and markers: The shape of the sign indicates \n", "the type of roadway: Interstate, U.S., State or County highway. Bicycle and pedestrian crossing \n", "signs: These signs have a yellow background with black symbols. They are used where both \n", "bicyclists and pedestrians might be crossing the roadway, such as at an intersection with a \n", "shared use path. Pass 3 ft min signs: These signs have a white background with black letters \n", "and PASS 3FT MIN 9 Colorado Driver Handbook symbols. Motorists, when passing or overtaking \n", "bicyclists, must allow for clearance of 3 feet to avoid sideswiping on all roadways even if a sign \n", "is not posted. Bicycle may use full lane signs: These signs have a white background with black \n", "letters and symbols. They remind drivers that bi cyclists have a right to ride in the center of the \n", "lane if they feel their safety is compromised by hazards or poor visibility if they were to ride in \n", "the right side of the lane. Slow moving vehicle marker: A reflective orange triangle on the rear of \n", "a vehicle means it is designed to travel at speeds slower than 25 miles per hour. Disabled \n", "parking signs: These signs mark special parking areas for only those vehicles displaying a \n", "disabled parking permit. Disabled parking indicators may also appear on the pav ement in \n", "designated parking spaces. Crosshatched sections are for van access only and parking is not \n", "allowed at any time. In order to park in a disabled parking space, the person who owns the \n", "disabled placard must be entering or exiting the vehicle. If you park illegally in a designated \n", "disabled parking spot without a placard or plate, you could be charged with a misdemeanor, \n", "and if convicted, subject to a $350 -$5,000 fine, possible jail time, loss of driving privileges \n", "and/or your car being impounded. If y ou park in one of these spaces with someone else’s placard or plate, you will be subject to jail time, loss of driving privileges and towing as well as \n", "fines double those listed above. \n", "The following text outlines rules regarding the right -of-way in various traffic situations. It \n", "emphasizes yielding to pedestrians, bicyclists, and vehicles already in an intersection. It \n", "covers scenarios such as four -way stops, uncontrolled intersections, left turns, l ane \n", "changes, merging, reversing, and yielding to emergency vehicles, maintenance vehicles, \n", "snowplows, school buses, transit buses, and vehicles in work/construction zones. It also \n", "discusses speed limits in work/construction zones. \n", "RIGHT-OF-WAY Where drivers or pedestrians meet one another, and there are no signs or \n", "signals to regulate traffic, there are rules that say who must yield the right -of-way. These rules \n", "tell drivers who proceeds first and who must wait in different traffic situations. The law states \n", "who must yield the right -of-way, but it does not give anyone the right -of-way, even if your traffic \n", "signal is green. You must yield the right -of-way to pedestrians, bicyclists, and other drivers who \n", "are already in an intersection you are approaching. Pedestrians: When driving, you must always \n", "yield the right\u0002of -way to pedestrians. Be very watchful for children, seniors and people with \n", "disabilities. Do not assume that pedestrians can hear or see you and/or your vehicle or any \n", "visual or audible crossing signals as some pedestrians may be deaf, hard of hearing, deaf -blind \n", "or blind. Most blind or deaf -blind people are easily recognized by the white cane they carry \n", "Roundabout lane 11 Colorado Driver Handbook and/or by their guide dog. P edestrians have the \n", "right-of\u0002way at all intersections and crosswalks. You must come to a complete stop and let the \n", "person pass safely. Bicycles: Bicycles on the road are considered vehicles and have many of the \n", "same rights and responsibilities as motor veh icles. Drivers must yield the right -of-way to \n", "bicyclists in a designated bike lane when merging with or crossing a bike lane to turn. Bicyclists \n", "riding on a sidewalk or crosswalk have the same rights and responsibilities as pedestrians. \n", "Four-way stop: You must yield the right\u0002of -way to the vehicle that reached the intersection first. \n", "When more than one vehicle reaches the intersection at the same time, the vehicle on the left \n", "must yield the right -of-way and allow the vehicle on the right to go first. Regard less of who has \n", "the right-of-way, you are always responsible for avoiding a crash. Uncontrolled intersection: An \n", "uncontrolled intersection is an intersection that does not have control devices such as stop \n", "signs or traffic lights. When more than one vehicl e reaches an uncontrolled intersection at the \n", "same time, the vehicle on the left must yield the right -of-way to the vehicle on the right and \n", "allow the vehicle on the right to go first. Turning left: Before proceeding through a left turn, \n", "always be sure to look for and yield to pedestrians in the crosswalk and other smaller oncoming \n", "vehicles such as bicyclists and motorcyclists and take time to properly judge their speed and \n", "distance. You must yield to all oncoming traffic, unless you have a green arrow or a rrived first at \n", "a four-way stop. Changing lanes and passing: You must yield the right -of\u0002way to vehicles \n", "already occupying the lane you wish to enter or use for passing. Do not change lanes if another \n", "vehicle must slow down for you. Merging: You must yield to all vehicles on the roadway you are \n", "merging with. Do not merge if another vehicle must slow down for you. Reversing: You must \n", "yield the right -of-way to all vehicles close enough to be a hazard. Narrow mountain road: When \n", "vehicles meet on a steep, narro w road that is not wide enough for two vehicles, the vehicle going \n", "downhill must yield the right -of-way by backing up to a wider place or by stopping, then leaving \n", "enough space for the vehicle going uphill, except where it is more practicable for the vehic le \n", "going uphill to return to a wider space or turnout. Emergency vehicles: You must yield the right -\n", "of-way to all emergency vehicles using a siren, air horn and/ or flashing red, blue, white or yellow \n", "lights. Where possible, you must pull to the right edge of the road and come to a stop. If you are \n", "in an intersection, drive through the intersection, then pull over. If you are approaching an \n", "emergency vehicle stopped along the side of the road, try to leave at least one lane between \n", "your vehicle and the emer gency vehicle. If the road only has one lane on your side or you cannot change lanes, slow down to a safe speed and use care and caution as you pass. Unless directed \n", "otherwise by emergency personnel or conditions prohibit the lane change, you should slow \n", "down to: ● 25 MPH if the posted speed limit is 45 MPH or less Or ● 20 MPH under the posted \n", "speed limit if the posted speed limit is above 45 MPH Maintenance vehicles: You must yield \n", "right of way to service vehicles and maintenance equipment when in use and flashing yellow \n", "and blue warning lights. Use extra caution when approach ing, overtaking or passing \n", "maintenance vehicles. Snow plows: Be especially cautious around snow plows because their \n", "size and speed can create clouds of blowing snow that can conceal the plow. It is illegal to pass \n", "an authorized snow plow when it is working in a formation in which the plows are staggered \n", "diagonally. School bus: You must stop your vehicle at least 20 feet before reaching a school bus \n", "that is stopped with its red lights flashing, and you must stop until the lights stop flashing. You \n", "must stop whether it is on your side of the road, the opposite side of the road or at an \n", "intersection you are approaching. You must remain stopped until the flashing red lights are no \n", "longer flashing. Carefully watch for children near the school bus and children cro ssing the \n", "roadway before proceeding. You are not required to stop if there is a median or other physical \n", "barrier separating the bus from your vehicle. Transit buses: You must yield right -of-way to a \n", "transit bus if it is signaling to enter a traffic lane an d the yield sign on the rear of the bus is \n", "illuminated. Road work/Construction zone: When driving in a work/ construction zone, keep \n", "construction crews and fellow road users safe by adjusting your lane position away from \n", "workers and slowing down to navigat e any obstacles or changes in the flow of traffic with \n", "caution. Stay alert and prepared to respond to any unpredictable events. For safety reasons, \n", "normal speed limits may be reduced in work/construction zones. Any reduced speed limits will \n", "be clearly mark ed. Failure to follow the speed limit in a work/ construction zone can result in \n", "double fines. \n", "The following emphasizes the importance of sharing the road safely with motorcyclists and \n", "outlines key considerations for drivers. It highlights the vulnerability of motorcyclists to \n", "injury and the need for drivers to be attentive and cautious around them. Additionally , it \n", "provides specific situations that can lead to collisions with motorcyclists and offers \n", "preventive measures for drivers to avoid such accidents, such as checking for oncoming \n", "motorcyclists before turning left and being vigilant when opening vehicle doo rs. \n", "MOTORCYCLES Motorcyclists have the same rights and responsibilities as other drivers. With \n", "minimal crash protection, motorcyclists are very vulnerable to injury, even death, when hit by a \n", "larger vehicle. Motorcyclists are entitled to the same full lane wid th as other vehicles. \n", "Motorcyclists frequently move around in their lane so they can see, be seen and avoid road \n", "hazards. Also, be aware that strong winds can unexpectedly move a motorcycle out of its lane. \n", "There are some additional situations and conditio ns you need to be aware of so you can safely \n", "share the road with motorcyclists: ● Motorcycles are smaller than other motor vehicles, harder \n", "to see and can move faster and stop quicker than expected. ● Road defects and debris can \n", "create dangers for motorcyc lists. ● Watch for motorcyclists, use extra caution when driving \n", "around them and increase your following distance. Avoiding Collisions: Drivers can help to \n", "prevent collisions with motorcyclists by knowing the most common causes of motorist -\n", "motorcyclist col lisions below and how to avoid them. Following are the c ause of collision and \n", "how to prevent : \n", "• Motorist turning left in front of an oncoming bicyclist -> Look for oncoming bicyclists \n", "riding on the shoulder or edge of the lane before turning \n", "• Motorist or bicyclist running a stop sign or stop signal -> Stop first, then proceed into \n", "intersection yielding to others. \n", "• Motorist opening a vehicle door without looking behind for a passing bicyclist -> Always \n", "check behind you before opening a door into the roadway \n", "• Bicyclist riding the wrong way against traffic, toward the motorist -> Ride bicycles in the \n", "same direction as traffic \n", "• Motorist pulling out from a driveway and failing to see a bicyclist on road or sidewalk -> \n", "Check both directions when crossing a sidewalk, bike path, or road . \n" ] } ], "source": [ "# Create a funtion to return top matching vectors for the query based on Cosine Similarity\n", "\n", "def pinecone_top_matching_vects(query, top_size= 2):\n", " top_matching_vects= index.similarity_search(query, k= top_size)\n", " return top_matching_vects\n", "\n", "# Tesitng\n", "for i in pinecone_top_matching_vects(\"Can I take the free right even if the signal is red?\", top_size= 3):\n", " print(i.page_content)" ] } ], "metadata": { "kernelspec": { "display_name": "venv", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.5" } }, "nbformat": 4, "nbformat_minor": 2 }