├── .DS_Store ├── LICENSE ├── README.md ├── attachments ├── demo.mp4 └── workflow.png ├── prompts ├── initial.txt └── wiring.txt ├── resources ├── cameras.json ├── convert-to-sql.js ├── create-table.sql ├── example_supabase_update_workflow_block.py └── update_clip_sql.py └── v0-site ├── .DS_Store ├── .gitignore ├── app ├── api │ ├── getResults │ │ └── route.ts │ ├── proxy-image │ │ └── route.ts │ └── search │ │ └── route.ts ├── globals.css ├── layout.tsx ├── page.tsx └── search │ ├── loading.tsx │ └── page.tsx ├── components.json ├── components ├── ErrorDisplay.tsx ├── HeatMap.tsx ├── LiveWebcam.tsx └── ui │ ├── accordion.tsx │ ├── alert-dialog.tsx │ ├── alert.tsx │ ├── aspect-ratio.tsx │ ├── avatar.tsx │ ├── badge.tsx │ ├── breadcrumb.tsx │ ├── button.tsx │ ├── calendar.tsx │ ├── card.tsx │ ├── carousel.tsx │ ├── chart.tsx │ ├── checkbox.tsx │ ├── collapsible.tsx │ ├── command.tsx │ ├── context-menu.tsx │ ├── dialog.tsx │ ├── drawer.tsx │ ├── dropdown-menu.tsx │ ├── form.tsx │ ├── hover-card.tsx │ ├── input-otp.tsx │ ├── input.tsx │ ├── label.tsx │ ├── menubar.tsx │ ├── navigation-menu.tsx │ ├── pagination.tsx │ ├── popover.tsx │ ├── progress.tsx │ ├── radio-group.tsx │ ├── resizable.tsx │ ├── scroll-area.tsx │ ├── select.tsx │ ├── separator.tsx │ ├── sheet.tsx │ ├── sidebar.tsx │ ├── skeleton.tsx │ ├── slider.tsx │ ├── sonner.tsx │ ├── switch.tsx │ ├── table.tsx │ ├── tabs.tsx │ ├── textarea.tsx │ ├── toast.tsx │ ├── toaster.tsx │ ├── toggle-group.tsx │ ├── toggle.tsx │ ├── tooltip.tsx │ ├── use-mobile.tsx │ └── use-toast.ts ├── hooks ├── use-mobile.tsx └── use-toast.ts ├── lib └── utils.ts ├── next.config.mjs ├── package.json ├── postcss.config.mjs ├── public ├── placeholder-logo.png ├── placeholder-logo.svg ├── placeholder-user.jpg ├── placeholder.jpg └── placeholder.svg ├── styles └── globals.css ├── tailwind.config.ts └── tsconfig.json /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yeldarby/nycerebro/935c840f3cf513b9e3aafa87185446087f9e1218/.DS_Store -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NYCerebro 2 | 3 | 4 | 8 | 9 | This repository contains the code for the NYCerebro, project which won the Vercel + NVIDA World's Shortest Hackathon. 10 | 11 | [Full writeup here](https://blog.roboflow.com/nycerebro/) of how we built this using CLIP, Supabase, Mapbox, and Roboflow. 12 | 13 | ## Project Description 14 | 15 | When we learned that the city of New York has publicly shared its 900+ surveillance cameras video streams (https://webcams.nyctmc.org/map), we thought it would be a cool to build a tool that would allow us to monitor the city in real-time. Specifically we got inspired by X-Men's Dr. Xavier's Cerebro device. 16 | 17 | ## How It Works 18 | 19 | ### Homepage (`/`) 20 | - **Simple Search Interface:** 21 | A clean, Google-style search page featuring the NYCerebro logo, a text box, and a “Search” button. 22 | - **Query Suggestions:** 23 | Quick links (e.g., “weird,” “busy,” “bright,” “time square,” “traffic”) help spark creative searches. 24 | 25 | ### Search Results (`/search?q=`) 26 | - **Live Camera Preview:** 27 | Your query is sent to a Roboflow CLIP workflow which generates an embedding from the text. This embedding is compared with camera embeddings stored in Supabase, and the best match is displayed as a live image (auto-refreshing every 2 seconds) using dynamically generated URLs. 28 | 29 | - **Interactive Heatmap:** 30 | A Mapbox-powered heatmap shows which parts of NYC most strongly correspond to your query. The location of the top-matching camera appears as the “hottest” point, while nearby matches contribute to the overall visual effect. 31 | 32 | - **Backend Processing:** 33 | While you wait, a loading screen is shown while the backend: 34 | - Calls a Roboflow workflow (using a dummy 10x10 black PNG as the required image input) to get a CLIP embedding. 35 | - Retrieves the 25 closest camera matches from Supabase (initially random until fully integrated). 36 | 37 | ### Roboflow & Supabase Integration 38 | - **Roboflow Workflow:** 39 | The app calls a Roboflow workflow that takes your query (with a dummy image) and returns a CLIP embedding. 40 | - **Camera Image Processing:** 41 | A Python script continuously fetches images from NYC cameras and uses Roboflow’s InferenceHTTPClient to process each image. The workflow then upserts the camera’s new CLIP embedding, ID, and current timestamp into our Supabase database. 42 | 43 | ### Workflow Diagram 44 | Below is an image of the Roboflow Workflow that manages CLIP embedding generation and Supabase updates: 45 | 46 | Roboflow Workflow 47 | 48 | (You can find the code for the custom python block for supabase updates in the resources folder) 49 | 50 | ## Tech Stack & APIs 51 | - **Frontend:** Minimalistic, search-driven interface. 52 | - **Backend:** Python and Node.js handle image fetching, Roboflow integration, and database updates. 53 | - **Database:** Supabase stores camera metadata and CLIP embeddings. 54 | - **Maps:** Mapbox renders a real-time heatmap of NYC. 55 | - **CLIP Embeddings:** Generated via a Roboflow Workflow integrating text queries and camera images. 56 | -------------------------------------------------------------------------------- /attachments/demo.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yeldarby/nycerebro/935c840f3cf513b9e3aafa87185446087f9e1218/attachments/demo.mp4 -------------------------------------------------------------------------------- /attachments/workflow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yeldarby/nycerebro/935c840f3cf513b9e3aafa87185446087f9e1218/attachments/workflow.png -------------------------------------------------------------------------------- /prompts/initial.txt: -------------------------------------------------------------------------------- 1 | I'm creating a web app called NYCerebro. It will let you search all of the live imagery from NYC's public traffic cameras using CLIP. 2 | 3 | The app will have two pages: 4 | 5 | / is the homepage and should be a similar interface to Google Search with a logo, a textbox, and a "Search" button. Below this there should be some ideas for queries (presented as "links" similar to the idea of "I'm feeling lucky" on Google to get people started if they don't know what to type. These should be "weird", "busy", "bright", "time square", and "traffic" 6 | /search?q= will be the search results page. At the top, it will have a live updating view of the best result webcam for the QUERY (as defined by the best match to the query's CLIP vector). Below that will be a heatmap of New York City (using the Mapbox API) showing where the QUERY is most concentrated based on the similarity of the images in the DB to the query's CLIP embedding (so, for example, querying "busy" during a weekday morning would likely be concentrated around the financial district and subway stations and "weird" would probably be concentrated around Bushwick). 7 | The /search page should show a loading screen while it hits a backend endpoint called /getResults. The responsibility of /getResults is to accept the QUERY as a string, embed it with CLIP and then pull the results needed to render the /search page from the database (skip the CLIP part for now and just pull results at random from the Supabase table; I will fill in the logic later). 8 | 9 | I have created a table in Supabase called cameras and filled it with rows with info like this (later on I will actually fill in the values for the embeddings by running CLIP on the webcam images on a recurring basis; let's ignore that for now): 10 | 11 | INSERT INTO cameras (camera_id, latitude, longitude, embedding) 12 | VALUES 13 | ('1b874f5c-e1c6-481d-bb85-8d7d92c1793b', 40.6656, -73.9536, array_fill(0::float, ARRAY[512])::vector) 14 | ... 15 | To generate an image URL from a camera_id, fill the ID into this string format: 16 | 17 | https://webcams.nyctmc.org/api/cameras/{CAMERA_ID_HERE}/image?t={EPOCH_TIME_IN_SECONDS} 18 | We should refresh the camera image every 2 seconds on the /search results page. 19 | 20 | For reference, here is my Mapbox Public Token: pk.eyJ1Ijoicm9ib2Zsb3dicmFkIiwiYSI6ImNtNjA1cXZnOTA1bHUya284OHB4Z25lYTEifQ.Y8nuCyyyE_nKDEK4TaHduA -------------------------------------------------------------------------------- /prompts/wiring.txt: -------------------------------------------------------------------------------- 1 | Now I'd like to actually wire this up. 2 | 3 | I've created a Roboflow Workflow that accepts a text query and returns a CLIP embedding. I also added a `ROBOFLOW_API_KEY` environment vairable. 4 | 5 | Adapt this example code for calling the workflow to happen from the server when we make a query: 6 | ``` 7 | const response = await fetch('https://detect.roboflow.com/infer/workflows/shortest-hackathon/embed-text', { 8 | method: 'POST', 9 | headers: { 10 | 'Content-Type': 'application/json' 11 | }, 12 | body: JSON.stringify({ 13 | api_key: 'YOUR API KEY HERE', 14 | inputs: { 15 | "image": {"type": "base64", "value": "..."}, 16 | "query": "TEXT QUERY HERE" 17 | } 18 | }) 19 | }); 20 | 21 | const result = await response.json(); 22 | ``` 23 | Please note that the `image` input is required but not actually used. Please fill it in with a dummy 10x10 black png image so we don't get an error. 24 | 25 | The response format will be something like this: 26 | ``` 27 | [ 28 | { 29 | "embedding": [ 30 | -0.04967321828007698, 31 | 0.029600081965327263, 32 | -0.1002882570028305, 33 | -0.04563215374946594, 34 | 0.0658196434378624, 35 | -0.18116864562034607, 36 | ... 37 | ]}] 38 | ``` 39 | 40 | Use this to query against the image embeddings in our Supabase table and return the 25 closest matches. 41 | 42 | Then use that information to update the heatmap. The location of the best match camera should be the "hottest". I'll let you choose how mathematically to accomplish that in a visually stimulating way. -------------------------------------------------------------------------------- /resources/convert-to-sql.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | /** 4 | * Usage: 5 | * 1. Save this file as, for example, `importCameras.js`. 6 | * 2. Run `npm init -y` (if you haven't already) to set up a Node project. 7 | * 3. Run `chmod +x importCameras.js` to make it executable (optional). 8 | * 4. Execute `node importCameras.js` (or `./importCameras.js`) to output the SQL. 9 | */ 10 | 11 | const fs = require('fs'); 12 | const path = require('path'); 13 | 14 | // Adjust this path if cameras.json is in a different directory 15 | const filePath = path.join(__dirname, 'cameras.json'); 16 | 17 | // Read the JSON file 18 | fs.readFile(filePath, 'utf8', (err, data) => { 19 | if (err) { 20 | console.error('Error reading cameras.json:', err); 21 | process.exit(1); 22 | } 23 | 24 | let cameras; 25 | try { 26 | cameras = JSON.parse(data); 27 | } catch (parseErr) { 28 | console.error('Error parsing JSON:', parseErr); 29 | process.exit(1); 30 | } 31 | 32 | // Build the VALUES clauses 33 | // Note: We map JSON's "lng" -> DB's "lon". 34 | // Embedding is zeros for now: `array_fill(0::float, ARRAY[512])::vector` 35 | const values = cameras.map((cam) => { 36 | const { id, lat, lng } = cam; 37 | 38 | // Be sure to handle any special characters or SQL escaping, if necessary. 39 | // For simplicity, we assume `id`, `lat`, and `lng` are well-formed. 40 | return `('${id}', ${lat}, ${lng}, array_fill(0::float, ARRAY[512])::vector)`; 41 | }); 42 | 43 | // Create the SQL insert statement 44 | // We omit last_updated so it uses its DEFAULT, 45 | // and we rely on the zero vector default for embedding if needed— 46 | // but here we explicitly provide it, just to show how it's done. 47 | const sql = ` 48 | INSERT INTO cameras (camera_id, lat, lon, embedding) 49 | VALUES 50 | ${values.join(',\n')} 51 | ;`; 52 | 53 | // Output the SQL 54 | console.log(sql); 55 | }); 56 | -------------------------------------------------------------------------------- /resources/create-table.sql: -------------------------------------------------------------------------------- 1 | -- Enable extensions if not already enabled 2 | CREATE EXTENSION IF NOT EXISTS pgvector; 3 | CREATE EXTENSION IF NOT EXISTS postgis; 4 | 5 | CREATE TABLE cameras ( 6 | camera_id UUID PRIMARY KEY, 7 | last_updated TIMESTAMP NOT NULL DEFAULT '1970-01-01 00:00:00', 8 | location GEOGRAPHY(Point, 4326) 9 | NOT NULL 10 | DEFAULT 'SRID=4326;POINT(0 0)'::geography, 11 | embedding vector(512) NOT NULL 12 | DEFAULT array_fill(0::float, ARRAY[512])::vector 13 | ); 14 | 15 | -- Index for nearest-neighbor on embedding 16 | CREATE INDEX cameras_embedding_idx 17 | ON cameras 18 | USING ivfflat (embedding vector_cosine_ops) 19 | WITH (lists = 100); 20 | 21 | -- Optional spatial index on location, if you need geospatial queries 22 | CREATE INDEX cameras_location_idx 23 | ON cameras 24 | USING GIST (location); 25 | -------------------------------------------------------------------------------- /resources/example_supabase_update_workflow_block.py: -------------------------------------------------------------------------------- 1 | # THIS IS THE CONTENT OF THE ROBOFLOW WORKFLOW "Supabase Update" CUSTOM PYTHON BLOCK 2 | # This code is here to be used as a reference for the Roboflow Workflow 3 | # It is not used in the server code 4 | import requests 5 | import datetime 6 | 7 | def run(self, clip_embedding, camera_id, SUPABASE_URL, SUPABASE_KEY) -> dict: 8 | # Current UTC time (assuming 'last_updated' column is TIMESTAMP or TIMESTAMPTZ) 9 | last_updated = datetime.datetime.utcnow().isoformat() 10 | 11 | # Data to be inserted or updated 12 | data_payload = { 13 | "camera_id": camera_id, 14 | "embedding": clip_embedding, 15 | "last_updated": last_updated 16 | } 17 | 18 | endpoint = f"{SUPABASE_URL}/rest/v1/cameras?on_conflict=camera_id" 19 | 20 | headers = { 21 | "apikey": SUPABASE_KEY, 22 | "Authorization": f"Bearer {SUPABASE_KEY}", 23 | "Content-Type": "application/json", 24 | "Prefer": "resolution=merge-duplicates,return=representation" 25 | } 26 | 27 | # PostgREST expects an array of rows for insert/upsert calls 28 | response = requests.post(endpoint, headers=headers, json=[data_payload]) 29 | status = "Successfully updated the database!" 30 | if response.status_code >= 300: 31 | print() 32 | status = "Error upserting data:" + str(response.status_code) + str(response.text) 33 | 34 | return {"status" : status} 35 | -------------------------------------------------------------------------------- /resources/update_clip_sql.py: -------------------------------------------------------------------------------- 1 | import json 2 | import requests 3 | import time 4 | from typing import List 5 | import os 6 | from inference_sdk import InferenceHTTPClient 7 | 8 | 9 | def load_camera_ids(json_file: str) -> List[str]: 10 | """Extract camera IDs from the JSON file.""" 11 | try: 12 | with open(json_file, 'r') as f: 13 | data = json.load(f) 14 | 15 | # Validate and extract IDs 16 | if not isinstance(data, list): 17 | raise ValueError("JSON data must be a list of camera objects.") 18 | return [camera['id'] for camera in data if 'id' in camera] 19 | 20 | except (json.JSONDecodeError, FileNotFoundError, ValueError) as e: 21 | print(f"Error loading camera IDs: {str(e)}") 22 | return [] 23 | 24 | 25 | def process_camera(camera_id: str): 26 | """ 27 | Fetch the image from the given camera ID and process it using InferenceHTTPClient. 28 | """ 29 | base_url = "https://webcams.nyctmc.org/api/cameras/{}/image" 30 | url = base_url.format(camera_id) 31 | 32 | try: 33 | # Fetch the image 34 | response = requests.get(url) 35 | if response.status_code == 200: 36 | # Save image to a temporary file 37 | image_path = f"{camera_id}_image.jpg" 38 | with open(image_path, 'wb') as f: 39 | f.write(response.content) 40 | 41 | # Initialize InferenceHTTPClient 42 | client = InferenceHTTPClient( 43 | api_url=os.getenv("INFERENCE_API_URL", "http://localhost:9001"), 44 | api_key=os.getenv("ROBOFLOW_API_KEY") 45 | ) 46 | 47 | # Run the workflow 48 | result = client.run_workflow( 49 | workspace_name="shortest-hackathon", 50 | workflow_id="indexwebcam", 51 | images={ 52 | "image": image_path 53 | }, 54 | parameters={ 55 | "SUPABASE_KEY": os.getenv("SUPABASE_KEY"), 56 | "SUPABASE_URL": os.getenv("SUPABASE_URL"), 57 | "camera_id": camera_id 58 | } 59 | )[0]["result"] 60 | 61 | print(f"Processed camera {camera_id}, the result is: {result}") 62 | # Remove the temporary image file after processing 63 | os.remove(image_path) 64 | 65 | else: 66 | print(f"Failed to fetch image from camera {camera_id}: Status {response.status_code}") 67 | except Exception as e: 68 | print(f"Error processing camera {camera_id}: {str(e)}") 69 | 70 | 71 | def fetch_camera_images(camera_ids: List[str], interval: float = 2.0): 72 | """ 73 | Fetch images from cameras in a loop, processing one camera every interval seconds. 74 | 75 | Args: 76 | camera_ids: List of camera IDs 77 | interval: Time in seconds to wait between processing each camera 78 | """ 79 | if not camera_ids: 80 | print("No camera IDs available to process. Exiting.") 81 | return 82 | 83 | most_recent_index = 0 84 | camera_count = len(camera_ids) 85 | 86 | while True: 87 | # Get the next camera ID to process 88 | camera_id = camera_ids[most_recent_index] 89 | print(f"Processing camera {camera_id}...") 90 | 91 | # Process the camera 92 | process_camera(camera_id) 93 | 94 | # Update the most recent index 95 | most_recent_index = (most_recent_index + 1) % camera_count 96 | 97 | # Wait for the specified interval before processing the next camera 98 | time.sleep(interval) 99 | 100 | 101 | def main(): 102 | # Assuming the JSON file is named 'cameras.json' 103 | camera_ids = load_camera_ids('cameras.json') 104 | print(f"Loaded {len(camera_ids)} camera IDs") 105 | 106 | # Start the loop to fetch and process camera images 107 | fetch_camera_images(camera_ids) 108 | 109 | 110 | if __name__ == "__main__": 111 | main() -------------------------------------------------------------------------------- /v0-site/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yeldarby/nycerebro/935c840f3cf513b9e3aafa87185446087f9e1218/v0-site/.DS_Store -------------------------------------------------------------------------------- /v0-site/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | 6 | # next.js 7 | /.next/ 8 | /out/ 9 | 10 | # production 11 | /build 12 | 13 | # debug 14 | npm-debug.log* 15 | yarn-debug.log* 16 | yarn-error.log* 17 | .pnpm-debug.log* 18 | 19 | # env files 20 | .env* 21 | 22 | # vercel 23 | .vercel 24 | 25 | # typescript 26 | *.tsbuildinfo 27 | next-env.d.ts -------------------------------------------------------------------------------- /v0-site/app/api/getResults/route.ts: -------------------------------------------------------------------------------- 1 | import { createClient } from '@supabase/supabase-js' 2 | import { NextResponse } from 'next/server' 3 | 4 | const supabase = createClient(process.env.SUPABASE_URL!, process.env.SUPABASE_ANON_KEY!) 5 | 6 | export async function GET(request: Request) { 7 | const { searchParams } = new URL(request.url) 8 | const query = searchParams.get('q') 9 | 10 | // For now, we'll just return random results 11 | const { data: cameras, error } = await supabase 12 | .from('cameras') 13 | .select('camera_id, latitude, longitude') 14 | .limit(50) 15 | 16 | if (error) { 17 | return NextResponse.json({ error: error.message }, { status: 500 }) 18 | } 19 | 20 | const bestMatch = cameras[Math.floor(Math.random() * cameras.length)].camera_id 21 | 22 | const heatmapData = cameras.map(camera => ({ 23 | latitude: camera.latitude, 24 | longitude: camera.longitude, 25 | intensity: Math.random() // Random intensity for now 26 | })) 27 | 28 | return NextResponse.json({ bestMatch, heatmapData }) 29 | } 30 | 31 | -------------------------------------------------------------------------------- /v0-site/app/api/proxy-image/route.ts: -------------------------------------------------------------------------------- 1 | import { NextResponse } from 'next/server' 2 | 3 | export async function GET(request: Request) { 4 | const { searchParams } = new URL(request.url) 5 | const imageUrl = searchParams.get('url') 6 | 7 | if (!imageUrl) { 8 | return NextResponse.json({ error: 'Image URL is required' }, { status: 400 }) 9 | } 10 | 11 | try { 12 | const response = await fetch(imageUrl) 13 | 14 | if (!response.ok) { 15 | throw new Error(`Failed to fetch image: ${response.status} ${response.statusText}`) 16 | } 17 | 18 | const imageBuffer = await response.arrayBuffer() 19 | const headers = new Headers(response.headers) 20 | headers.set('Access-Control-Allow-Origin', '*') 21 | 22 | return new NextResponse(imageBuffer, { 23 | status: 200, 24 | headers: headers, 25 | }) 26 | } catch (error: any) { 27 | console.error('Proxy error:', error) 28 | return NextResponse.json({ error: error.message || 'Failed to fetch image' }, { status: 500 }) 29 | } 30 | } 31 | 32 | -------------------------------------------------------------------------------- /v0-site/app/api/search/route.ts: -------------------------------------------------------------------------------- 1 | import { createClient } from '@supabase/supabase-js' 2 | import { NextResponse } from 'next/server' 3 | 4 | const supabase = createClient(process.env.SUPABASE_URL!, process.env.SUPABASE_ANON_KEY!) 5 | 6 | export async function GET(request: Request) { 7 | const { searchParams } = new URL(request.url) 8 | const query = searchParams.get('q') 9 | 10 | if (!query) { 11 | return NextResponse.json({ error: 'Query parameter is required' }, { status: 400 }) 12 | } 13 | 14 | try { 15 | console.log('Sending request to Roboflow API...') 16 | const clipResponse = await fetch('https://detect.roboflow.com/infer/workflows/shortest-hackathon/embed-text', { 17 | method: 'POST', 18 | headers: { 19 | 'Content-Type': 'application/json' 20 | }, 21 | body: JSON.stringify({ 22 | api_key: process.env.ROBOFLOW_API_KEY, 23 | inputs: { 24 | "image": {"type": "url", "value": "https://source.roboflow.com/c8QoUtY71EUIn6gsXQMkSt8K0fC3/lUis6HgjW32zZv1WYVKQ/thumb.jpg"}, 25 | "query": query 26 | } 27 | }) 28 | }) 29 | 30 | if (!clipResponse.ok) { 31 | const errorText = await clipResponse.text() 32 | console.error('Roboflow API error response:', errorText) 33 | throw new Error(`Roboflow API error: ${clipResponse.status} ${clipResponse.statusText} - ${errorText}`) 34 | } 35 | 36 | const clipResult = await clipResponse.json() 37 | console.log('Roboflow API response:', JSON.stringify(clipResult, null, 2)) 38 | 39 | if (!clipResult.outputs || !Array.isArray(clipResult.outputs) || clipResult.outputs.length === 0) { 40 | console.error('Invalid Roboflow API response structure:', clipResult) 41 | throw new Error('Invalid response structure from Roboflow API: Missing or empty outputs array') 42 | } 43 | 44 | const embedding = clipResult.outputs[0].embedding 45 | 46 | if (!Array.isArray(embedding) || embedding.length === 0) { 47 | console.error('Invalid embedding in Roboflow API response:', clipResult.outputs[0]) 48 | throw new Error('Invalid embedding in Roboflow API response: Expected non-empty array') 49 | } 50 | 51 | console.log('Querying Supabase...') 52 | const { data: matchedCameras, error } = await supabase.rpc('match_cameras', { 53 | query_embedding: embedding, 54 | match_threshold: 0, // Lowered threshold to get more results 55 | match_count: 25 56 | }) 57 | 58 | if (error) { 59 | console.error('Supabase error:', error) 60 | throw new Error(`Supabase error: ${error.message}`) 61 | } 62 | 63 | console.log('Supabase query result:', JSON.stringify(matchedCameras, null, 2)) 64 | 65 | let cameras; 66 | if (!matchedCameras || matchedCameras.length === 0) { 67 | console.log('No matching cameras found. Returning all cameras.') 68 | const { data: allCameras, error: allCamerasError } = await supabase 69 | .from('cameras') 70 | .select('camera_id, latitude, longitude') 71 | .limit(25) 72 | 73 | if (allCamerasError) { 74 | console.error('Error fetching all cameras:', allCamerasError) 75 | throw new Error(`Error fetching all cameras: ${allCamerasError.message}`) 76 | } 77 | 78 | if (!allCameras || allCameras.length === 0) { 79 | return NextResponse.json({ error: 'No cameras found in the database' }, { status: 404 }) 80 | } 81 | 82 | cameras = allCameras.map(camera => ({ 83 | ...camera, 84 | distance: Math.random() // Assign random distances for visualization 85 | })) 86 | } else { 87 | cameras = matchedCameras; 88 | } 89 | 90 | console.log(`Found ${cameras.length} cameras`) 91 | console.log('Camera data:', JSON.stringify(cameras, null, 2)) 92 | 93 | const validDistances = cameras.map((c: any) => c.distance).filter((d: number) => !isNaN(d)) 94 | const maxDistance = Math.max(...validDistances) 95 | const minDistance = Math.min(...validDistances) 96 | 97 | console.log('Max distance:', maxDistance) 98 | console.log('Min distance:', minDistance) 99 | 100 | const heatmapData = cameras.map((camera: any) => { 101 | let intensity = null 102 | if (!isNaN(camera.distance) && maxDistance !== minDistance) { 103 | intensity = (maxDistance - camera.distance) / (maxDistance - minDistance) 104 | } 105 | console.log(`Camera ${camera.camera_id}: distance = ${camera.distance}, intensity = ${intensity}`) 106 | return { 107 | latitude: camera.latitude, 108 | longitude: camera.longitude, 109 | intensity: intensity 110 | } 111 | }) 112 | 113 | console.log('Processed heatmap data:', JSON.stringify(heatmapData, null, 2)) 114 | 115 | const bestMatch = cameras[0].camera_id 116 | 117 | return NextResponse.json({ bestMatch, heatmapData }) 118 | } catch (error: any) { 119 | console.error('Search error:', error) 120 | console.error('Error stack:', error.stack) 121 | return NextResponse.json({ 122 | error: error.message || 'An unknown error occurred', 123 | stack: process.env.NODE_ENV === 'development' ? error.stack : undefined 124 | }, { status: 500 }) 125 | } 126 | } 127 | 128 | -------------------------------------------------------------------------------- /v0-site/app/globals.css: -------------------------------------------------------------------------------- 1 | @tailwind base; 2 | @tailwind components; 3 | @tailwind utilities; 4 | 5 | @layer base { 6 | :root { 7 | --background: 0 0% 100%; 8 | --foreground: 222.2 84% 4.9%; 9 | --card: 0 0% 100%; 10 | --card-foreground: 222.2 84% 4.9%; 11 | --popover: 0 0% 100%; 12 | --popover-foreground: 222.2 84% 4.9%; 13 | --primary: 222.2 47.4% 11.2%; 14 | --primary-foreground: 210 40% 98%; 15 | --secondary: 210 40% 96.1%; 16 | --secondary-foreground: 222.2 47.4% 11.2%; 17 | --muted: 210 40% 96.1%; 18 | --muted-foreground: 215.4 16.3% 46.9%; 19 | --accent: 210 40% 96.1%; 20 | --accent-foreground: 222.2 47.4% 11.2%; 21 | --destructive: 0 84.2% 60.2%; 22 | --destructive-foreground: 210 40% 98%; 23 | --border: 214.3 31.8% 91.4%; 24 | --input: 214.3 31.8% 91.4%; 25 | --ring: 222.2 84% 4.9%; 26 | --radius: 0.5rem; 27 | } 28 | 29 | .dark { 30 | --background: 222.2 84% 4.9%; 31 | --foreground: 210 40% 98%; 32 | --card: 222.2 84% 4.9%; 33 | --card-foreground: 210 40% 98%; 34 | --popover: 222.2 84% 4.9%; 35 | --popover-foreground: 210 40% 98%; 36 | --primary: 210 40% 98%; 37 | --primary-foreground: 222.2 47.4% 11.2%; 38 | --secondary: 217.2 32.6% 17.5%; 39 | --secondary-foreground: 210 40% 98%; 40 | --muted: 217.2 32.6% 17.5%; 41 | --muted-foreground: 215 20.2% 65.1%; 42 | --accent: 217.2 32.6% 17.5%; 43 | --accent-foreground: 210 40% 98%; 44 | --destructive: 0 62.8% 30.6%; 45 | --destructive-foreground: 210 40% 98%; 46 | --border: 217.2 32.6% 17.5%; 47 | --input: 217.2 32.6% 17.5%; 48 | --ring: 212.7 26.8% 83.9%; 49 | } 50 | } 51 | 52 | @layer base { 53 | * { 54 | @apply border-border; 55 | } 56 | body { 57 | @apply bg-background text-foreground; 58 | } 59 | } 60 | 61 | @layer utilities { 62 | .animate-text-shine { 63 | background-size: 200% auto; 64 | animation: text-shine 3s linear infinite; 65 | } 66 | 67 | @keyframes text-shine { 68 | from { 69 | background-position: 0% center; 70 | } 71 | to { 72 | background-position: 200% center; 73 | } 74 | } 75 | } 76 | 77 | -------------------------------------------------------------------------------- /v0-site/app/layout.tsx: -------------------------------------------------------------------------------- 1 | import './globals.css' 2 | import type { Metadata } from 'next' 3 | import { JetBrains_Mono } from 'next/font/google' 4 | 5 | const jetBrainsMono = JetBrains_Mono({ subsets: ['latin'] }) 6 | 7 | export const metadata: Metadata = { 8 | title: 'NYCerebro', 9 | description: 'Search NYC traffic cameras using CLIP', 10 | } 11 | 12 | export default function RootLayout({ 13 | children, 14 | }: { 15 | children: React.ReactNode 16 | }) { 17 | return ( 18 | 19 | 20 | {children} 21 | 22 | 23 | ) 24 | } 25 | 26 | -------------------------------------------------------------------------------- /v0-site/app/page.tsx: -------------------------------------------------------------------------------- 1 | 'use client' 2 | 3 | import { useState } from 'react' 4 | import Link from 'next/link' 5 | import { Input } from "@/components/ui/input" 6 | import { Button } from "@/components/ui/button" 7 | 8 | export default function Home() { 9 | const [query, setQuery] = useState('') 10 | 11 | return ( 12 |
13 | {/* Background image with overlay */} 14 |
15 |
19 |
20 |
21 | 22 | {/* Content */} 23 |
24 | {/* Title */} 25 |

26 | NYCerebro 27 |

28 | 29 | {/* Search form */} 30 |
34 | setQuery(e.target.value)} 39 | placeholder="Search NYC cameras..." 40 | className="flex-1 h-12 bg-gray-900/50 border-purple-500/20 text-gray-100 placeholder:text-gray-400 text-lg rounded-lg" 41 | /> 42 | 48 |
49 | 50 | {/* Quick search links */} 51 |
52 | {['weird', 'busy', 'bright', 'time square', 'traffic'].map((term) => ( 53 | 58 | {term} 59 | 60 | ))} 61 |
62 |
63 |
64 | ) 65 | } 66 | 67 | -------------------------------------------------------------------------------- /v0-site/app/search/loading.tsx: -------------------------------------------------------------------------------- 1 | export default function LoadingScreen() { 2 | return ( 3 |
4 |
5 |
6 | ) 7 | } 8 | 9 | -------------------------------------------------------------------------------- /v0-site/app/search/page.tsx: -------------------------------------------------------------------------------- 1 | 'use client' 2 | 3 | import { useSearchParams } from 'next/navigation' 4 | import { useEffect, useState } from 'react' 5 | import LoadingScreen from './loading' 6 | import LiveWebcam from '@/components/LiveWebcam' 7 | import HeatMap from '@/components/HeatMap' 8 | import ErrorDisplay from '@/components/ErrorDisplay' 9 | 10 | interface SearchResult { 11 | bestMatch: string; 12 | heatmapData: Array<{ latitude: number; longitude: number; intensity: number }>; 13 | } 14 | 15 | export default function SearchResults() { 16 | const searchParams = useSearchParams() 17 | const query = searchParams.get('q') 18 | const [results, setResults] = useState(null) 19 | const [loading, setLoading] = useState(true) 20 | const [error, setError] = useState(null) 21 | 22 | useEffect(() => { 23 | async function fetchResults() { 24 | setLoading(true) 25 | setError(null) 26 | try { 27 | const response = await fetch(`/api/search?q=${encodeURIComponent(query || '')}`) 28 | const data = await response.json() 29 | 30 | if (!response.ok) { 31 | throw new Error(data.error || 'An unknown error occurred') 32 | } 33 | 34 | console.log('Search results:', data) 35 | setResults(data) 36 | } catch (error: any) { 37 | console.error('Search error:', error) 38 | setError(error.message || 'An unknown error occurred') 39 | } finally { 40 | setLoading(false) 41 | } 42 | } 43 | 44 | fetchResults() 45 | }, [query]) 46 | 47 | if (loading) { 48 | return 49 | } 50 | 51 | if (error) { 52 | return 53 | } 54 | 55 | return ( 56 |
57 |

Search Results for: {query}

58 | {results && ( 59 | <> 60 | 61 | {results && results.heatmapData && results.heatmapData.length > 0 ? ( 62 | <> 63 | 64 |
65 |       {JSON.stringify(results.heatmapData, null, 2)}
66 |     
67 | 68 | ) : ( 69 |
No heatmap data available
70 | )} 71 | 72 | )} 73 |
74 | ) 75 | } 76 | 77 | -------------------------------------------------------------------------------- /v0-site/components.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://ui.shadcn.com/schema.json", 3 | "style": "default", 4 | "rsc": true, 5 | "tsx": true, 6 | "tailwind": { 7 | "config": "tailwind.config.ts", 8 | "css": "app/globals.css", 9 | "baseColor": "neutral", 10 | "cssVariables": true, 11 | "prefix": "" 12 | }, 13 | "aliases": { 14 | "components": "@/components", 15 | "utils": "@/lib/utils", 16 | "ui": "@/components/ui", 17 | "lib": "@/lib", 18 | "hooks": "@/hooks" 19 | }, 20 | "iconLibrary": "lucide" 21 | } -------------------------------------------------------------------------------- /v0-site/components/ErrorDisplay.tsx: -------------------------------------------------------------------------------- 1 | import { AlertCircle } from 'lucide-react' 2 | 3 | interface ErrorDisplayProps { 4 | message: string 5 | details?: any 6 | } 7 | 8 | export default function ErrorDisplay({ message, details }: ErrorDisplayProps) { 9 | return ( 10 |
11 |
12 |
13 | 14 | Error: 15 |
16 | {message} 17 | {process.env.NODE_ENV === 'development' && details && ( 18 |
19 |             {JSON.stringify(details, null, 2)}
20 |           
21 | )} 22 |
23 |
24 | ) 25 | } 26 | 27 | -------------------------------------------------------------------------------- /v0-site/components/HeatMap.tsx: -------------------------------------------------------------------------------- 1 | 'use client' 2 | 3 | import { useEffect, useRef, useState, useCallback } from 'react' 4 | import mapboxgl from 'mapbox-gl' 5 | import 'mapbox-gl/dist/mapbox-gl.css' 6 | 7 | interface HeatMapProps { 8 | data: Array<{ latitude: number; longitude: number; intensity: number }> 9 | } 10 | 11 | export default function HeatMap({ data }: HeatMapProps) { 12 | const mapContainer = useRef(null) 13 | const map = useRef(null) 14 | const [error, setError] = useState(null) 15 | const [isStyleLoaded, setIsStyleLoaded] = useState(false) 16 | 17 | const updateMapData = useCallback((mapData: typeof data) => { 18 | if (!map.current) { 19 | console.log('Map not initialized, cannot update data') 20 | return 21 | } 22 | 23 | try { 24 | console.log('Updating map with data:', mapData) 25 | const features = mapData.map(point => ({ 26 | 'type': 'Feature' as const, 27 | 'properties': { 28 | 'intensity': point.intensity 29 | }, 30 | 'geometry': { 31 | 'type': 'Point' as const, 32 | 'coordinates': [point.longitude, point.latitude] 33 | } 34 | })) 35 | 36 | console.log('Created features:', features) 37 | 38 | if (!map.current.getSource('points')) { 39 | console.error('Points source not found, attempting to add it') 40 | map.current.addSource('points', { 41 | 'type': 'geojson', 42 | 'data': { 43 | 'type': 'FeatureCollection', 44 | 'features': [] 45 | } 46 | }) 47 | } 48 | 49 | const source = map.current.getSource('points') as mapboxgl.GeoJSONSource 50 | if (source) { 51 | source.setData({ 52 | 'type': 'FeatureCollection', 53 | 'features': features 54 | }) 55 | 56 | // Fit the map to the data points 57 | if (features.length > 0) { 58 | const bounds = new mapboxgl.LngLatBounds() 59 | features.forEach((feature: any) => { 60 | bounds.extend(feature.geometry.coordinates as [number, number]) 61 | }) 62 | map.current!.fitBounds(bounds, { 63 | padding: 50, 64 | maxZoom: 13 65 | }) 66 | } 67 | 68 | console.log('Map data updated successfully') 69 | } else { 70 | console.error('Points source still not found after attempting to add it') 71 | } 72 | } catch (err: any) { 73 | console.error('Error updating map data:', err) 74 | setError(`Failed to update map data: ${err.message}`) 75 | } 76 | }, []) 77 | 78 | useEffect(() => { 79 | mapboxgl.accessToken = 'pk.eyJ1Ijoicm9ib2Zsb3dicmFkIiwiYSI6ImNtNjA1cXZnOTA1bHUya284OHB4Z25lYTEifQ.Y8nuCyyyE_nKDEK4TaHduA' 80 | 81 | if (map.current) return 82 | 83 | console.log('Initializing Mapbox map...') 84 | 85 | try { 86 | map.current = new mapboxgl.Map({ 87 | container: mapContainer.current!, 88 | style: 'mapbox://styles/mapbox/dark-v10', 89 | center: [-73.98, 40.75], 90 | zoom: 11 91 | }) 92 | 93 | map.current.on('style.load', () => { 94 | console.log('Map style loaded') 95 | setIsStyleLoaded(true) 96 | 97 | if (!map.current) return 98 | 99 | map.current.addSource('points', { 100 | 'type': 'geojson', 101 | 'data': { 102 | 'type': 'FeatureCollection', 103 | 'features': [] 104 | } 105 | }) 106 | 107 | map.current.addLayer({ 108 | 'id': 'points-heat', 109 | 'type': 'heatmap', 110 | 'source': 'points', 111 | 'paint': { 112 | 'heatmap-weight': [ 113 | 'interpolate', 114 | ['linear'], 115 | ['get', 'intensity'], 116 | 0, 1, 117 | 1, 3 118 | ], 119 | 'heatmap-intensity': [ 120 | 'interpolate', 121 | ['linear'], 122 | ['zoom'], 123 | 0, 1, 124 | 20, 5 125 | ], 126 | 'heatmap-color': [ 127 | 'interpolate', 128 | ['linear'], 129 | ['heatmap-density'], 130 | 0, 'rgba(0, 0, 255, 0)', 131 | 0.2, 'rgba(0, 255, 255, 0.8)', 132 | 0.4, 'rgba(0, 255, 0, 0.9)', 133 | 0.6, 'rgba(255, 255, 0, 1)', 134 | 0.8, 'rgba(255, 0, 0, 1)', 135 | 1, 'rgba(255, 0, 255, 1)' 136 | ], 137 | 'heatmap-radius': [ 138 | 'interpolate', 139 | ['linear'], 140 | ['zoom'], 141 | 0, 10, 142 | 20, 30 143 | ], 144 | 'heatmap-opacity': 1 145 | } 146 | }) 147 | 148 | map.current.addLayer({ 149 | 'id': 'points-circles', 150 | 'type': 'circle', 151 | 'source': 'points', 152 | 'paint': { 153 | 'circle-radius': 8, 154 | 'circle-color': [ 155 | 'interpolate', 156 | ['linear'], 157 | ['get', 'intensity'], 158 | 0, '#0000ff', 159 | 0.5, '#00ff00', 160 | 1, '#ff0000' 161 | ], 162 | 'circle-opacity': 0.9, 163 | 'circle-stroke-width': 2, 164 | 'circle-stroke-color': '#ffffff' 165 | } 166 | }) 167 | 168 | console.log('Map layers added') 169 | 170 | if (data.length > 0) { 171 | console.log('Updating initial data after style load') 172 | updateMapData(data) 173 | } 174 | }) 175 | 176 | map.current.on('error', (e) => { 177 | console.error('Mapbox error:', e) 178 | setError(`Mapbox error: ${e.error?.message || 'Unknown error'}`) 179 | }) 180 | 181 | } catch (err: any) { 182 | console.error('Error initializing map:', err) 183 | setError(`Failed to initialize map: ${err.message}`) 184 | } 185 | 186 | return () => { 187 | if (map.current) { 188 | map.current.remove() 189 | } 190 | } 191 | }, [data, updateMapData]) 192 | 193 | useEffect(() => { 194 | if (!map.current || !isStyleLoaded) { 195 | console.log('Map or style not ready, waiting...') 196 | return 197 | } 198 | 199 | console.log('Data changed, updating map') 200 | updateMapData(data) 201 | }, [data, isStyleLoaded, updateMapData]) 202 | 203 | if (error) { 204 | return ( 205 |
206 | {error} 207 |
208 | ) 209 | } 210 | 211 | return ( 212 |
213 |
214 |
215 | Heatmap data points: {data.length} 216 |
217 |
218 | ) 219 | } 220 | 221 | -------------------------------------------------------------------------------- /v0-site/components/LiveWebcam.tsx: -------------------------------------------------------------------------------- 1 | 'use client' 2 | 3 | import { useState, useEffect } from 'react' 4 | import Image from 'next/image' 5 | import { AlertCircle, RefreshCcw } from 'lucide-react' 6 | import { Button } from "@/components/ui/button" 7 | 8 | interface LiveWebcamProps { 9 | cameraId: string 10 | } 11 | 12 | export default function LiveWebcam({ cameraId }: LiveWebcamProps) { 13 | const [imageUrl, setImageUrl] = useState('') 14 | const [error, setError] = useState(null) 15 | const [loading, setLoading] = useState(true) 16 | 17 | const updateImage = async () => { 18 | setLoading(true) 19 | setError(null) 20 | const epochTime = Math.floor(Date.now() / 1000) 21 | const originalUrl = `https://webcams.nyctmc.org/api/cameras/${cameraId}/image?t=${epochTime}` 22 | const proxyUrl = `/api/proxy-image?url=${encodeURIComponent(originalUrl)}` 23 | 24 | try { 25 | const response = await fetch(proxyUrl) 26 | if (!response.ok) { 27 | throw new Error(`Failed to load webcam image: ${response.status} ${response.statusText}`) 28 | } 29 | const blob = await response.blob() 30 | setImageUrl(URL.createObjectURL(blob)) 31 | } catch (err: any) { 32 | console.error('Error loading webcam image:', err) 33 | setError(err.message || 'Failed to load webcam image') 34 | } finally { 35 | setLoading(false) 36 | } 37 | } 38 | 39 | useEffect(() => { 40 | updateImage() 41 | const interval = setInterval(updateImage, 2000) 42 | return () => clearInterval(interval) 43 | }, [cameraId]) 44 | 45 | return ( 46 |
47 |

Live Webcam

48 |
49 | {loading && ( 50 |
51 |
52 |
53 | )} 54 | {error ? ( 55 |
56 | 57 |

{error}

58 | 62 |
63 | ) : ( 64 | imageUrl && ( 65 | Live webcam 72 | ) 73 | )} 74 |
75 |
76 | ) 77 | } 78 | 79 | -------------------------------------------------------------------------------- /v0-site/components/ui/accordion.tsx: -------------------------------------------------------------------------------- 1 | "use client" 2 | 3 | import * as React from "react" 4 | import * as AccordionPrimitive from "@radix-ui/react-accordion" 5 | import { ChevronDown } from "lucide-react" 6 | 7 | import { cn } from "@/lib/utils" 8 | 9 | const Accordion = AccordionPrimitive.Root 10 | 11 | const AccordionItem = React.forwardRef< 12 | React.ElementRef, 13 | React.ComponentPropsWithoutRef 14 | >(({ className, ...props }, ref) => ( 15 | 20 | )) 21 | AccordionItem.displayName = "AccordionItem" 22 | 23 | const AccordionTrigger = React.forwardRef< 24 | React.ElementRef, 25 | React.ComponentPropsWithoutRef 26 | >(({ className, children, ...props }, ref) => ( 27 | 28 | svg]:rotate-180", 32 | className 33 | )} 34 | {...props} 35 | > 36 | {children} 37 | 38 | 39 | 40 | )) 41 | AccordionTrigger.displayName = AccordionPrimitive.Trigger.displayName 42 | 43 | const AccordionContent = React.forwardRef< 44 | React.ElementRef, 45 | React.ComponentPropsWithoutRef 46 | >(({ className, children, ...props }, ref) => ( 47 | 52 |
{children}
53 |
54 | )) 55 | 56 | AccordionContent.displayName = AccordionPrimitive.Content.displayName 57 | 58 | export { Accordion, AccordionItem, AccordionTrigger, AccordionContent } 59 | -------------------------------------------------------------------------------- /v0-site/components/ui/alert-dialog.tsx: -------------------------------------------------------------------------------- 1 | "use client" 2 | 3 | import * as React from "react" 4 | import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog" 5 | 6 | import { cn } from "@/lib/utils" 7 | import { buttonVariants } from "@/components/ui/button" 8 | 9 | const AlertDialog = AlertDialogPrimitive.Root 10 | 11 | const AlertDialogTrigger = AlertDialogPrimitive.Trigger 12 | 13 | const AlertDialogPortal = AlertDialogPrimitive.Portal 14 | 15 | const AlertDialogOverlay = React.forwardRef< 16 | React.ElementRef, 17 | React.ComponentPropsWithoutRef 18 | >(({ className, ...props }, ref) => ( 19 | 27 | )) 28 | AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName 29 | 30 | const AlertDialogContent = React.forwardRef< 31 | React.ElementRef, 32 | React.ComponentPropsWithoutRef 33 | >(({ className, ...props }, ref) => ( 34 | 35 | 36 | 44 | 45 | )) 46 | AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName 47 | 48 | const AlertDialogHeader = ({ 49 | className, 50 | ...props 51 | }: React.HTMLAttributes) => ( 52 |
59 | ) 60 | AlertDialogHeader.displayName = "AlertDialogHeader" 61 | 62 | const AlertDialogFooter = ({ 63 | className, 64 | ...props 65 | }: React.HTMLAttributes) => ( 66 |
73 | ) 74 | AlertDialogFooter.displayName = "AlertDialogFooter" 75 | 76 | const AlertDialogTitle = React.forwardRef< 77 | React.ElementRef, 78 | React.ComponentPropsWithoutRef 79 | >(({ className, ...props }, ref) => ( 80 | 85 | )) 86 | AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName 87 | 88 | const AlertDialogDescription = React.forwardRef< 89 | React.ElementRef, 90 | React.ComponentPropsWithoutRef 91 | >(({ className, ...props }, ref) => ( 92 | 97 | )) 98 | AlertDialogDescription.displayName = 99 | AlertDialogPrimitive.Description.displayName 100 | 101 | const AlertDialogAction = React.forwardRef< 102 | React.ElementRef, 103 | React.ComponentPropsWithoutRef 104 | >(({ className, ...props }, ref) => ( 105 | 110 | )) 111 | AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName 112 | 113 | const AlertDialogCancel = React.forwardRef< 114 | React.ElementRef, 115 | React.ComponentPropsWithoutRef 116 | >(({ className, ...props }, ref) => ( 117 | 126 | )) 127 | AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName 128 | 129 | export { 130 | AlertDialog, 131 | AlertDialogPortal, 132 | AlertDialogOverlay, 133 | AlertDialogTrigger, 134 | AlertDialogContent, 135 | AlertDialogHeader, 136 | AlertDialogFooter, 137 | AlertDialogTitle, 138 | AlertDialogDescription, 139 | AlertDialogAction, 140 | AlertDialogCancel, 141 | } 142 | -------------------------------------------------------------------------------- /v0-site/components/ui/alert.tsx: -------------------------------------------------------------------------------- 1 | import * as React from "react" 2 | import { cva, type VariantProps } from "class-variance-authority" 3 | 4 | import { cn } from "@/lib/utils" 5 | 6 | const alertVariants = cva( 7 | "relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground", 8 | { 9 | variants: { 10 | variant: { 11 | default: "bg-background text-foreground", 12 | destructive: 13 | "border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive", 14 | }, 15 | }, 16 | defaultVariants: { 17 | variant: "default", 18 | }, 19 | } 20 | ) 21 | 22 | const Alert = React.forwardRef< 23 | HTMLDivElement, 24 | React.HTMLAttributes & VariantProps 25 | >(({ className, variant, ...props }, ref) => ( 26 |
32 | )) 33 | Alert.displayName = "Alert" 34 | 35 | const AlertTitle = React.forwardRef< 36 | HTMLParagraphElement, 37 | React.HTMLAttributes 38 | >(({ className, ...props }, ref) => ( 39 |
44 | )) 45 | AlertTitle.displayName = "AlertTitle" 46 | 47 | const AlertDescription = React.forwardRef< 48 | HTMLParagraphElement, 49 | React.HTMLAttributes 50 | >(({ className, ...props }, ref) => ( 51 |
56 | )) 57 | AlertDescription.displayName = "AlertDescription" 58 | 59 | export { Alert, AlertTitle, AlertDescription } 60 | -------------------------------------------------------------------------------- /v0-site/components/ui/aspect-ratio.tsx: -------------------------------------------------------------------------------- 1 | "use client" 2 | 3 | import * as AspectRatioPrimitive from "@radix-ui/react-aspect-ratio" 4 | 5 | const AspectRatio = AspectRatioPrimitive.Root 6 | 7 | export { AspectRatio } 8 | -------------------------------------------------------------------------------- /v0-site/components/ui/avatar.tsx: -------------------------------------------------------------------------------- 1 | "use client" 2 | 3 | import * as React from "react" 4 | import * as AvatarPrimitive from "@radix-ui/react-avatar" 5 | 6 | import { cn } from "@/lib/utils" 7 | 8 | const Avatar = React.forwardRef< 9 | React.ElementRef, 10 | React.ComponentPropsWithoutRef 11 | >(({ className, ...props }, ref) => ( 12 | 20 | )) 21 | Avatar.displayName = AvatarPrimitive.Root.displayName 22 | 23 | const AvatarImage = React.forwardRef< 24 | React.ElementRef, 25 | React.ComponentPropsWithoutRef 26 | >(({ className, ...props }, ref) => ( 27 | 32 | )) 33 | AvatarImage.displayName = AvatarPrimitive.Image.displayName 34 | 35 | const AvatarFallback = React.forwardRef< 36 | React.ElementRef, 37 | React.ComponentPropsWithoutRef 38 | >(({ className, ...props }, ref) => ( 39 | 47 | )) 48 | AvatarFallback.displayName = AvatarPrimitive.Fallback.displayName 49 | 50 | export { Avatar, AvatarImage, AvatarFallback } 51 | -------------------------------------------------------------------------------- /v0-site/components/ui/badge.tsx: -------------------------------------------------------------------------------- 1 | import * as React from "react" 2 | import { cva, type VariantProps } from "class-variance-authority" 3 | 4 | import { cn } from "@/lib/utils" 5 | 6 | const badgeVariants = cva( 7 | "inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2", 8 | { 9 | variants: { 10 | variant: { 11 | default: 12 | "border-transparent bg-primary text-primary-foreground hover:bg-primary/80", 13 | secondary: 14 | "border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80", 15 | destructive: 16 | "border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80", 17 | outline: "text-foreground", 18 | }, 19 | }, 20 | defaultVariants: { 21 | variant: "default", 22 | }, 23 | } 24 | ) 25 | 26 | export interface BadgeProps 27 | extends React.HTMLAttributes, 28 | VariantProps {} 29 | 30 | function Badge({ className, variant, ...props }: BadgeProps) { 31 | return ( 32 |
33 | ) 34 | } 35 | 36 | export { Badge, badgeVariants } 37 | -------------------------------------------------------------------------------- /v0-site/components/ui/breadcrumb.tsx: -------------------------------------------------------------------------------- 1 | import * as React from "react" 2 | import { Slot } from "@radix-ui/react-slot" 3 | import { ChevronRight, MoreHorizontal } from "lucide-react" 4 | 5 | import { cn } from "@/lib/utils" 6 | 7 | const Breadcrumb = React.forwardRef< 8 | HTMLElement, 9 | React.ComponentPropsWithoutRef<"nav"> & { 10 | separator?: React.ReactNode 11 | } 12 | >(({ ...props }, ref) =>