module a and b
|
Before Width: | Height: | Size: 165 KiB |
|
Before Width: | Height: | Size: 130 KiB |
@@ -1,141 +0,0 @@
|
||||
# 🏆 WSC2026 Test Project - Web Technologies
|
||||
## **Module D: AI-Powered Global City Explorer (Full-stack Integration)**
|
||||
|
||||
### **1. Project Overview**
|
||||
You are a full-stack developer for the 'Global City Explorer' platform. The internal AI Engineering team has developed an **'AI Middleware Server'** using local AI models (Ollama) to analyze text information and extract keywords from images. This has been provided to you as a Starter Kit.
|
||||
|
||||
Your task is to run the provided AI server, analyze its APIs, and build a sophisticated **Front-end (UI)** where administrators can create, read, update, and delete (CRUD) city information. Furthermore, you must develop a robust **Back-end (DB Storage)** that processes and securely stores the data only after it passes strict server-side validation.
|
||||
|
||||
---
|
||||
|
||||
### **2. Infrastructure Setup**
|
||||
Before beginning the task, you must ensure that your local PC meets the requirements to run the AI models and the Node.js server, and configure the environment accordingly.
|
||||
|
||||
#### **2.1. Hardware Requirements**
|
||||
To run the two AI models smoothly in a local environment, the following specifications are recommended:
|
||||
* **Memory (RAM):** Minimum 8GB / Recommended 16GB+ (Both models need to be loaded into memory).
|
||||
* **GPU:** NVIDIA GPU with 6GB+ VRAM recommended (CPU execution is possible, but image analysis processing time may be delayed).
|
||||
* **Storage:** Minimum 10GB of free space (SSD is highly recommended over HDD).
|
||||
|
||||
#### **2.2. Node.js Verification & Installation**
|
||||
A Node.js environment is required to run the back-end middleware.
|
||||
1. Open your terminal (or Command Prompt) and type `node -v` to check the installation. (A version of `v18.x.x` or higher is expected).
|
||||
2. **If not installed:** Visit the [Node.js official website (nodejs.org)](https://nodejs.org/), download the LTS (Long Term Support) version, and install it.
|
||||
|
||||
#### **2.3. Ollama (AI Engine) Verification & Installation**
|
||||
1. Open your terminal and type `ollama -v` to check the version.
|
||||
2. **If not installed:** On Windows, run **PowerShell** as an Administrator and paste the following command to install:
|
||||
`irm https://ollama.com/install.ps1 | iex`
|
||||
*(After installation, you must restart your terminal to apply the environment variables.)*
|
||||
|
||||
#### **2.4. AI Model Download & Characteristics**
|
||||
Open your terminal and run the following commands sequentially to download the two AI models used in this project. (Verify the installation using the `ollama list` command).
|
||||
|
||||
* **Download Text Processing Model:** `ollama pull phi3`
|
||||
* **[Model Characteristics]:** A Small Language Model (SLM) developed by Microsoft. It is lightweight and fast, possessing excellent text generation and logical reasoning capabilities, making it ideal for writing city introductions.
|
||||
* **Download Vision (Image) Processing Model:** `ollama pull llava`
|
||||
* **[Model Characteristics]:** A Multimodal AI equipped with 'Vision' capabilities alongside text. It analyzes uploaded landmark images to describe objects or scenery and extracts core keywords.
|
||||
|
||||
---
|
||||
|
||||
### **3. AI Middleware Server Setup & Execution**
|
||||
The provided Starter Kit contains an `ai-api` folder created by the AI engineering team. Inside, you will find `server.js` and `package.json`. **(🚨 NOTICE: Do NOT modify the code in this server under any circumstances.)**
|
||||
|
||||
1. Open a terminal and navigate to the provided `ai-api` folder directory.
|
||||
2. Enter the following command to install the required packages:
|
||||
`npm install`
|
||||
3. Once the installation is complete, start the server:
|
||||
`npm start`
|
||||
4. If the message `🚀 AI Middleware Server running on http://localhost:3000` appears in the terminal, the server is running correctly. Do not close this terminal until the competition module ends.
|
||||
|
||||
---
|
||||
|
||||
### **4. API Testing via HOPPSCOTCH**
|
||||
Before starting your development, you must use Hoppscotch (or Postman) to test the two provided APIs and understand the format of the data they return.
|
||||
|
||||
* **API 1: Text Information Generation (`POST /api/generate-text`)**
|
||||
* Body (`application/json`): `{"city_name": "Paris", "country": "France"}`
|
||||

|
||||
|
||||
* **API 2: Integrated Image Analysis (`POST /api/analyze-image`)**
|
||||
* Body (`multipart/form-data`): `city_name` (Text), `country` (Text), `image` (File type for image upload)
|
||||

|
||||
|
||||
---
|
||||
|
||||
### **5. Tasks to Complete**
|
||||
|
||||
#### **5.1. Front-end Requirements (Advanced UI/UX)**
|
||||
Build the `index.html` (or use an SPA framework) interface for administrators. The screen should be broadly divided into a **'Data Registration/Edit Area'** and a **'Registered List View Area'**.
|
||||
|
||||
* **[Data Registration & Edit Area (Form Area)]**
|
||||
* **Image Preview:** When an image is selected via `<input type="file">`, an image thumbnail must instantly appear on the screen as a preview before it is sent to the server.
|
||||
* **AI Data Integration:** Call the AI text generation API after entering the city/country name, and call the AI vision analysis API after uploading a photo. Populate the form with the returned data.
|
||||
* **Form Lock & Loading (Asynchronous State Management):** Because heavy AI analysis takes time (10~30 seconds), you must **disable** all input fields and buttons during the process to prevent duplicate clicks and user errors. Additionally, display a clear loading UI (spinner, progress bar, etc.) to optimize the User Experience.
|
||||
* **Edit Data & AI Re-fetch:**
|
||||
* Clicking an 'Edit' button on a specific city in the list should populate the form with that city's data.
|
||||
* The edit form must include a **'Re-fetch All Info from AI'** button. Clicking this button should trigger both AI APIs again based on the current city, country, and image in the form, entirely replacing the text values (description, keywords) with the newly generated AI response. The data will update in the DB only when the user clicks 'Final Update'.
|
||||
|
||||
* **[List View & Filtering Area (List & Interactive Filtering)]**
|
||||
* Fetch the globally saved city information from the DB and render it visually in a List or Card Gallery format. Each item must include an **'Edit'** and **'Delete'** button.
|
||||
* **Delete Data:** When the 'Delete' button is clicked, prevent accidental deletions by prompting the user with a browser native `confirm` dialog or a custom Modal. Upon confirmation, delete the data from the DB and immediately update the list.
|
||||
* **Hashtag Filtering:** Clicking a specific keyword (e.g., `#EiffelTower`) displayed in the list must instantly filter the entire list to show only the city cards that contain that keyword.
|
||||
|
||||
#### **5.2. Back-end Requirements (DB & Server-side Validation)**
|
||||
Construct your own back-end server and database to perfectly handle the Create, Read, Update, and Delete (CRUD) operations for your data.
|
||||
|
||||
* **DB Schema:** Design and create a `city_contents` table in MySQL/MariaDB.
|
||||
* **API Implementation (CRUD):**
|
||||
1. **GET (Read):** Returns all data saved in the DB in JSON format.
|
||||
2. **POST (Create):** `INSERT` new data into the DB and physically save the uploaded image to an upload folder.
|
||||
3. **PUT or PATCH (Update):** Updates data for a specific ID. (If a new image is submitted, you must replace the old image file or update the new file path).
|
||||
4. **DELETE (Delete):** Removes data for a specific ID from the DB.
|
||||
* **Server-side Validation (Security Check):** For POST and PUT/PATCH requests, ONLY data that passes the following validation checks should be saved to the server:
|
||||
1. **File Size Limit:** If the uploaded image exceeds **5MB**, the server must reject the request and return an error message along with HTTP status code 400 (Bad Request).
|
||||
2. **Extension Check:** The server must reject the upload if it is not an allowed image format (`.jpg`, `.jpeg`, `.png`, `.webp`).
|
||||
|
||||
#### **5.3. Additional Requirements (Pitfalls & Evaluation Points)**
|
||||
* **Data Parsing:** Within the Vision API's response, the `keywords` are not returned as a pure array, but as a **Stringified Array wrapped in JSON format**. To render these cleanly as individual tag UIs, the front-end MUST execute proper parsing (`JSON.parse`).
|
||||
* **Exception Handling:** If the back-end validation fails (e.g., File size exceeded), the front-end application must not crash. It must catch the error and clearly notify the user via an `alert` or Modal window.
|
||||
|
||||
---
|
||||
|
||||
### **6. Competitor Workspace Guide**
|
||||
|
||||
* **AI Middleware Execution Location:** The provided `ai-api` folder. (Run in Terminal 1 and leave it active).
|
||||
* **Competitor Workspace:** Your web server's root folder (e.g., `http://localhost/module-d/`).
|
||||
* **Evaluation Preparation:** At the end of the module, both the AI Middleware terminal and the web server you created must be running. Experts will connect via browser and sequentially test the following cycle:
|
||||
1. Attempt to upload an image exceeding 5MB (Check Error Handling)
|
||||
2. Normal data generation (Create)
|
||||
3. List view and Hashtag click filtering (Read & Filter)
|
||||
4. **Click 'Edit', 'Re-fetch from AI' to renew contents, and Save (Update)**
|
||||
5. **Click 'Delete' to permanently erase data (Delete)**
|
||||
|
||||
---
|
||||
|
||||
### **7. Appendix: Sample Data**
|
||||
Utilize the city/country list below for testing and final demonstration. **Recommended landmark images for testing are provided in the `sample-images` folder inside the Starter Kit.** (Prepare at least one high-resolution image larger than 5MB to test your back-end defense logic).
|
||||
|
||||
| City Name | Country Name | Landmark |
|
||||
| :--- | :--- | :--- |
|
||||
| **Paris** | France | Eiffel Tower, Louvre Museum |
|
||||
| **Seoul** | South Korea | Gyeongbokgung, N Seoul Tower |
|
||||
| **Tokyo** | Japan | Tokyo Tower, Shibuya Crossing |
|
||||
| **New York** | USA | Statue of Liberty, Times Square |
|
||||
| **Rome** | Italy | Colosseum, Trevi Fountain |
|
||||
| **Sydney** | Australia | Opera House, Harbour Bridge |
|
||||
| **Cairo** | Egypt | Pyramids of Giza, Sphinx |
|
||||
| **London** | UK | Big Ben, London Eye |
|
||||
|
||||
---
|
||||
|
||||
### **8. Mark Summary (Total: 25 Marks)**
|
||||
This table provides a summary of the points allocated per evaluation category. A detailed Marking Scheme will be provided separately.
|
||||
|
||||
| Category | Description | Max Marks |
|
||||
| :--- | :--- | :---: |
|
||||
| **A. Front-end UI & UX** | UI composition, Async state management (Loading/Locking), Data binding & Parsing | 7 |
|
||||
| **B. Data Interaction** | Data list rendering and Hashtag-based filtering functionality | 5 |
|
||||
| **C. Back-end CRUD API** | DB & File System Create, Read, Update (including AI Re-fetch), and Delete operations | 8 |
|
||||
| **D. Security & Validation**| Server-side file size/extension validation, Client-side exception handling | 5 |
|
||||
| **Total Marks** | | **25** |
|
||||
@@ -1,141 +0,0 @@
|
||||
# 🏆 WSC2026 Test Project - Web Technologies
|
||||
## **Module D: AI-Powered Global City Explorer (Full-stack Integration)**
|
||||
|
||||
### **1. 과제 개요 (Project Overview)**
|
||||
당신은 'Global City Explorer' 플랫폼의 풀스택 개발자입니다. 사내 AI 엔지니어링 팀이 로컬 AI 모델(Ollama)을 활용하여 도시의 텍스트 정보와 이미지의 키워드를 분석해 주는 **'AI 마이크로서비스(AI Middleware Server)'**를 개발하여 Starter Kit으로 제공했습니다.
|
||||
|
||||
당신의 임무는 제공된 AI 서버를 구동하고 API를 명확히 분석한 뒤, 관리자가 도시 정보를 등록, 조회, **수정 및 삭제(CRUD)** 할 수 있는 고도화된 **프론트엔드(UI)**와 엄격한 유효성 검사를 통과한 데이터만 안전하게 처리하는 **백엔드(DB Storage)**를 완벽하게 구축하는 것입니다.
|
||||
|
||||
---
|
||||
|
||||
### **2. 인프라 구축 방법 (Infrastructure Setup)**
|
||||
과제를 수행하기 전, 로컬 PC가 AI 모델과 Node.js 서버를 구동하기 위한 요구사항을 충족하는지 확인하고 환경을 세팅해야 합니다.
|
||||
|
||||
#### **2.1. 하드웨어 권장 사양 (Hardware Requirements)**
|
||||
로컬 환경에서 두 개의 AI 모델을 원활하게 구동하기 위해 아래 사양을 권장합니다.
|
||||
* **Memory (RAM):** 최소 8GB / 권장 16GB 이상 (두 모델이 메모리에 적재되어야 하므로 RAM 용량이 중요합니다.)
|
||||
* **GPU:** VRAM 6GB 이상의 NVIDIA GPU 권장 (CPU로도 구동은 가능하나, 이미지 분석 시 처리 시간이 다소 지연될 수 있습니다.)
|
||||
* **Storage:** 최소 10GB 이상의 여유 공간 (HDD보다 SSD 사용을 강력히 권장합니다.)
|
||||
|
||||
#### **2.2. Node.js 확인 및 설치**
|
||||
백엔드 미들웨어를 실행하기 위해 Node.js 환경이 필요합니다.
|
||||
1. 터미널(또는 명령 프롬프트)을 열고 `node -v`를 입력하여 설치 여부를 확인합니다. (`v18.x.x` 이상의 버전이 표출되면 정상입니다.)
|
||||
2. **미설치 시:** [Node.js 공식 홈페이지(nodejs.org)](https://nodejs.org/)에 접속하여 LTS(Long Term Support) 버전을 다운로드하고 설치하십시오.
|
||||
|
||||
#### **2.3. Ollama (AI 구동 엔진) 확인 및 설치**
|
||||
1. 터미널을 열고 `ollama -v`를 입력하여 버전 정보가 나오는지 확인합니다.
|
||||
2. **미설치 시:** Windows의 경우 **PowerShell**을 관리자 권한으로 실행한 뒤, 아래 명령어를 붙여넣어 설치를 진행하십시오.
|
||||
`irm https://ollama.com/install.ps1 | iex`
|
||||
*(설치가 완료되면 터미널을 재시작해야 환경변수가 적용됩니다.)*
|
||||
|
||||
#### **2.4. AI 모델 다운로드 및 특징**
|
||||
터미널을 열고 아래 명령어를 순차적으로 실행하여 본 과제에 사용할 2개의 AI 모델을 다운로드합니다. (`ollama list` 명령어로 설치 완료 확인)
|
||||
|
||||
* **텍스트 처리 모델 다운로드:** `ollama pull phi3`
|
||||
* **[모델 특징]:** Microsoft에서 개발한 초경량 언어 모델(SLM)입니다. 가볍고 빠르면서도 훌륭한 문장 생성 및 논리적 추론 능력을 갖추고 있어 도시의 소개글을 작성하는 데 사용됩니다.
|
||||
* **비전(이미지) 처리 모델 다운로드:** `ollama pull llava`
|
||||
* **[모델 특징]:** 텍스트뿐만 아니라 '눈(Vision)'을 가진 멀티모달(Multimodal) AI입니다. 사용자가 업로드한 명소 이미지를 분석하여 그 안의 객체나 풍경을 설명하고 핵심 키워드를 추출하는 역할을 합니다.
|
||||
|
||||
---
|
||||
|
||||
### **3. AI Middleware Server 설치 및 실행**
|
||||
제공된 Starter Kit 안에는 AI 엔지니어링 팀이 작성한 `ai-api` 폴더가 있습니다. 이 폴더 안에는 `server.js`와 `package.json`이 포함되어 있습니다. **(🚨 주의: 이 서버의 코드는 절대 수정하지 마십시오.)**
|
||||
|
||||
1. 터미널을 열고 제공된 `ai-api` 폴더 경로로 이동합니다.
|
||||
2. 아래 명령어를 입력하여 필수 패키지를 설치합니다.
|
||||
`npm install`
|
||||
3. 설치가 완료되면 서버를 실행합니다.
|
||||
`npm start`
|
||||
4. 터미널에 `🚀 AI Middleware Server running on http://localhost:3000` 메시지가 출력되면 서버가 정상 작동 중인 것입니다. 이 터미널은 과제가 끝날 때까지 닫지 마십시오.
|
||||
|
||||
---
|
||||
|
||||
### **4. HOPPSCOTCH를 활용한 API 테스트**
|
||||
본격적인 개발에 앞서, Hoppscotch(또는 Postman)를 이용하여 제공된 두 개의 API가 어떤 형태의 데이터를 반환하는지 반드시 테스트하십시오.
|
||||
|
||||
* **API 1: 텍스트 정보 생성 (`POST /api/generate-text`)**
|
||||
* Body (`application/json`): `{"city_name": "Paris", "country": "France"}`
|
||||

|
||||
|
||||
* **API 2: 이미지 통합 분석 (`POST /api/analyze-image`)**
|
||||
* Body (`multipart/form-data`): `city_name` (Text), `country` (Text), `image` (File 형식으로 이미지 업로드)
|
||||

|
||||
|
||||
---
|
||||
|
||||
### **5. 선수들이 만들어야 할 과제 (Tasks to Complete)**
|
||||
|
||||
#### **5.1. Front-end 요구사항 (Advanced UI/UX)**
|
||||
관리자가 사용할 `index.html` (또는 SPA 프레임워크) 화면을 구축하십시오. 화면은 크게 **'정보 등록/수정 영역'**과 **'등록된 목록 조회 영역'**으로 나뉘어야 합니다.
|
||||
|
||||
* **[정보 등록 및 수정 영역 (Form Area)]**
|
||||
* **이미지 미리보기 (Image Preview):** `<input type="file">`을 통해 이미지를 선택하면, 서버에 전송하기 전 화면에 즉시 이미지 썸네일이 미리보기로 표시되어야 합니다.
|
||||
* **AI 데이터 연동:** 도시명/국가명 입력 후 AI 텍스트 생성 API를 호출하고, 사진 등록 후 AI 비전 분석 API를 호출하여 반환된 데이터를 폼(Form)에 채우십시오.
|
||||
* **완벽한 비동기 상태 관리 (Form Lock & Loading):** 무거운 AI 분석 작업(10~30초 소요)이 진행되는 동안 사용자의 중복 클릭 및 오류를 방지하기 위해 **모든 입력 폼과 버튼을 비활성화(Disabled)** 처리해야 합니다. 또한 작업 진행 상태를 명확히 알 수 있는 로딩 UI(스피너 애니메이션, 프로그레스 바 등)를 화면에 표시하여 사용자 경험을 최적화하십시오.
|
||||
* **정보 수정 및 AI 다시 불러오기 (Re-fetch):**
|
||||
* 목록에서 특정 도시의 '수정' 버튼을 누르면 해당 도시의 데이터가 폼에 채워져야 합니다.
|
||||
* 수정 폼에는 **'AI에서 모든 정보 다시 불러오기'** 버튼이 있어야 합니다. 이 버튼을 클릭하면 현재 폼에 있는 도시, 국가, 이미지 데이터를 바탕으로 AI API 두 개를 다시 호출하고, 폼의 텍스트 값들(설명, 키워드 등)을 완전히 새로운 AI 응답으로 교체해야 합니다. 이후 사용자가 '최종 수정' 버튼을 누르면 업데이트됩니다.
|
||||
|
||||
* **[목록 조회 및 필터링 영역 (List & Interactive Filtering)]**
|
||||
* 최종 저장된 글로벌 도시 정보들을 DB에서 불러와 리스트(List) 또는 카드(Card) 갤러리 형태로 렌더링하십시오. 각 아이템에는 **'수정(Edit)'** 및 **'삭제(Delete)'** 버튼이 포함되어야 합니다.
|
||||
* **데이터 삭제 (Delete):** '삭제' 버튼 클릭 시, 실수로 삭제하는 것을 방지하기 위해 브라우저의 기본 `confirm` 창이나 커스텀 모달(Modal) 창으로 확인을 거친 후 DB에서 데이터를 삭제하고 목록을 즉시 갱신하십시오.
|
||||
* **해시태그 필터링:** 목록에 표시된 특정 키워드(예: `#에펠탑`)를 클릭하면, 전체 목록이 즉시 필터링되어 해당 키워드를 보유한 도시 카드들만 화면에 노출되어야 합니다.
|
||||
|
||||
#### **5.2. Back-end 요구사항 (DB 및 Server-side Validation)**
|
||||
데이터의 생성(Create), 조회(Read), 수정(Update), 삭제(Delete)를 완벽하게 처리하는 본인만의 백엔드 서버와 데이터베이스를 구축하십시오.
|
||||
|
||||
* **DB 스키마:** MySQL/MariaDB에 `city_contents` 테이블을 직접 설계하여 생성하십시오.
|
||||
* **API 구현 (CRUD):**
|
||||
1. **GET (조회):** DB에 저장된 전체 데이터를 JSON 형태로 반환합니다.
|
||||
2. **POST (생성):** 새로운 데이터를 DB에 `INSERT` 하고 이미지를 업로드 폴더에 물리적으로 저장합니다.
|
||||
3. **PUT 또는 PATCH (수정):** 특정 ID의 데이터를 수정합니다. (새로운 이미지가 전송되었다면 기존 이미지 파일을 교체하거나 새로운 경로를 업데이트해야 합니다.)
|
||||
4. **DELETE (삭제):** 특정 ID의 데이터를 DB에서 삭제합니다.
|
||||
* **저장/수정 로직의 보안 검사 (Server-side Validation):** POST 및 PUT/PATCH 요청 시, 아래의 유효성 검사를 반드시 통과한 데이터만 서버에 저장해야 합니다.
|
||||
1. **파일 용량 제한:** 업로드된 이미지 파일이 **5MB**를 초과할 경우 처리를 거부하고 HTTP 상태 코드 400(Bad Request)과 함께 에러 메시지를 반환해야 합니다.
|
||||
2. **확장자 검사:** 허용된 이미지 포맷(`.jpg`, `.jpeg`, `.png`, `.webp`)이 아닐 경우 저장을 거부해야 합니다.
|
||||
|
||||
#### **5.3. 기타 요구사항 (함정 및 평가 포인트)**
|
||||
* **데이터 파싱(Parsing):** 비전 API의 응답 중 `keywords`는 순수 배열이 아닌 **JSON 포맷으로 감싸진 텍스트 문자열(Stringified Array)**로 반환됩니다. 이를 화면에 깔끔한 태그로 렌더링하기 위해 프론트엔드에서 반드시 적절한 파싱(`JSON.parse`) 과정을 거쳐야 합니다.
|
||||
* **예외 처리:** 백엔드 유효성 검사 실패 시(예: 용량 초과) 프론트엔드 프로그램이 멈추지 않고, 캐치(Catch)하여 사용자에게 `alert` 또는 모달 창으로 명확히 안내해야 합니다.
|
||||
|
||||
---
|
||||
|
||||
### **6. 선수 작업 안내 (Competitor Workspace Guide)**
|
||||
|
||||
* **AI Middleware 실행 위치:** 제공된 `ai-api` 폴더. (터미널 1에서 실행 후 방치)
|
||||
* **선수 작업 위치:** 본인의 웹 서버 루트 폴더(예: `http://localhost/module-d/`).
|
||||
* **평가 준비:** 과제 종료 시점에는 AI Middleware 터미널과 선수가 작성한 웹 서버가 모두 실행 중이어야 합니다. 심사위원(Expert)은 브라우저를 통해 접속하여 아래 사이클을 순차적으로 테스트할 것입니다.
|
||||
1. 5MB 초과 이미지 업로드 시도 (에러 처리 확인)
|
||||
2. 정상 데이터 생성 (Create)
|
||||
3. 목록 조회 및 해시태그 클릭 필터링 (Read & Filter)
|
||||
4. **'수정' 버튼 클릭 후 'AI 다시 불러오기'를 통한 내용 갱신 및 저장 (Update)**
|
||||
5. **'삭제' 버튼 클릭을 통한 데이터 완전 삭제 (Delete)**
|
||||
|
||||
---
|
||||
|
||||
### **7. Appendix: 테스트용 제공 데이터 (Sample Data)**
|
||||
테스트 및 최종 시연을 위해 아래의 도시/국가 목록을 활용하십시오. **과제 테스트용 명소 이미지는 제공된 Starter Kit 내의 `sample-images` 폴더에 준비되어 있습니다.** (특히 5MB가 넘는 고해상도 이미지를 하나 준비하여 백엔드 방어 로직을 테스트하십시오.)
|
||||
|
||||
| 도시명 (City) | 국가명 (Country) | 대표 명소 |
|
||||
| :--- | :--- | :--- |
|
||||
| **Paris** | France | 에펠탑, 루브르 박물관 |
|
||||
| **Seoul** | South Korea | 경복궁, N서울타워 |
|
||||
| **Tokyo** | Japan | 도쿄 타워, 시부야 교차로 |
|
||||
| **New York** | USA | 자유의 여신상, 타임스퀘어 |
|
||||
| **Rome** | Italy | 콜로세움, 트레비 분수 |
|
||||
| **Sydney** | Australia | 오페라 하우스, 하버 브릿지 |
|
||||
| **Cairo** | Egypt | 기자 피라미드, 스핑크스 |
|
||||
| **London** | UK | 빅 벤, 런던 아이 |
|
||||
|
||||
---
|
||||
|
||||
### **8. Mark Summary (채점 요약표 - Total 25 Marks)**
|
||||
이 표는 평가 카테고리별 배점 요약입니다. 세부 채점 기준(Marking Scheme)은 별도로 제공됩니다.
|
||||
|
||||
| Category | Description | Max Marks |
|
||||
| :--- | :--- | :---: |
|
||||
| **A. Front-end UI & UX** | UI 구성, 비동기 상태 관리(로딩/잠금), 데이터 바인딩 및 파싱 처리 | 7 |
|
||||
| **B. Data Interaction** | 데이터 목록 렌더링 및 해시태그 기반 필터링 기능 | 5 |
|
||||
| **C. Back-end CRUD API** | 데이터베이스 및 파일 시스템 기반의 생성, 조회, 수정(AI 다시 불러오기 포함), 삭제 기능 | 8 |
|
||||
| **D. Security & Validation**| 서버 측 파일 용량 및 확장자 검사, 클라이언트 측 예외 처리 | 5 |
|
||||
| **Total Marks** | | **25** |
|
||||
@@ -1,141 +0,0 @@
|
||||
# 🏆 WSC2026 Test Project - Veb Texnologiyalar
|
||||
## **D Moduli: AI yordamida ishlaydigan Global City Explorer (Full-stack Integratsiya)**
|
||||
|
||||
### **1. Loyiha haqida umumiy ma'lumot (Project Overview)**
|
||||
Siz 'Global City Explorer' platformasining full-stack dasturchisisiz. Ichki AI muhandislik jamoasi matnli ma'lumotlarni tahlil qilish va rasmlardan kalit so'zlarni ajratib olish uchun mahalliy AI modellaridan (Ollama) foydalanadigan **'AI Middleware Server'** ni (AI Oraliq Serveri) ishlab chiqdi. Bu sizga Starter Kit (Boshlang'ich to'plam) sifatida taqdim etilgan.
|
||||
|
||||
Sizning vazifangiz taqdim etilgan AI serverini ishga tushirish, uning API'larini tahlil qilish va administratorlar shahar ma'lumotlarini yaratishi, o'qishi, yangilashi va o'chirishi (CRUD) mumkin bo'lgan mukammal **Front-end (UI)** yaratishdir. Bundan tashqari, ma'lumotlarni faqat qat'iy server tekshiruvidan (server-side validation) o'tgandan keyingina qayta ishlaydigan va xavfsiz saqlaydigan kuchli **Back-end (DB Storage)** ni ishlab chiqishingiz kerak.
|
||||
|
||||
---
|
||||
|
||||
### **2. Infratuzilmani sozlash (Infrastructure Setup)**
|
||||
Vazifani boshlashdan oldin, shaxsiy kompyuteringiz AI modellari va Node.js serverini ishga tushirish talablariga javob berishiga ishonch hosil qilishingiz va atrof-muhitni shunga mos ravishda sozlashingiz kerak.
|
||||
|
||||
#### **2.1. Uskuna talablari (Hardware Requirements)**
|
||||
Mahalliy muhitda ikkita AI modelini uzluksiz ishga tushirish uchun quyidagi xususiyatlar tavsiya etiladi:
|
||||
* **Xotira (RAM):** Kamida 8GB / Tavsiya etiladi 16GB+ (Ikkala model ham xotiraga yuklanishi kerak).
|
||||
* **GPU:** 6GB+ VRAM'ga ega NVIDIA GPU tavsiya etiladi (CPU orqali ishlash ham mumkin, lekin tasvirni tahlil qilish vaqti kechikishi mumkin).
|
||||
* **Disk hajmi (Storage):** Kamida 10GB bo'sh joy (HDD dan ko'ra SSD dan foydalanish qat'iy tavsiya etiladi).
|
||||
|
||||
#### **2.2. Node.js'ni tekshirish va o'rnatish**
|
||||
Back-end oraliq dasturini (middleware) ishga tushirish uchun Node.js muhiti talab qilinadi.
|
||||
1. Terminalni (yoki Command Prompt) oching va o'rnatilganligini tekshirish uchun `node -v` deb yozing. (`v18.x.x` yoki undan yuqori versiya chiqishi kutiladi).
|
||||
2. **Agar o'rnatilmagan bo'lsa:** [Node.js rasmiy veb-saytiga (nodejs.org)](https://nodejs.org/) kiring, LTS (Long Term Support) versiyasini yuklab oling va o'rnating.
|
||||
|
||||
#### **2.3. Ollama (AI Dvigateli) ni tekshirish va o'rnatish**
|
||||
1. Terminalni oching va versiyani tekshirish uchun `ollama -v` deb yozing.
|
||||
2. **Agar o'rnatilmagan bo'lsa:** Windows tizimida **PowerShell**'ni Administrator sifatida ishga tushiring va o'rnatish uchun quyidagi buyruqni kiriting:
|
||||
`irm https://ollama.com/install.ps1 | iex`
|
||||
*(O'rnatish tugagandan so'ng, muhit o'zgaruvchilari (environment variables) qo'llanilishi uchun terminalni qayta ishga tushirishingiz kerak.)*
|
||||
|
||||
#### **2.4. AI modellarini yuklab olish va ularning xususiyatlari**
|
||||
Ushbu loyihada foydalaniladigan ikkita AI modelini yuklab olish uchun terminalni oching va quyidagi buyruqlarni ketma-ket bajaring. (O'rnatish muvaffaqiyatli bo'lganini `ollama list` buyrug'i orqali tekshiring).
|
||||
|
||||
* **Matnni qayta ishlash modelini yuklab olish:** `ollama pull phi3`
|
||||
* **[Model xususiyatlari]:** Microsoft tomonidan ishlab chiqilgan Kichik Til Modeli (SLM - Small Language Model). U yengil va tez bo'lib, mukammal matn yaratish va mantiqiy fikrlash qobiliyatiga ega. Bu uni shahar haqida qisqacha ma'lumot yozish uchun ideal qiladi.
|
||||
* **Ko'rish (Tasvir) ni qayta ishlash modelini yuklab olish:** `ollama pull llava`
|
||||
* **[Model xususiyatlari]:** Matn bilan bir qatorda 'Ko'rish' (Vision) imkoniyatlari bilan jihozlangan Multimodal AI. U foydalanuvchi tomonidan yuklangan diqqatga sazovor joylar tasvirlarini tahlil qilib, ob'ektlar yoki manzaralarni tasvirlaydi va asosiy kalit so'zlarni (keywords) ajratib oladi.
|
||||
|
||||
---
|
||||
|
||||
### **3. AI Middleware Serverni o'rnatish va ishga tushirish**
|
||||
Taqdim etilgan Starter Kit ichida AI muhandislik jamoasi tomonidan yaratilgan `ai-api` papkasi mavjud. Uning ichida `server.js` va `package.json` fayllarini topasiz. **(🚨 DIQQAT: Hech qanday holatda ushbu server kodini o'zgartirmang.)**
|
||||
|
||||
1. Terminalni oching va taqdim etilgan `ai-api` papkasi katalogiga o'ting.
|
||||
2. Kerakli paketlarni o'rnatish uchun quyidagi buyruqni kiriting:
|
||||
`npm install`
|
||||
3. O'rnatish tugagach, serverni ishga tushiring:
|
||||
`npm start`
|
||||
4. Agar terminalda `🚀 AI Middleware Server running on http://localhost:3000` xabari paydo bo'lsa, server to'g'ri ishlamoqda. Musobaqa moduli tugamaguncha bu terminalni yopmang.
|
||||
|
||||
---
|
||||
|
||||
### **4. HOPPSCOTCH orqali API test qilish**
|
||||
Dasturlashni boshlashdan oldin, taqdim etilgan ikkita API qanday formatdagi ma'lumotlarni qaytarishini tushunish va test qilish uchun Hoppscotch (yoki Postman) dan foydalanishingiz SHART.
|
||||
|
||||
* **1-API: Matn ma'lumotlarini yaratish (`POST /api/generate-text`)**
|
||||
* Body (`application/json`): `{"city_name": "Paris", "country": "France"}`
|
||||

|
||||
|
||||
* **2-API: Tasvirni kompleks tahlil qilish (`POST /api/analyze-image`)**
|
||||
* Body (`multipart/form-data`): `city_name` (Text), `country` (Text), `image` (Rasm yuklash uchun File formati)
|
||||

|
||||
|
||||
---
|
||||
|
||||
### **5. Bajarilishi kerak bo'lgan vazifalar (Tasks to Complete)**
|
||||
|
||||
#### **5.1. Front-end talablari (Kengaytirilgan UI/UX)**
|
||||
Administratorlar uchun `index.html` (yoki SPA framework) interfeysini yarating. Ekran asosan **'Ma'lumotlarni ro'yxatdan o'tkazish/Tahrirlash hududi'** va **'Ro'yxatga olinganlarni ko'rish hududi'** ga bo'linishi kerak.
|
||||
|
||||
* **[Ma'lumotlarni ro'yxatdan o'tkazish va tahrirlash hududi (Form Area)]**
|
||||
* **Tasvirni oldindan ko'rish (Image Preview):** `<input type="file">` orqali rasm tanlanganda, u serverga yuborilishidan oldin ekranda rasm eskizi (thumbnail) darhol paydo bo'lishi kerak.
|
||||
* **AI ma'lumotlar integratsiyasi:** Shahar/davlat nomini kiritgandan so'ng AI matn yaratish API'sini chaqiring va rasm yuklangandan so'ng AI vizual tahlil API'sini chaqiring. Qaytarilgan ma'lumotlar bilan formani to'ldiring.
|
||||
* **Formani qulflash va yuklanish (Asynchronous State Management):** Og'ir AI tahlili biroz vaqt (10~30 soniya) talab qilganligi sababli, jarayon davomida foydalanuvchi qayta-qayta bosishining va xatoliklarning oldini olish uchun barcha kiritish maydonlari (input fields) va tugmalarni **qulflashingiz (disabled)** kerak. Bundan tashqari, foydalanuvchi tajribasini (UX) optimallashtirish uchun aniq yuklanish UI elementini (spinner, progress bar va hk.) ko'rsating.
|
||||
* **Ma'lumotlarni tahrirlash va AI'dan qayta yuklash (Re-fetch):**
|
||||
* Ro'yxatdagi ma'lum bir shahar uchun 'Tahrirlash' (Edit) tugmachasini bosish, formani o'sha shaharning ma'lumotlari bilan to'ldirishi kerak.
|
||||
* Tahrirlash formasi **'Barcha ma'lumotlarni AI'dan qayta yuklash'** tugmasini o'z ichiga olishi kerak. Ushbu tugmani bosish formadagi joriy shahar, davlat va rasmga asoslanib, ikkala AI API'sini ham qayta ishga tushirishi va matn qiymatlarini (tavsif, kalit so'zlar) butunlay yangi AI javobi bilan almashtirishi kerak. Foydalanuvchi 'Yakuniy saqlash' ni bosganidagina ma'lumotlar DB'da yangilanadi.
|
||||
|
||||
* **[Ro'yxatni ko'rish va filtrlash hududi (List & Interactive Filtering)]**
|
||||
* Butun dunyo bo'ylab saqlangan shahar ma'lumotlarini DB'dan oling va uni vizual ravishda Ro'yxat (List) yoki Kartalar Galereyasi (Card Gallery) formatida ko'rsating. Har bir elementda **'Tahrirlash' (Edit)** va **'O'chirish' (Delete)** tugmalari bo'lishi kerak.
|
||||
* **Ma'lumotlarni o'chirish (Delete):** 'O'chirish' tugmasi bosilganda, tasodifan o'chirib yuborishning oldini olish uchun brauzerning standart `confirm` oynasi yoki maxsus Modal orqali foydalanuvchidan tasdiqlashni so'rang. Tasdiqlangandan so'ng, ma'lumotlarni DB'dan o'chiring va ro'yxatni darhol yangilang.
|
||||
* **Heshteg orqali filtrlash:** Ro'yxatda ko'rsatilgan ma'lum bir kalit so'zni (masalan, `#EiffelTower`) bosish orqali darhol butun ro'yxat filtrlari ishga tushishi va faqat o'sha kalit so'zni o'z ichiga olgan shahar kartalarigina ko'rsatilishi kerak.
|
||||
|
||||
#### **5.2. Back-end talablari (DB va Server tomonida tekshirish)**
|
||||
Ma'lumotlaringizni Yaratish, O'qish, Yangilash va O'chirish (CRUD - Create, Read, Update, Delete) operatsiyalarini mukammal bajarish uchun shaxsiy back-end serveringiz va ma'lumotlar bazasini yarating.
|
||||
|
||||
* **DB Sxemasi:** MySQL/MariaDB da `city_contents` jadvalini loyihalashtiring va yarating.
|
||||
* **API ilovasi (CRUD):**
|
||||
1. **GET (O'qish):** DB'da saqlangan barcha ma'lumotlarni JSON formatida qaytaradi.
|
||||
2. **POST (Yaratish):** DB'ga yangi ma'lumotlarni `INSERT` qiladi va yuklangan rasmni jismoniy jihatdan yuklash (uploads) papkasiga saqlaydi.
|
||||
3. **PUT yoki PATCH (Yangilash):** Muayyan ID uchun ma'lumotlarni yangilaydi. (Agar yangi rasm yuborilsa, eski rasm faylini almashtirishingiz yoki yangi fayl yo'lini yangilashingiz kerak).
|
||||
4. **DELETE (O'chirish):** Muayyan ID uchun ma'lumotlarni DB'dan o'chiradi.
|
||||
* **Server tomonida tekshirish (Xavfsizlikni tekshirish):** POST va PUT/PATCH so'rovlari uchun FAQAT quyidagi tekshiruvlardan o'tgan ma'lumotlargina serverga saqlanishi kerak:
|
||||
1. **Fayl hajmi chegarasi:** Agar yuklangan rasm **5MB** dan oshsa, server so'rovni rad etishi va 400 HTTP status kodi (Bad Request) bilan birga xatolik xabarini qaytarishi kerak.
|
||||
2. **Kengaytmani tekshirish:** Agar rasm ruxsat etilgan formatda bo'lmasa (`.jpg`, `.jpeg`, `.png`, `.webp`), server yuklashni rad etishi kerak.
|
||||
|
||||
#### **5.3. Qo'shimcha talablar (Xatolar va baholash mezonlari)**
|
||||
* **Ma'lumotlarni tahlil qilish (Data Parsing):** Vision API javobida `keywords` toza massiv (array) sifatida emas, balki **JSON formatida o'ralgan matnli massiv (Stringified Array)** sifatida qaytariladi. Ularni toza va alohida teg UI sifatida ko'rsatish uchun front-end albatta to'g'ri tahlil qilish (parsing - `JSON.parse`) ni amalga oshirishi SHART.
|
||||
* **Istisnolarni ko'rib chiqish (Exception Handling):** Agar back-end tekshiruvi muvaffaqiyatsiz bo'lsa (masalan, Fayl hajmi oshib ketdi), front-end ilovasi buzilmasligi (crash) kerak. U xatoni ushlab olishi (catch) va foydalanuvchini `alert` yoki Modal oyna orqali aniq xabardor qilishi kerak.
|
||||
|
||||
---
|
||||
|
||||
### **6. Ishtirokchi ish stoli bo'yicha qo'llanma (Competitor Workspace Guide)**
|
||||
|
||||
* **AI Middleware ishga tushirish joyi:** Taqdim etilgan `ai-api` papkasi. (1-Terminalda ishga tushiring va uni ochiq qoldiring).
|
||||
* **Ishtirokchi ish stoli:** Sizning veb-serveringizning asosiy(root) papkasi (masalan, `http://localhost/module-d/`).
|
||||
* **Baholashga tayyorgarlik:** Modul oxirida AI Middleware terminali ham, siz yaratgan veb-server ham ishlab turgan bo'lishi kerak. Ekspertlar brauzer orqali ulanadi va quyidagi siklni ketma-ket sinab ko'radi:
|
||||
1. 5MB dan katta hajmdagi rasmni yuklashga urinish (Xatoni ushlab qolishni tekshirish)
|
||||
2. Oddiy ma'lumotlarni yaratish (Create)
|
||||
3. Ro'yxatni ko'rish va heshtegni bosish orqali filtrlash (Read & Filter)
|
||||
4. **'Tahrirlash' tugmasini bosish, 'AI'dan qayta yuklash' orqali tarkibni yangilash va Saqlash (Update)**
|
||||
5. **Ma'lumotni butunlay yo'q qilish uchun 'O'chirish' tugmasini bosish (Delete)**
|
||||
|
||||
---
|
||||
|
||||
### **7. Ilova: Namuna ma'lumotlar (Sample Data)**
|
||||
Test qilish va yakuniy namoyish uchun quyidagi shahar/davlat ro'yxatidan foydalaning. **Test qilish uchun tavsiya etilgan diqqatga sazovor joylarning rasmlari Starter Kit ichidagi `sample-images` papkasida taqdim etilgan.** (Back-end himoya mantiqini sinab ko'rish uchun kamida bitta 5MB dan katta yuqori aniqlikdagi rasmni tayyorlab qo'ying).
|
||||
|
||||
| Shahar nomi | Davlat nomi | Diqqatga sazovor joy (Landmark) |
|
||||
| :--- | :--- | :--- |
|
||||
| **Paris** | France | Eyfel minorasi, Luvr muzeyi |
|
||||
| **Seoul** | South Korea | Kyonbokkun saroyi, N Seul minorasi |
|
||||
| **Tokyo** | Japan | Tokio minorasi, Shibuya chorrahasi |
|
||||
| **New York** | USA | Ozodlik haykali, Tayms maydoni |
|
||||
| **Rome** | Italy | Kolizey, Trevi favvorasi |
|
||||
| **Sydney** | Australia | Opera teatri, Harbor ko'prigi |
|
||||
| **Cairo** | Egypt | Giza piramidalari, Sfinks |
|
||||
| **London** | UK | Big Ben, London ko'zi |
|
||||
|
||||
---
|
||||
|
||||
### **8. Baholash xulosasi (Mark Summary - Jami 25 ball)**
|
||||
Ushbu jadval baholash toifalari bo'yicha ajratilgan ballar xulosasini beradi. Batafsil baholash sxemasi (Marking Scheme) alohida taqdim etiladi.
|
||||
|
||||
| Toifa (Category) | Tavsif (Description) | Maksimal Ball |
|
||||
| :--- | :--- | :---: |
|
||||
| **A. Front-end UI & UX** | UI tuzilishi, Asinxron holatni boshqarish (Yuklash/Qulflash), Ma'lumotlarni ulash (Binding) va Tahlil qilish (Parsing) | 7 |
|
||||
| **B. Data Interaction** | Ma'lumotlar ro'yxatini ko'rsatish (rendering) va Heshtegga asoslangan filtrlash funksiyasi | 5 |
|
||||
| **C. Back-end CRUD API** | DB va Fayl tizimida Yaratish, O'qish, Yangilash (AI'dan qayta yuklash bilan birga) va O'chirish amallari | 8 |
|
||||
| **D. Security & Validation**| Server tomonida fayl hajmi/kengaytmani tekshirish, Mijoz tomonida istisnolarni (xatolarni) ko'rib chiqish | 5 |
|
||||
| **Jami Ballar** | | **25** |
|
||||
1017
module-d/package-lock.json
generated
@@ -1,18 +0,0 @@
|
||||
{
|
||||
"name": "wsc2026-module-b-ai-middleware",
|
||||
"version": "1.0.0",
|
||||
"description": "WSC2026 Web Technologies - Test Project: AI Middleware",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
"start": "node server.js"
|
||||
},
|
||||
"author": "WorldSkills Expert Team",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"cors": "^2.8.5",
|
||||
"express": "^4.19.2",
|
||||
"multer": "^1.4.5-lts.1"
|
||||
},
|
||||
"keywords": [],
|
||||
"type": "commonjs"
|
||||
}
|
||||
|
Before Width: | Height: | Size: 39 KiB |
|
Before Width: | Height: | Size: 60 KiB |
|
Before Width: | Height: | Size: 34 KiB |
|
Before Width: | Height: | Size: 76 KiB |
|
Before Width: | Height: | Size: 102 KiB |
|
Before Width: | Height: | Size: 35 KiB |
|
Before Width: | Height: | Size: 94 KiB |
|
Before Width: | Height: | Size: 64 KiB |
|
Before Width: | Height: | Size: 77 KiB |
|
Before Width: | Height: | Size: 68 KiB |
|
Before Width: | Height: | Size: 49 KiB |
|
Before Width: | Height: | Size: 53 KiB |
|
Before Width: | Height: | Size: 28 KiB |
|
Before Width: | Height: | Size: 43 KiB |
|
Before Width: | Height: | Size: 32 KiB |
|
Before Width: | Height: | Size: 79 KiB |
|
Before Width: | Height: | Size: 5.5 MiB |
@@ -1,173 +0,0 @@
|
||||
/**
|
||||
* ============================================================================
|
||||
* WSC2026 Web Technologies - Test Project: AI Middleware Server
|
||||
* ============================================================================
|
||||
* 🚨 [Competitor Notice]
|
||||
* You do NOT need to modify this file. This is a black-box AI microservice.
|
||||
* Your task is to run this server, test the APIs, and build your own
|
||||
* Front-end and Back-end (Database) application that communicates with it.
|
||||
* ============================================================================
|
||||
*/
|
||||
|
||||
const express = require('express');
|
||||
const cors = require('cors');
|
||||
const multer = require('multer');
|
||||
|
||||
const app = express();
|
||||
app.use(cors());
|
||||
app.use(express.json());
|
||||
|
||||
// Use memory storage (Converts image buffer directly to Base64)
|
||||
const upload = multer({ storage: multer.memoryStorage() });
|
||||
const OLLAMA_API = 'http://localhost:11434/api/generate';
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
// API 1: Text AI (Generate City Description and Country Info)
|
||||
// ----------------------------------------------------------------------------
|
||||
app.post('/api/generate-text', async (req, res) => {
|
||||
const { city_name, country } = req.body;
|
||||
if (!city_name || !country) {
|
||||
return res.status(400).json({ error: 'city_name and country are required.' });
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(OLLAMA_API, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
model: 'phi3',
|
||||
// 🚀 Advanced Prompt: Request city description and country info in JSON format
|
||||
prompt: `Provide information about ${city_name} in ${country}.
|
||||
Return a JSON object with exactly two keys:
|
||||
1. "city_description": A 2-sentence tourist introduction for the city.
|
||||
2. "country_info": One interesting or essential fact about the country ${country}.
|
||||
DO NOT output any explanations. JUST the JSON object.`,
|
||||
format: 'json',
|
||||
stream: false
|
||||
})
|
||||
});
|
||||
const data = await response.json();
|
||||
const rawText = data.response;
|
||||
|
||||
console.log(`[Text API] AI Original Response for ${city_name}, ${country}:`, rawText);
|
||||
|
||||
// --- 🛡️ Text Hallucination Defense Logic ---
|
||||
let cityDescription = "Failed to generate city description. Please enter manually.";
|
||||
let countryInfo = "Failed to generate country information. Please enter manually.";
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(rawText);
|
||||
cityDescription = parsed.city_description || cityDescription;
|
||||
countryInfo = parsed.country_info || countryInfo;
|
||||
} catch (e) {
|
||||
// Fallback: Use regular expressions if JSON parsing fails
|
||||
console.warn("[Text API] JSON parsing failed. Attempting regex extraction.");
|
||||
const descMatch = rawText.match(/"city_description"\s*:\s*"([^"]+)"/i);
|
||||
if (descMatch) cityDescription = descMatch[1];
|
||||
const infoMatch = rawText.match(/"country_info"\s*:\s*"([^"]+)"/i);
|
||||
if (infoMatch) countryInfo = infoMatch[1];
|
||||
}
|
||||
|
||||
res.json({
|
||||
city_description: cityDescription,
|
||||
country_info: countryInfo
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[Text API] Error:", error);
|
||||
res.status(500).json({ error: 'Text AI processing failed. Ensure Ollama is running.' });
|
||||
}
|
||||
});
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
// API 2: Vision AI (Integrated Image Analysis - Description and Keywords)
|
||||
// ----------------------------------------------------------------------------
|
||||
app.post('/api/analyze-image', upload.single('image'), async (req, res) => {
|
||||
const file = req.file;
|
||||
const { city_name, country } = req.body;
|
||||
|
||||
if (!file || !city_name || !country) {
|
||||
return res.status(400).json({ error: 'image, city_name, and country are required.' });
|
||||
}
|
||||
|
||||
try {
|
||||
const base64Image = file.buffer.toString('base64');
|
||||
const response = await fetch(OLLAMA_API, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
model: 'llava',
|
||||
prompt: `Analyze this image of ${city_name}, ${country}.
|
||||
Return a JSON object with:
|
||||
1. "description": A short 1-2 sentence description of the image.
|
||||
2. "keywords": An array of exactly 3 descriptive words.
|
||||
JUST the JSON object. DO NOT output any markdown, tags, or extra text.`,
|
||||
images: [base64Image],
|
||||
format: 'json',
|
||||
stream: false
|
||||
})
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
const rawAiText = data.response;
|
||||
|
||||
console.log(`[Vision API] AI Original Response for ${city_name}, ${country}:`, rawAiText);
|
||||
|
||||
// --- 🛡️ Hallucination Defense & Data Sanitization Logic ---
|
||||
let finalDescription = "No description generated. Please enter manually.";
|
||||
let finalKeywords = [];
|
||||
|
||||
try {
|
||||
// Attempt 1: Force extract inside curly braces {} in case AI adds markdown wrappers
|
||||
const jsonMatch = rawAiText.match(/\{[\s\S]*\}/);
|
||||
const targetText = jsonMatch ? jsonMatch[0] : rawAiText;
|
||||
const parsed = JSON.parse(targetText);
|
||||
|
||||
if (parsed.description) finalDescription = parsed.description;
|
||||
if (parsed.keywords) {
|
||||
if (Array.isArray(parsed.keywords)) {
|
||||
finalKeywords = parsed.keywords;
|
||||
} else if (typeof parsed.keywords === 'string') {
|
||||
// Split into an array if keywords arrive as a comma-separated string
|
||||
finalKeywords = parsed.keywords.split(',');
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn("[Vision API] JSON parsing failed. Attempting regex fallback.");
|
||||
|
||||
// Attempt fallback extraction for description
|
||||
const descMatch = rawAiText.match(/"description"\s*:\s*"([^"]+)"/i);
|
||||
if (descMatch) finalDescription = descMatch[1];
|
||||
|
||||
// Attempt fallback extraction for keywords array
|
||||
const arrMatch = rawAiText.match(/\[(.*?)\]/s);
|
||||
if (arrMatch) finalKeywords = arrMatch[1].replace(/["']/g, '').split(',');
|
||||
}
|
||||
|
||||
// Sanitize the keywords array (trim, remove brackets/quotes, filter empty, limit to 3)
|
||||
finalKeywords = finalKeywords
|
||||
.map(w => w.trim().replace(/[{}"\[\]]/g, ''))
|
||||
.filter(w => w.length > 0)
|
||||
.slice(0, 3);
|
||||
|
||||
if (finalKeywords.length === 0) {
|
||||
finalKeywords = ["analysis_failed", "manual_input_required", "error"];
|
||||
}
|
||||
|
||||
// Finally, return the description (Text) and keywords (Stringified Array)
|
||||
res.json({
|
||||
description: finalDescription,
|
||||
keywords: JSON.stringify(finalKeywords)
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error("[Vision API] Error:", error);
|
||||
res.status(500).json({ error: 'Vision AI processing failed. Ensure Ollama is running.' });
|
||||
}
|
||||
});
|
||||
|
||||
const PORT = 3000;
|
||||
app.listen(PORT, () => {
|
||||
console.log(`🚀 AI Middleware Server running on http://localhost:${PORT}`);
|
||||
console.log(`- Text API: POST http://localhost:${PORT}/api/generate-text`);
|
||||
console.log(`- Vision API: POST http://localhost:${PORT}/api/analyze-image`);
|
||||
});
|
||||