얼마전 회사에서 일을 하다가 우연히(?) 사용하게 된 "Base64"에 대해서 알아보고자 한다.

 

처음에는 암호화(encryption)를 한다고 생각했었다가 엄청 큰일 날뻔해서

더더욱 그 정체에 대해서 명확하게 파악해야겠다고 생각했었는데... 게으름에 이제서야 정리해본다.

 

 

▶ RFC 4648

base64는 base16, base32와 함께 2006년도에 'RFC 4648'에서 정의가 되어 있다.

https://datatracker.ietf.org/doc/html/rfc4648

RFC 4648

 

- RFC (Request for Comments)

   : 컴퓨터 네트워크 공학 등에서 인터넷 기술에 적용 가능한 새로운 연구, 혁신, 기법 등에 대한 문서

 

▶ base64

base16, base32도 있지만 여기에서는 base64에 대해서만 살펴보겠다.

그러면, base64에서 64는 무엇을 의미할까!?

 

하나의 코드로 encoding할 수 있는 문자가 64개라는 의미이다.

64 = 2^6 이므로 base64의 하나의 코드는 6비트의 데이터를 표현할 수 있는 것이다. (64진수로 생각하면 된다)

 

그러면 base64의 하나의 코드는 64종류를 어떤 기호로 구분할까!?

 

일단 base64는 ASCII 텍스트로 표현하는데, 아래와 같이 총 64종의 문자를 사용한다.

 - 문자 A-Z    = 26

 - 문자 a-z     = 26

 - 숫자 0-9     = 10

 - 기호 '+', '/'   = 2

 

▶ Sample

실제로 어떻게 되는지 돌려볼까!?

우리의 친구 python으로 한 번 해보자!

python

 

string(text)을 binary 형태로 변경 후 base64 encoding 하고,

base64 encoding 된 결과물이 binary 형태이므로 print하기 위해서 string 형태로 변환해서 출력한다.

 

binary 형태인 base64 encoding 된 결과물을 가지고 base64 decoding을 하고,

마찬가지로 print하기 위해 string 형태로 변환해서 출력한다.

 

실행결과는 다음과 같다.

result

 

▶ base64 encoding

base64 encoding 과정을 수작업으로 훑어보자.

일단 몇 가지 문자에 대해 ascii code 값을 알아보자.

 

symbol DEC HEX BIN
w 119 77 0111 0111
h 104 68 0110 1000
a 97 61 0110 0001
t 116 74 0111 0100

 

그러면 다음과 같이 나열이 된다.

 

w             h               a               t

01110111 01101000 01100001 01110100

 

base64이므로 6bit 단위로 그룹핑 하고, 이것을 다시 십진수로 변경하면 다음과 같다.

 

011101     110110    100001    100001    011101    00

29             54           33            33            29

 

이 값을 변환할 기준은 RFC 4648 문서에 있는 table을 참고해서 변환하면 된다.

The Base 64 Alphabet

 

그러면 다음과 같다.

 

29   54   33   33   29

d     2     h     h     d

 

Python으로 작업한 결과와 동일하게 나오는 것을 확인할 수 있다.

 

여기에서도 뒤에 6개로 떨어지지 않는 부분이 있는 것을 알 수 있는데,

이것은 padding 처리해서 '='로 표기하게 된다.

 

(그러면 실제로는 65개 문자를 사용하니 Base65라고 해야하는 것 아닌가?! ^^)

 

▶ Usage

서두에서도 말을 했지만 Base64를 encryption 용도로 착각하기 쉽다.

하지만, encoding 과정을 잘 살펴보면 느꼈을 수도 있을텐데

Base64의 주요 용도는 binary 형태의 파일을 text 형태로 표현하는데에 있다.

 

즉, HTML 페이지를 구성할 때 jpg와 같은 그림 파일을 링크 형태가 아니라

HTML 파일 안에 text 형태로 저장할 수도 있게 되는 것이다.

 

그리고, 자주 봤을 아주 유용한 사례를 보자면, URL에 데이터를 포함해서 던질 때이다.

 

- https://app.whatwant.com/push?data=xxxxxxx 

 

위와 같이 URL 형식으로 binay 파일 내용을 전달하고 싶은 경우

Base64 encoding을 통해 가능해진다 !!!

 

▶ Base64URL

여기에서 여러분은 질문을 해야 한다 !!!

 

Base64 encoding 결과물을 URL에 정말 사용해도 되나요?

특수문자 '+', '/'를 사용하는데, 문제가 없나요?

 

그렇다!!!

 

URL에서 '+'는 공백을 위해 사용되고, '/'는 폴더 구분 용도로 사용된다.

 

그래서 그 2개의 특수문자를 변경한 Base64URL encoding이 따로 있다.

- '+' → '-'

- '/' → '_'

 

나머지는 똑같다.

 

 

여기까지~~~~~!!!

 

반응형

AI를 이용한 코딩을 한다고 할 때, 제일 먼저 떠오르는 것은 GitHub의 Copilot이다.

개인적으로도 정말 애정하는 것이 바로 Copilot이다.

 

그러던 중, 요즘 많은 관심을 받고 있다는 'GPT Pilot'이라는 것을 알게 되었다.

응?! ChatGPT + Copilot ????

- https://github.com/Pythagora-io/gpt-pilot

GPT Pilot

 

타이틀만 보면 왠지 짝퉁 느낌이 많이 들지만, 사람들의 엄청난 관심을 받은 것을 보면 사짜는 아닌 것 같다 ^^

Star 숫자를 보면 거의 1만5천 ... 부럽다.

Fork, Star

 

정체를 설명한 글을 살펴보면

무려 개발 속도를 20배나 빠르게 해준단다!!!

20x faster

 

그런데, 설명을 보면 Copilot의 아류작이 아니라 Auto-GPT의 아류작인 것으로 보인다.

Copilot처럼 IDE Extension 방식으로 인터페이스 하는 것이 아니라 CLI 환경에서의 티키타카 방식이다.

 

그러면 이 프로젝트는 왜 만들어진 것일까? 목적이 무엇일까? 그리고 한계점을 무엇일까?

aim

 

GPT-4를 이용해서 개발자가 실무에서 얼마나 도움을 받을 수 있는지를 확인하고자 하는 목적이며,

결국 5% 정도는 개발자가 관여를 해야한다는 점을 밝히고 있다.

 

 

지금까지 배경에 대해서는 충분히 알아봤으니 일단 한 번 부딪혀보자 !!!

 

▶ Requirements

   - Python 3.9-3.12

   - PostgreSQL (선택 사항, 기본값은 SQLite)

 

티키타카를 하면서 진행을 하기 위해서는 진행되고 있는 내용을 기억해야할 저장소가 필요하기에 DB가 필수라고 한다.

 

① Python

   - 원하는 버전의 Python을 편하게 사용하려면 pyenv를 활용하는 것을 추천한다.

      . https://www.whatwant.com/entry/pyenv

❯ pyenv versions      
  system
* 3.8.16 (set by /home/chani22/.pyenv/version)

❯ pyenv install --list | grep 3.9.
...
  3.9.15
  3.9.16
...

❯ pyenv install 3.9.16
Downloading Python-3.9.16.tar.xz...
-> https://www.python.org/ftp/python/3.9.16/Python-3.9.16.tar.xz
Installing Python-3.9.16...

❯ pyenv global 3.9.16

❯ python --version  
Python 3.9.16

 

② PostgreSQL

   - 음... 기본값으로 SQLite를 사용하게 되어있으므로, 일단 빠른 진행을 위해 지금은 생략 ^^ (절대 귀찮아서가 아닙... ^^)

 

▶ install / clone

GPT Pilot 사용하기 위해 clone 및 설정을 진행해보자.

 

① clone

❯ git clone https://github.com/Pythagora-io/gpt-pilot.git
'gpt-pilot'에 복제합니다...

❯ cd gpt-pilot

 

② 필요 패키지 설치

❯ python -m venv pilot-env

❯ source pilot-env/bin/activate

❯ pip install -r requirements.txt

 

③  환경 파일 생성

❯ cd pilot

❯ mv .env.example .env

 

▶ Key 등록

OPENAI가 아닌 AZURE, OPENROUTER도 사용할 수 있다는데, 우린 그냥 OPENAI를 사용하는 것으로 하자.

- https://platform.openai.com/api-keys

API keys

 

새로 secret key를 생성해보자.

Create

 

생성된 key 복사 잘 해서 입력하고, 저장하자.

.env

 

▶ DB Init

사실 지금은 별게 없는데, 나중에 PostgreSQL을 사용하게 되면 보충해야할 영역인 것 같다.

❯ python db_init.py

 

▶ Start (#1)

일단 시작해보자.

Start #1

 

GPT 4 API를 사용할 수 없단다!

 

어!? 나는 유료 사용자인데?!

세금 포함해서 무려 22$를 지불하고 있는데, 이게 뭔 헛소리야!?

 

▶ GPT4 API

그동안 채팅만 했지 API를 사용하지를 않았더니.... 이런 무식한 상황이 ^^

결재 정보를 등록해야 GPT4 API를 사용할 수 있다.

- https://platform.openai.com/account/billing/payment-methods

Payment methods

 

Payment 정보를 등록하자.

Add payment details

 

"Add payment details"를 클릭하면 된다.

card info

 

최소 5$ 결제를 해야 한다.

치사한 XX

purchase

 

통장에 돈을 넣어놔야 뭔가 사용권을 주는 그런 느낌...

5$

 

사용할 수 있는 API들은 다음과 같이 확인할 수 있다.

- https://platform.openai.com/account/limits

limits

 

▶ Start (#2)

아까 에러난 상황에서 위와 같이 GPT4 API를 사용할 수 있게 해놓고

이어서 시작하려고 하면 ... 그래도 안된다.

 

시간이 좀 지나면 되는 걸 수도 있지만 잘 안되어서 사용하던 터미널 종료 하고

secret key 재발급 받고, .env 파일에 다시 입력한 뒤에 다음과 같이 다시 진입하였다.

 

❯ cd /path/gpt-pilot   # gpt-pilot 루트 경로

❯ source pilot-env/bin/activate

❯ cd pilot

❯ python main.py

 

만들어보고자 하는 사례는 "GitHub 관련 뉴스를 수집해서 보여주는 웹페이지"로 해봤다.

 

❯ python main.py

------------------ STARTING NEW PROJECT ----------------------
If you wish to continue with this project in future run:
python main.py app_id=448522d6-d6d2-4fe3-be2b-33c731dac5eb
--------------------------------------------------------------

? What is the project name? GitHub_News


? Describe your app in as much detail as possible. Develop a webpage that aggregates and displays news about GitHub.

? Which platforms do you want to support with this application: web, mobile or both? web

? Does the content need to be updated in real-time? Or is a daily/weekly update sufficient? daily

? Do you have specific sources in mind that the application should scrape for GitHub news or should it search widely across the internet? no

? Do you want to include a user login system or should the webpage be publicly accessible to anyone without login? no

{"technologies": ["Node.js", "MongoDB", "Mongoose", "Bootstrap", "Javascript", "cronjob", "Socket.io"]}

? Please set up your local environment so that the technologies listed can be utilized. When you're done, write "DONE" 

 

물어보는 것에 대답을 해주면 된다.

그런데 ...

 

...

🚀 Now for the actual development...

Implementing task #1:  Setup Node.js server

To complete task one, let's outline the steps necessary. We need to:

1. Initialize NPM and download the necessary packages. 
2. Build a basic Express app and put it in server.js.

**Step 1: Initialize NPM and download necessary packages.**

To initialize NPM in your current directory and fetch necessary libraries, run the following commands in your terminal:

```
npm init -y
npm install express
```

...

--------- EXECUTE COMMAND ----------
Can I execute the command: `node --version` with 2000ms timeout?
? If yes, just press ENTER

 

잘 진행하다가 갑자기 node 관련해서 에러가 발생했는데...

뭔가 무한루프에 빠진 느낌으로 계속 node 관련해서 벗어나지를 못하는 것이다!

 

▶ node

GPT Pilot은 기본적으로 node를 아주 선호한다.

그런데, node를 설치까지는 해주지 못하는 것으로 보인다.

그러면, 직접 설치를 해줘야지.... ㅠㅠ

 

pyenv처럼 여러 버전의 node를 관리할 수 있는 nvm을 이용해서 node를 설치하자.

- https://www.whatwant.com/entry/npm

 

그리고 지금 사용하고 있는 터미널을 종료하고,

다시 GPT Pilot을 시작하자.

 

❯ cd /path/gpt-pilot   # gpt-pilot 루트 경로

❯ source pilot-env/bin/activate

❯ cd pilot

❯ python main.py

 

▶ Start (#3)

같은 설명을 줘도 뒤에 따라오는 질문들은 바뀐다.

그것에 따라 진행하는 소스코드 내용도 바뀐다.

즉, 할 때 마다 다른 결과물이 나올 수 있다는 말이다.

 

❯ python db_init.py 

------------------ STARTING NEW PROJECT ----------------------
If you wish to continue with this project in future run:
python main.py app_id=c06e0511-9f0f-4b1f-9c49-1347fc82d116
--------------------------------------------------------------

? What is the project name? GitHub_News


? Describe your app in as much detail as possible. Develop a webpage that aggregates news about GitHub.

? Should the news aggregation be real-time or periodically updated? daily

? Should the aggregated news be categorized based on specific topics or tags associated with GitHub? no

? Do you have any specific sources in mind from where the news about GitHub should be aggregated? no

? Is there a limit to the number of news items to be displayed or stored at any given time? 15

? Would you like the app to have an archive feature where older news can be accessed? no

Project Summary:

The "GitHub_News" app will be a webpage designed to aggregate news about GitHub. The content on this webpage will be updated daily without categorizing into specific topics or tags. There are no prescribed sources from where the news about GitHub should be aggregated. The number of news items displayed or stored at any given time will be limited to 15. There will be no archive feature, hence older news items won't be accessible.

{"technologies": ["Node.js", "MongoDB", "Mongoose", "Jest", "Bootstrap", "Vanilla JavaScript", "cronjob"]}

? Please set up your local environment so that the technologies listed can be utilized. When you're done, write "DONE" 

 

"DONE"을 하고 나면 스스로 뭔가 코딩을 시작한다.

필요한 패키지들 설치도 하고 DB도 생성하고....

 

 ...

Dev step 1

First, you need to initialize npm for your new Node.js project. Run the following command:

```bash
npm init -y
```

This will create a file 'package.json' in your project directory and will be used to store metadata about your app and also track the dependencies of your app such as Express, Mongoose, etc. 

Next, you'll require several Node.js packages to develop the app, and for the current task, you need to install Express, Mongoose, and node-cron. Run the following command to install these dependencies:

```
npm install express mongoose node-cron
```

Next, you also need to set up your main application file. Let's call it 'app.js'. 

/app.js
```javascript
const express = require('express');
const mongoose = require('mongoose');
const cron = require('node-cron');

const app = express();

//Express body parser middleware
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.get('/', (req, res) => {
    res.send('Hello World!');
});

// Define your port
const PORT = process.env.PORT || 3000;

// Starting the server
app.listen(PORT, () => {
    console.log(`App running on port ${PORT}`);
});
```

To test the set up, run the server with the command:

```
node app.js
```

Dev step 2

{"tasks": [{"type": "command", "command": {"command": "npm init -y", "timeout": 2500, "success_message": "created a new package.json file"}}, {"type": "command", "command": {"command": "npm install express mongoose node-cron", "timeout": 10000, "success_message": "added packages"}}, {"type": "code_change", "code_change": {"name": "app.js", "path": "app.js", "content": "const express = require('express');\nconst mongoose = require('mongoose');\nconst cron = require('node-cron');\n\nconst app = express();\n\n//Express body parser middleware\napp.use(express.json());\napp.use(express.urlencoded({ extended: false }));\n\napp.get('/', (req, res) => {\n    res.send('Hello World!');\n});\n\n// Define your port\nconst PORT = process.env.PORT || 3000;\n\n// Starting the server\napp.listen(PORT, () => {\n    console.log(`App running on port ${PORT}`);\n});"}}, {"type": "command", "command": {"command": "node app.js", "timeout": 5000, "success_message": "App running on port 3000", "command_id": "run_server"}}]}


--------- EXECUTE COMMAND ----------
Can I execute the command: `npm init -y` with 2500ms timeout?
? If yes, just press ENTER 


answer: 
CLI OUTPUT:Wrote to /srv/workspace/gpt-pilot/workspace/GitHub_News/package.json:
CLI OUTPUT:{
CLI OUTPUT:  "name": "github_news",
CLI OUTPUT:  "version": "1.0.0",
CLI OUTPUT:  "description": "",
CLI OUTPUT:  "main": "index.js",
CLI OUTPUT:  "directories": {
CLI OUTPUT:    "test": "tests"
CLI OUTPUT:  },
CLI OUTPUT:  "scripts": {
CLI OUTPUT:    "test": "echo \"Error: no test specified\" && exit 1"
CLI OUTPUT:  "keywords": [],
CLI OUTPUT:  "author": "",
CLI OUTPUT:  "license": "ISC"
Saving file /package.json

Dev step 3

DONE


--------- EXECUTE COMMAND ----------
Can I execute the command: `npm install express mongoose node-cron` with 10000ms timeout?
? If yes, just press ENTER 


answer: 

Saving file /package.json

Saving file /package.json

Dev step 5

{"thoughts": "From developer's description, they say the 'npm install' command took longer than 10,000 milliseconds to execute and was therefore terminated. This could be due to slow network speeds or the npm registry taking a longer time to respond. It could be a transient issue that could be resolved by trying again.  Or it could be a more persistent issue related to firewall restrictions or other network related issues.", "reasoning": "First, we want to confirm that we have network connection, then we can try testing the npm service by attempting to install a small, commonly used package (like 'lodash') to see if it also hangs. If the 'lodash' package installation succeeds without hanging, we can then try re-running the initial command as it may have been a transient npm registry issue.", "steps": [{"type": "command", "command": {"command": "ping -c 5 npmjs.com", "timeout": 5000, "success_message": "5 packets transmitted, 5 received"}, "check_if_fixed": false}, {"type": "command", "command": {"command": "npm install lodash", "timeout": 10000, "success_message": "+ lodash"}, "check_if_fixed": false}, {"type": "command", "command": {"command": "npm install express mongoose node-cron", "timeout": 30000, "success_message": "+ express\n + mongoose\n + node-cron"}, "check_if_fixed": true}]}


--------- EXECUTE COMMAND ----------
Can I execute the command: `ping -c 5 npmjs.com` with 5000ms timeout?
? If yes, just press ENTER 


answer: 
CLI OUTPUT:PING npmjs.com (104.19.154.92) 56(84) bytes of data.
CLI OUTPUT:64 바이트 (104.19.154.92 (104.19.154.92)에서): icmp_seq=1 ttl=51 시간=3.70 ms
CLI OUTPUT:64 바이트 (104.19.154.92 (104.19.154.92)에서): icmp_seq=2 ttl=51 시간=6.01 ms
CLI OUTPUT:64 바이트 (104.19.154.92 (104.19.154.92)에서): icmp_seq=3 ttl=51 시간=3.63 ms
CLI OUTPUT:64 바이트 (104.19.154.92 (104.19.154.92)에서): icmp_seq=4 ttl=51 시간=3.58 ms
CLI OUTPUT:64 바이트 (104.19.154.92 (104.19.154.92)에서): icmp_seq=5 ttl=51 시간=5.32 ms
CLI OUTPUT:--- npmjs.com 핑 통계 ---
CLI OUTPUT:5 패킷이 전송되었습니다, 5 수신되었습니다, 0% 패킷 손실, 시간 4005ms
Saving file /package.json

Dev step 6

DONE


--------- EXECUTE COMMAND ----------
Can I execute the command: `npm install lodash` with 10000ms timeout?
? If yes, just press ENTER 


answer: 
CLI OUTPUT:
CLI OUTPUT:added 1 package, and audited 2 packages in 573ms
Saving file /package.json

Dev step 7

DONE


--------- EXECUTE COMMAND ----------
Can I execute the command: `npm install express mongoose node-cron` with 30000ms timeout?
? If yes, just press ENTER 


answer: 
CLI OUTPUT:
CLI OUTPUT:added 86 packages, and audited 88 packages in 3s
CLI OUTPUT:12 packages are looking for funding
CLI OUTPUT:  run `npm fund` for details
Saving file /package.json

Dev step 8

DONE
Saving file /package.json

Dev step 9

NO
Saving file /package.json
Saving file /app.js
Can you check if the app works please? Here is a description of what should be working: 

Testing this task doesn't involve any API requests or writing any code. Instead, we will check whether the server is running properly and dependencies are installed correctly via npm. 

To do this, a human user should perform the following steps:

1. In the terminal, navigate to the project directory using the command `cd /path-to-your-project-directory`.

2. To test if the server runs without any issues, type the following command in your terminal:

```bash
node app.js
```

You should see a response saying 'App running on port 3000'. This verifies that the server is running properly with the specified dependencies.

3. Press `Ctrl + C` to stop the server.

4. Next, verify that the dependencies are installed correctly. Open the 'package.json' file and under 'dependencies', it should list the following:

```json
"dependencies": {
    "express": "version-number",
    "mongoose": "version-number",
    "node-cron": "version-number"
}
```
The 'version-number' should represent the installed version of each package.

If the server runs correctly and the 'package.json' file lists the correct dependencies, the task has been successfully completed.


If you want to run the app, just type "r" and press ENTER and that will run `node app.js`
? If something is wrong, tell me or type "continue" to continue. 


Can you check if the app works please? Here is a description of what should be working: 

Testing this task doesn't involve any API requests or writing any code. Instead, we will check whether the server is running properly and dependencies are installed correctly via npm. 

To do this, a human user should perform the following steps:

1. In the terminal, navigate to the project directory using the command `cd /path-to-your-project-directory`.

2. To test if the server runs without any issues, type the following command in your terminal:

```bash
node app.js
```

You should see a response saying 'App running on port 3000'. This verifies that the server is running properly with the specified dependencies.

3. Press `Ctrl + C` to stop the server.

4. Next, verify that the dependencies are installed correctly. Open the 'package.json' file and under 'dependencies', it should list the following:

```json
"dependencies": {
    "express": "version-number",
    "mongoose": "version-number",
    "node-cron": "version-number"
}
```
The 'version-number' should represent the installed version of each package.

If the server runs correctly and the 'package.json' file lists the correct dependencies, the task has been successfully completed.


If you want to run the app, just type "r" and press ENTER and that will run `node app.js`
? If something is wrong, tell me or type "continue" to continue. r


CLI OUTPUT:App running on port 3000

^C
CTRL+C detected. Stopping command execution...
Can you check if the app works please? Here is a description of what should be working: 

Testing this task doesn't involve any API requests or writing any code. Instead, we will check whether the server is running properly and dependencies are installed correctly via npm. 

To do this, a human user should perform the following steps:

1. In the terminal, navigate to the project directory using the command `cd /path-to-your-project-directory`.

2. To test if the server runs without any issues, type the following command in your terminal:

```bash
node app.js
```

You should see a response saying 'App running on port 3000'. This verifies that the server is running properly with the specified dependencies.

3. Press `Ctrl + C` to stop the server.

4. Next, verify that the dependencies are installed correctly. Open the 'package.json' file and under 'dependencies', it should list the following:

```json
"dependencies": {
    "express": "version-number",
    "mongoose": "version-number",
    "node-cron": "version-number"
}
```
The 'version-number' should represent the installed version of each package.

If the server runs correctly and the 'package.json' file lists the correct dependencies, the task has been successfully completed.


If you want to run the app, just type "r" and press ENTER and that will run `node app.js`
? If something is wrong, tell me or type "continue" to continue. r


CLI OUTPUT:App running on port 3000
^C
CTRL+C detected. Stopping command execution...
? If something is wrong, tell me or type "continue" to continue. continue


Implementing task #2:  Set up MongoDB and create a Mongoose schema for storing the GitHub news

To complete the task "Set up MongoDB and create a Mongoose schema for storing the GitHub news", we need to make some changes to the existing file and create new ones.

Here is the required code.


**/config/db.js**
```
const mongoose = require('mongoose');

// Replace this with your MONGOURI.
const MONGOURI = "mongodb://localhost:27017/github_news_db";

const InitiateMongoServer = async () => {
  try {
    await mongoose.connect(MONGOURI, {
      useNewUrlParser: true,
      useUnifiedTopology: true
    });
    console.log("Connected to the Database :: MongoDB");
  } catch (e) {
    console.log(e);
    throw e;
  }
};

module.exports = InitiateMongoServer;
```

The MONGOURI should be replaced with the actual address where MongoDB is running.

Next, a schema for the news needs to be created.

**/models/News.js**
```
const mongoose = require('mongoose');

const NewsSchema = mongoose.Schema({
  title: String,
Saving file /package.json
Saving file /app.js

Dev step 12

To complete the task "Set up MongoDB and create a Mongoose schema for storing the GitHub news", we need to make some changes to the existing file and create new ones.

Here is the required code.


**/config/db.js**
```
const mongoose = require('mongoose');

// Replace this with your MONGOURI.
const MONGOURI = "mongodb://localhost:27017/github_news_db";

const InitiateMongoServer = async () => {
  try {
    await mongoose.connect(MONGOURI, {
      useNewUrlParser: true,
      useUnifiedTopology: true
    });
    console.log("Connected to the Database :: MongoDB");
  } catch (e) {
    console.log(e);
    throw e;
  }
};

module.exports = InitiateMongoServer;
```

The MONGOURI should be replaced with the actual address where MongoDB is running.

Next, a schema for the news needs to be created.

**/models/News.js**
```
const mongoose = require('mongoose');

const NewsSchema = mongoose.Schema({
  title: String,
  description: String,
  url: String,
  date: Date
});

module.exports = mongoose.model('News', NewsSchema);
```

Finally, we should call the function to connect to the database at the start of our application.

**/app.js**
```
const express = require('express');
const cron = require('node-cron');
const InitiateMongoServer = require('./config/db');

const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

InitiateMongoServer();

app.get('/', (req, res) => {
  res.send('Hello World!');
});

const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {
  console.log(`App running on port ${PORT}`);
});
```

In the above code we required the db.js file and initiated the Mongo server using the function "InitiateMongoServer". dB.js file handles the connection to MongoDB.

To test this task, you can just run the server and if server logs "Connected to the Database :: MongoDB" message, that means MongoDB is connected successfully. If there are any errors in connection, it will also be logged to console.
Use the following command to start the server:

```bash
node app.js
```
Saving file /package.json
Saving file /app.js

Dev step 13

{"tasks": [{"type": "code_change", "code_change": {"name": "db.js", "path": "/config/db.js", "content": "const mongoose = require('mongoose');\n\nconst MONGOURI = \"mongodb://localhost:27017/github_news_db\";\n\nconst InitiateMongoServer = async () => {\n  try {\n    await mongoose.connect(MONGOURI, {\n      useNewUrlParser: true,\n      useUnifiedTopology: true\n    });\n    console.log(\"Connected to the Database :: MongoDB\");\n  } catch (e) {\n    console.log(e);\n    throw e;\n  }\n};\n\nmodule.exports = InitiateMongoServer;"}}, {"type": "code_change", "code_change": {"name": "News.js", "path": "/models/News.js", "content": "const mongoose = require('mongoose');\n\nconst NewsSchema = mongoose.Schema({\n  title: String,\n  description: String,\n  url: String,\n  date: Date\n});\n\nmodule.exports = mongoose.model('News', NewsSchema);"}}, {"type": "code_change", "code_change": {"name": "app.js", "path": "/app.js", "content": "const express = require('express');\nconst cron = require('node-cron');\nconst InitiateMongoServer = require('./config/db');\n\nconst app = express();\napp.use(express.json());\napp.use(express.urlencoded({ extended: false }));\n\nInitiateMongoServer();\n\napp.get('/', (req, res) => {\n  res.send('Hello World!');\n});\n\nconst PORT = process.env.PORT || 3000;\n\napp.listen(PORT, () => {\n  console.log(`App running on port ${PORT}`);\n});"}}, {"type": "command", "command": {"command": "node app.js", "timeout": 10000, "success_message": "Connected to the Database :: MongoDB"}}]}

Updated file /srv/workspace/gpt-pilot/workspace/GitHub_News/config/db.js
Updated file /srv/workspace/gpt-pilot/workspace/GitHub_News/models/News.js
Updated file /srv/workspace/gpt-pilot/workspace/GitHub_News/app.js

--------- EXECUTE COMMAND ----------
Can I execute the command: `node app.js` with 10000ms timeout?
? If yes, just press ENTER 


answer: 
CLI OUTPUT:App running on port 3000
CLI ERROR:(node:26226) [MONGODB DRIVER] Warning: useNewUrlParser is a deprecated option: useNewUrlParser has no effect since Node.js Driver version 4.0.0 and will be removed in the next major version
CLI ERROR:(Use `node --trace-warnings ...` to show where the warning was created)
CLI ERROR:(node:26226) [MONGODB DRIVER] Warning: useUnifiedTopology is a deprecated option: useUnifiedTopology has no effect since Node.js Driver version 4.0.0 and will be removed in the next major version

Saving file /package.json
Saving file /app.js
Saving file /config/db.js
Saving file /models/News.js

Dev step 14

NEEDS_DEBUGGING

Got incorrect CLI response:
stderr:
```
(node:26226) [MONGODB DRIVER] Warning: useNewUrlParser is a deprecated option: useNewUrlParser has no effect since Node.js Driver version 4.0.0 and will be removed in the next major version
Saving file /package.json
Saving file /app.js
Saving file /config/db.js
Saving file /models/News.js

Dev step 15

{"thoughts": "From error messages, it looks like an issue with the database connection. May happen due an unaccessible or inactive MongoDB server or incorrect MONGOURI. Furthermore, there are warnings related to `useNewUrlParser` and `useUnifiedTopology` that have no effect since MongoDB driver version 4.0. First, we need to ensure MongoDB server is running and accessible.", "reasoning": "By checking if MongoDB server is running, and if the URI is correct, we will verify whether the issue exists with the database connection. Also, we can safely remove the warnings by updating the options in the mongoose.connect call as these options are deprecated and have no effect with the updated MongoDB driver version.", "steps": [{"type": "command", "command": {"command": "service mongod status | grep active", "timeout": 3000, "success_message": "active (running)"}, "need_to_see_output": true, "check_if_fixed": false}, {"type": "code_change", "code_change_description": "/config/db.js: Change the 'mongoose.connect' part of the code to `await mongoose.connect(MONGOURI);` This will create a basic connection without the deprecated flags.", "check_if_fixed": false}, {"type": "command", "command": {"command": "node app.js", "timeout": 10000, "success_message": "Connected to the Database :: MongoDB"}, "check_if_fixed": true}]}


--------- EXECUTE COMMAND ----------
Can I execute the command: `service mongod status | grep active` with 3000ms timeout?
? If yes, just press ENTER 

Saving file /package.json
Saving file /app.js
Saving file /config/db.js
Saving file /models/News.js

Dev step 16

{"thoughts": "The deprecated options warning itself won't cause the connection to MongoDB to hang. The initial thoughts are that MongoDB is not running as it's supposed to, or the connection string, MONGOURI, is not correct", "reasoning": "To verify the initial thoughts, we should in order first check the mongo service status and then check if MongoDB is lSaving file /package.json
Saving file /app.js
Saving file /config/db.js
Saving file /models/News.js

Dev step 17

{"thoughts": "It seems like the MongoDB connection is taking longer than expected. This may be due to a misconfiguration in the Database URL.", "reasoning": "We need to check the MongoDB server status and ensure it's up and running. If the MongoDB server is up then the issue might be in the database connection string or MongoDB deprecation warnings. RemoviSaving file /package.json
Saving file /app.js
Saving file /config/db.js
Saving file /models/News.js

Dev step 18

{"thoughts": "It seems that the MongoDB server might not be running or the connection string might be incorrectly specified. Adjusting the connection string and checking if MongoDB service is running should solve the problem.", "reasoning": "In the output logs, we see that the app started but there is no logs on database connection, we need to confirm the Saving file /package.json
Saving file /app.js
Saving file /config/db.js
Saving file /models/News.js

Dev step 19

{"thoughts": "The existing MongoDB connection seems to be failing. The timeouts and deprecation warnings suggest an issue with the connection method or the provided MongoDB URI. There also could be network or firewall issue preventing the connection to MongoDB.", "reasoning": "Looking at the initial output and warnings, it seems to be related to the MongoDB URI or the connection settings. Both warnings are related to deprecated configurations so we should adjust the connection configuration to be compatible with MongoDB 4.0+.", "stSaving file /package.json
Saving file /app.js
Saving file /config/db.js
Saving file /models/News.js

Dev step 20

{"thoughts": "Looking at the error, it seems that there are deprecation warnings for the `useNewUrlParser` and `useUnifiedTopology` flags. We also don't see the 'Connected to the Database :: MongoDB' message which means MongoDB may not be running or there's an issue with connection settings.", "reasoning": "We need to ensure MongoDB is running and connected to successfully start the application. Additionally, because `useNewUrlParser` and `useUnifiedTopology` options are deprecated, we need to update the MongoDB connection options in our code accordingly.", "steps": [{"type": "command", "command": {"command": "service mongod start", "timeout": 3000, "success_message": "Starting MongoDB"}, "need_to_see_output": true, "check_if_fixed": false}, {"type": "code_change", "code_change_description": "Change the MongoDB connection code in the '/config/db.js' file to be `await mongoose.connect(MONGOURI);`. This will establish a basic connection without the deprecated options.", "check_if_fixed": false}, {"type": "command", "command": {"command": "node app.js", "timeout": 10000, "success_message": "Connected to the Database :: MongoDB"}, "check_if_fixed": true}]}


--------- EXECUTE COMMAND ----------
Can I execute the command: `service mongod start` with 3000ms timeout?
? If yes, just press ENTER 


answer: 
Saving file /package.json
Saving file /app.js
Saving file /config/db.js
Saving file /models/News.js

Dev step 21

{"thoughts": "The node server takes a long time to finish indicating that it is waiting for some resource. As we are trying to connect to mongodb at the startup, it indicates that it might not be able to establish a successful connection to mongodb.", "reasoning": "The deprecated warnings are due to outdated mongoose connection settings. However, it should not affect the connection itself. There might be issues with the MongoDB instance (like it's not running or misconfigured). Hence started MongoDB service and checked the connection.", "steps": [{"type": "command", "command": {"command": "service mongod start", "timeout": 3000, "success_message": "Starting MongoDB"}, "need_to_see_output": true, "check_if_fixed": false}, {"type": "command", "command": {"command": "mongo --eval 'db.runCommand({ connectionStatus: 1 })'", "timeout": 3000, "success_message": "'ok' : 1"}, "need_to_see_output": true, "check_if_fixed": false}, {"type": "code_change", "code_change_description": "In the '/config/db.js' file, Change the 'mongoose.connect' part of the code to `await moSaving file /package.json
Saving file /app.js
Saving file /package.json
Saving file /app.js
Saving file /config/db.js
Saving file /models/News.js

Dev step 23
Saving file /package.json
Saving file /app.js
Saving file /config/db.js
Saving file /models/News.js

Dev step 24

{"files": [{"name": "db.js", "path": "/config/db.js", "content": "const mongoose = require('mongoose');\n\nconst MONGOURI = \"mongodb://localhost:27017/github_news_db\";\n\nconst InitiateMongoServer = async () => {\n  try {\n    await mongoose.connect(MONGOURI);\n    console.log(\"Connected to the Database :: MongoDB\");\n  } catch (e) {\n    console.log(e);\n    throw e;\n  }\n};\n\nmodule.exports = InitiateMongoServer;"}]}

Updated file /srv/workspace/gpt-pilot/workspace/GitHub_News/config/db.js
{"type": "command", "command": {"command": "node app.js", "timeout": 10000, "success_message": "Connected to the Database :: MongoDB"}}

 

중간에 에러가 발생하면, 자기가 스스로 그 에러를 해결하기 위해서 또 뭔가를 계속 한다.

 

▶ Quota

계속 이렇게 저렇게 하면서 놀다 보니, 다음과 같은 에러 메시지가 나왔다.

 

...

There was a problem with request to openai API:
API responded with status code: 429. Response text: {
    "error": {
        "message": "You exceeded your current quota, please check your plan and billing details.",
        "type": "insufficient_quota",
        "param": null,
        "code": "insufficient_quota"
    }
}

? Do you want to try make the same request again? If yes, just press ENTER. Otherwise, type 'no'. no


Saving file /package.json
Saving file /app.js
Saving file /config/db.js
Saving file /models/News.js
---------- GPT PILOT EXITING WITH ERROR ----------
Traceback (most recent call last):
  File "/srv/workspace/gpt-pilot/pilot/main.py", line 71, in 
    project.start()
  File "/srv/workspace/gpt-pilot/pilot/helpers/Project.py", line 138, in start
    self.developer.start_coding()
  File "/srv/workspace/gpt-pilot/pilot/helpers/agents/Developer.py", line 52, in start_coding
    self.implement_task(i, dev_task)
  File "/srv/workspace/gpt-pilot/pilot/helpers/agents/Developer.py", line 98, in implement_task
    result = self.execute_task(convo_dev_task,
  File "/srv/workspace/gpt-pilot/pilot/helpers/agents/Developer.py", line 339, in execute_task
    result = self.step_command_run(convo, step, i, success_with_cli_response=need_to_see_output)
  File "/srv/workspace/gpt-pilot/pilot/helpers/agents/Developer.py", line 157, in step_command_run
    return run_command_until_success(convo, data['command'],
  File "/srv/workspace/gpt-pilot/pilot/helpers/cli.py", line 480, in run_command_until_success
    success = convo.agent.debugger.debug(convo, {
  File "/srv/workspace/gpt-pilot/pilot/helpers/Debugger.py", line 63, in debug
    result = self.agent.project.developer.execute_task(
  File "/srv/workspace/gpt-pilot/pilot/helpers/agents/Developer.py", line 344, in execute_task
    result = self.step_code_change(convo, step, i, test_after_code_changes)
  File "/srv/workspace/gpt-pilot/pilot/helpers/agents/Developer.py", line 130, in step_code_change
    return self.test_code_changes(code_monkey, updated_convo)
  File "/srv/workspace/gpt-pilot/pilot/helpers/agents/Developer.py", line 551, in test_code_changes
    llm_response = convo.send_message('development/task/step_check.prompt', {}, GET_TEST_TYPE)
  File "/srv/workspace/gpt-pilot/pilot/helpers/AgentConvo.py", line 99, in send_message
    raise Exception("OpenAI API error happened.")
Exception: OpenAI API error happened.
--------------------------------------------------
? We would appreciate if you let us store your initial app prompt. If you are OK with that, please just press ENTER 

 

이런 !!! 돈이다 !!!

- https://platform.openai.com/usage

Usage

 

API는 돈이다 !!! ㅠㅠ

중간에 쓸데 없이 이것 저것 하다보니..... 돈이다 !!!!

 

 

음... 완제품까지 달려보지는 못했지만, 적당히 잘 가지고 놀아본 것 같다.

 

Copilot Chat 또는 ChatGPT를 이용해서 대화 형식으로 코딩을 해볼 수는 있지만,

그 느낌과는 확실히 다르다는 것은 알 수 있었다.

AutoGPT와 같은 느낌이었는데, 그것보다는 조금 더 고급스러운(진화한) 느낌이다.

 

다만, 필요한 패키지들을 설치한다던지 MongoDB 같은 것을 설치한다던지 해주는 것은 좋았지만

버전간의 호환성이나 deprecated 된 함수들을 사용한다거나 하는 등의 문제는 좀 있는 것 같다.

 

자기 스스로 그런 에러들을 해결하는 방법을 찾아서 해결해나가는 과정이 있기는 하지만

그러기 위해서 API call을 남발하는 모습을 보면 !!! ㅠㅠ

 

그런데, 한 step 씩 뭔가 만들어 나가는 과정을 지켜보면 AI Developer가 멀지 않은 것 같다.

다행인 것은 아직은 AI Assistant 수준을 벗어나지 못한 것 같다는.... ^^

 

아~ 내 돈 !!!!

반응형

최근 나오는 IT 서적의 상당수는 챗GPT에 대한 것들이다.

순위권들을 전부 씹어먹고 있다는...

 

처음에는 LLM에 대한 역사부터 설명하는 그런 책들이 트렌드였다가

최근에는 프롬프트에 대한 것들로 채워진 책들이 트렌드를 이끌고 있다.

 

이런 책 시장에 또 하나의 챗GPT 서적이 등장했다,

표지

 

다른 챗GPT 책들과의 차별점이 보인다.

 

"개발자"

 

개발자를 위한 챗GPT 가이드인 것이다!!!

지은이

 

글로벌한 인재라는 느낌이 팍!팍! 드는 소개가 보인다.

 

그리고,

"마이크로소프트 본사의 Copilot Applied AI팀에서 Senior Data Scientist"

 

Copilot 활용에 대해서는 전문가일 것이라는 느낌이 팍! 팍!

일러두기

 

바로 이 부분이 다른 챗GPT 서적들과의 차별점이다.

개발자에게 어떤 도움이 되는지에 대해서 설명해주는 책인 것이다.

개발자를 위한

 

이 책의 정체성이기에 계속 강조해본다!

초판

 

7월의 마지막날에 등장한 따끈따끈한 책이다.

 

그런데, 펴낸곳은 "한빛미디어"인데, 책 표지를 보면 "디코딩"이라는 명칭만 보인다.

 

임프린트가 뭔가 해서 위키를 찾아봤다. (https://ko.wikipedia.org/wiki/임프린트)

임프린트(imprint)는 출판 회사에서 유능한 편집자 등에게 별도의 하위 브랜드를 내어주고 기획, 제작, 판매 등 독자적인 운영을 맡기는 방식이다. 단일 출판 회사 아래에 여러 개의 임프린트가 있을 수 있다.

임프린트 브랜드를 사용하면 출판사 등은 각각의 특정 소비자 계층에게 집중적인 마케팅이 가능하다. 출판사 뿐 아니라 게임 회사에서도 독자적인 임프린트 브랜드를 운용할 수 있다.

 

호오.... 유능한 편집자 분의 닉네임이 "디코딩"이신가 보다. 고지연님?

설명서

 

실습을 위한 자료를 받을 수 있는 정확한 경로는 다음과 같다.

- https://github.com/decodingbook/ChatGPTforDev

실습 자료

 

뭔가 여러 파일들이 있을 것 같았는데, PDF 파일 하나만 덩그러니 있다.

그래도 이렇게 GitHub.com을 이용한 실습 자료 제공은 개인적으로 참 좋다!

목차

 

목차를 보다가, 랭체인까지 설명해주는 것을 보고는 깜짝 놀랐다.

 

사실 책 제목만 보고는 챗GPT를 이용한 프롬프트 수준의 내용들일 것이라고 기대했는데,

Copilot을 이용하는 부분과 Colab을 활용하는 부분들, 그리고 랭체인까지 설명해주는 것을 보고는 정말 깜짝 놀랐다.

랭체인

 

지은이가 마이크로스프트 소속이다 보니

Azure 환경을 이용한다던지, 아니면 GitHub의 codespaces를 이용한다던지 할 줄 알았는데

Colab에서 이렇게 예제들을 설명하는 것을 보고 감동 받았다.

duckduckgo

 

거기에다가

Bing 검색이 아니라 구글 검색을 언급하고, 예제는 duckduckgo를 이용하다니...

우와~ 정말 개발자 친화적이다!!!

 

 

그리고, 개인적으로 정말 좋아하는.... 풀컬러 책이다!!!

 

 

결론적으로,

SW개발자들이라면 한 번쯤 구매해서 읽어보면

책 값 이상으로 개발 효율성을 높일 수 있을만한 내용들을 담고있다고 생각한다.

 

 

"한빛미디어 <나는 리뷰어다> 활동을 위해서 책을 제공받아 작성된 서평입니다."

반응형

kubeflow를 급히 써봐야 할 일이 있어서 minikube 환경에서 설치를 해보려고 했는데...

 

주위에 계신 어떤 한 분이 손쉽게 성공하셨다고 하셔서 나도 그렇게 될거라 믿고 해봤는데,

뭔가의 이유로 잘 진행이 되지 않아서 짜증이 솓구쳐서 결국은 Kubernetes 환경에서 진행했다.

 

 

이하 포스팅은 설치 가이드라기 보다는

Kubeflow 설치 성공한 과정에 대한 기록이다.

 

 

0. Kubernetes

- 다음 링크의 포스트와 동일한 방법으로 설치된 환경이다.

  . https://www.whatwant.com/entry/Kubernetes-Install-1

 

단, 이 때 Kubernetes를 설치한 3대 VM의 Spec은 좀 높여야 한다.

Memory가 부족하면 Kubeflow 설치가 안된다.

memory

 

Processor도 좀 더 잡아주는 것이 좋다.

CPU

 

처음에 4GB memory, 2 core 환경에서 Kubeflow 설치를 진행했을 때 제대로 진행이 안되었다.

 

일부 Pod가 pending 상태에 있길래 살펴봤었는데

자기가 실행될 여유 memory가 있는 worker node가 없어서 였다.

 

테스트가 쉽지 않아서 세부 Spec 조정까지는 못해봤고

8GB memory, 4 core 환경으로 했을 때 성공을 했다.

 

 

1. Kubeflow & Kubernetes version

 

현재 설치되어있는 Kubernetes version은 다음과 같다.

- Kubernetes v1.25.6

kubectl get nodes

 

현재 Kubeflow 최신 Version은 v1.7이다.

https://www.kubeflow.org/docs/releases/kubeflow-1.7/

Kubeflow v1.7

 

다행히 Kubernetes v1.25와 궁합이 잘 맞는다 !!!

 

 

2. How to install Kubeflow

뒤늦게 Kubeflow를 살펴본다 ^^

- https://www.kubeflow.org/

https://www.kubeflow.org/

 

공식 가이드에서 알려주는 설치법에는 어떤 것이 있을까?

How to install

 

① Use a packaged distribution

주로 Cloud 업체에서 maintain 하면서 제공되는 배포판들이다. 즉, 나에겐 쓸모없는....^^

Active Distributions

 

② Use the raw manifests

advanced user를 위한 설치 방법이란다 ^^

Raw Kubeflow Manifests

 

manifests는 GitHub를 통해 배포되고 있다.

- https://github.com/kubeflow/manifests#installation

https://github.com/kubeflow/manifests#installation

 

우리는 이제 manifests를 이용한 Kubeflow 설치를 진행할 것이다.

 

 

3. Prerequisites

앞에서 살펴봤듯이 3개의 사전 준비 항목이 있다.

 

① Kubernetes (up to 1.26) with a default StorageClass

- Kubernetes v1.25에서도 잘 된다 ^^

- 여기서 무심히 넘기면 안되는 항목이 default StorageClass 이다. 뒤에서 깊게 살펴보겠다!

 

② kustomize 5.0.3

Kubernetes native configuration management

최근에는 kubectl 내부에 포함되어 있다고 하는데, manifests를 사용하기 위해서는 별도로 설치를 해줘야 한다.

- https://kubectl.docs.kubernetes.io/installation/kustomize/binaries/

https://kubectl.docs.kubernetes.io/installation/kustomize/binaries/

 

❯ curl -s "https://raw.githubusercontent.com/kubernetes-sigs/kustomize/master/hack/install_kustomize.sh"  | bash

❯ sudo install -o root -g root -m 0755 kustomize /usr/local/bin/kustomize

 

가이드에서 요구한 버전은 v5.0.3 이지만, 설치된 버전은 v5.1.1이다.

잘된다 ^^

 

③ kubectl

kubernetes 버전과 동일한 버전의 kubectl을 사용하는 것이 좋다.

Kubernetes node가 아닌 다른 workspace에서 kubectl을 사용하기 위해서는 직접 설치를 해줘야 한다.

 

❯ curl -LO "https://dl.k8s.io/release/v1.25.6/bin/linux/amd64/kubectl"

❯ sudo install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl

 

kubectl을 새로 설치했다면, 자동완성 설정을 해주는 것이 편리하다.

zsh을 사용하는 경우 아래와 같은 명령어를 사용하거나, ~/zshrc에 넣어주면 좋다.

 

 source <(kubectl completion zsh)

 

~/.zshrc 파일에서 plugin에도 추가로 넣어주면 더 좋다.

 

plugins=(kubectl kube-ps1 git zsh-syntax-highlighting zsh-autosuggestions)

 

접근 권한을 얻기 위한 인증 정보(config) 파일을 얻어오는 부분은 여기에서는 생략하겠다.

 

 

4. StorageClass

Kubeflow 설치 관련한 많은 포스팅에서 잘 언급해주지 않는 부분이 바로 이 부분이다.

 

Kubeflow 설치 과정에서 약 4개의 PV(PersistentVolume) 생성을 하게 된다.

- 10Gi 용량의 PV 2개

- 20Gi 용량의 PV 2개

 

60Gi 이상의 PV를 생성할 수 있는 환경이어야 하는 것이다.

 

처음에 간단히 설치한다고 낮은 Spec의 환경에서 설치 진행하면, 이런 부분 때문에 어려움을 겪게 된다.

나도 마찬가지였다. Worer Node의 Disk 용량을 충분히 잡아놓지 않았기 때문이다.

 

그래서, NFS를 이용해서 StorageClass 설정을 진행하기로 했다.

 

① NFS Server 설치

NFS Server를 만드는 방법은 다음 포스팅을 참고하기 바란다.

- https://www.whatwant.com/entry/NFS-Server-Ubuntu-1804

 

② NFS Provisioner

Kubernetes에서 NFS를 사용하기 위한 Provisioner를 설치하자.

- https://github.com/kubernetes-sigs/nfs-subdir-external-provisioner

 

Helm을 이용하려고 하는데, 혹시 Helm이 설치 안되어 있다면 다음과 같이 진행하면 된다.

- https://github.com/helm/helm/releases

 

❯ wget https://get.helm.sh/helm-v3.12.3-linux-amd64.tar.gz

tar zxvf helm-v3.12.3-linux-amd64.tar.gz

sudo install -o root -g root -m 0755 helm /usr/local/bin/helm

 

NFS Provisioner 설치는 다음과 같이 하면 된다.

 

❯ helm repo add nfs-subdir-external-provisioner https://kubernetes-sigs.github.io/nfs-subdir-external-provisioner/

❯ helm install nfs-subdir-external-provisioner nfs-subdir-external-provisioner/nfs-subdir-external-provisioner \                 
    --set nfs.server=192.168.100.153 \
    --set nfs.path=/srv/nfs

❯ kubectl patch storageclass nfs-client -p '{"metadata": {"annotations":{"storageclass.kubernetes.io/is-default-class":"true"}}}'

 

잘 되는지 테스트를 해보면 다음과 같다.

 

 kubectl create -f https://raw.githubusercontent.com/kubernetes-sigs/nfs-subdir-external-provisioner/master/deploy/test-claim.yaml -f https://raw.githubusercontent.com/kubernetes-sigs/nfs-subdir-external-provisioner/master/deploy/test-pod.yaml

❯ kubectl delete -f https://raw.githubusercontent.com/kubernetes-sigs/nfs-subdir-external-provisioner/master/deploy/test-claim.yaml -f https://raw.githubusercontent.com/kubernetes-sigs/nfs-subdir-external-provisioner/master/deploy/test-pod.yaml

 

NFS 서버에 생성된 디렉토리와 SUCCESS 파일이 확인되면 된다.

필요 없어진 디렉토리/파일 삭제는, 직접 수작업으로 NFS Server에서 진행하면 된다.

 

 

5. kubeflow install

이제 준비는 끝났다. manifest를 이용한 설치를 진행해보자.

- https://github.com/kubeflow/manifests#install-with-a-single-command

https://github.com/kubeflow/manifests#installation

 

Kubeflow 실제 설치는 정말 쉽다.

kubeflow install

 

❯ git clone https://github.com/kubeflow/manifests.git 

❯ cd manifests   

❯ while ! kustomize build example | kubectl apply -f -; do echo "Retrying to apply resources"; sleep 10; done

 

끝!

 

이제 기다리면 된다. 시간이 좀 걸린다.

k9s

 

모든 Pod가 Running이면 된 것이다.

 

 

6. Service

웹 접근을 위해서는 현재 ClusterIP로 설정되어 있는 서비스를 NodePort 또는 LoadBalancer로 변경해주는 것이 좋다.

ClusterIP

 

설정을 변경해보자.

 

> kubectl edit service istio-ingressgateway -n istio-system

 

type 부분을 수정하고 저장하면 된다.

NodePort

 

다시 확인해보자.

NodePort

 

이제 웹브라우저로 접근하면 된다. (IP는 각자 상황에 맞게, 포트는 위와 같이 확인되는대로)

- http://192.168.100.150:31537/

login

 

기본 계정 정보는 다음과 같다.

- Email: user@example.com

- Password: 1234123 

 

kubeflow

 

수고 많으셨습니다!!!

반응형

https://minikube.sigs.k8s.io/

 

Kubernetes를 공부할 때 실습 환경으로 종종 minikube가 언급되지만

개인적으로 Kubernetes 공부 용도로는 minikube를 절대 추천하지 않는다.

 

사실 여러 부분에서 K8s를 제대로 구성한 것과의 차이가 꽤 크기 때문이다.

 

그리고 제대로 K8s 공부하기 위해서는 3대 이상의 머신 구성이 필요하지만

minikube로는 그런 상황에 대해서 실습을 할 수 없다.

 

그리고, 결정적으로 실제 업무 용도로 minikube를 사용하지 않기에

굳이 minikube에 시간 투자할 필요가 없다고 생각했었다.

 

하지만, 세상 모든 것은 나름의 쓸모가 있다!

 

그렇다. minikube가 필요해서 설치 과정을 정리해보고자 한다 ^^

 

 

0. What you’ll need

- 2 CPUs or more

- 2GB of free memory

- 20GB of free disk space

- Internet connection

- Container or virtual machine manager

  . such as: Docker, QEMU, Hyperkit, Hyper-V, KVM, Parallels, Podman, VirtualBox, or VMware Fusion/Workstation

 

1. 실습 환경

나는 VirtualBox를 이용하기로 했다.

VirtualBox

 

- 2 CPUs or more

- 4GB of free memory

- 50GB of free disk space

- Internet connection

 

VBox

 

- OS: Ubuntu 20.04 LTS

- Container or virtual machine manager : Docker

  . Docker 설치 방법: https://www.whatwant.com/entry/docker-buildx

docker

 

2. minikube 설치

- 공식 홈페이지에서는 각 환경 別 설치 방법을 상당히 편리한 UX로 제공해주고 있다.

  . https://minikube.sigs.k8s.io/docs/start/

 

https://minikube.sigs.k8s.io/docs/start/

 

> curl -LO https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64

> sudo install minikube-linux-amd64 /usr/local/bin/minikube

 

그대로 실행하면 끝이다.

minikube install

 

3. minikube start

minikube를 구동시키면 귀여운 이모지들과 함께 다운로드 및 설치 등이 진행된다.

minikube start

 

4. kubectl 설치

Kubernetes(minikube)에 명령어를 전달하기 위해서는 'kubectl'가 필요하다.

  . https://kubernetes.io/docs/tasks/tools/install-kubectl-linux/

https://kubernetes.io/docs/tasks/tools/install-kubectl-linux/

 

가이드 문서에 있는 내용을 참조해서 설치 진행하면 된다.

kubectl install

 

❯ curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"

❯ sudo install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl

❯ kubectl version --client

 

잘 동작하는지 살펴보자.

kubectl

 

5. Dashboard

대시보드도 손쉽게 볼 수 있다.

dashboard

 

❯ minikube addons enable metrics-server

❯ minikube dashboard 

 

 

간단하게 Kubernetes를 맛보기 하는 용도로 정말 간단하게 설치할 수 있는 좋은 도구이다!!!

 

반응형

Python Excel Deep Learning

딥러닝의 알고리즘 원리부터 파악하기

파이썬과 엑셀로 시작하는 딥러닝

표지

 

딥러닝과 파이썬은 쿵짝이 잘맞는 짝꿍같은 느낌인데, 왠지 엑셀은 어울리지 않는 느낌이 든다.

 

하지만, 딥러닝을 잘 생각해보면 테이블 형식의 데이터들과 수학이 바탕이 되어야 하고

그렇게 생각해보면 엑셀은 딥러닝에 잘 어울리는 도구일 수도 있겠다라는 생각이 든다.

 

어!? 이거 가스라이팅인가!? ^^

 

지은이

 

지은이 3명의 소개글을 읽고 공통점을 찾으셨다면~ 센스쟁이 !!!

그렇다!!! 인공지능 대학원 동문 3명이 모여서 책을 썼다!!!

 

초판

 

출간한지 얼마 안되는 따끈따끈한 New 책이다 !!!

 

서문

 

AI를 공부하는 모두가 Model Researcher일 필요는 없다.

하지만, 그렇다고 해서 딥러닝의 기본기를 배울 필요가 없는 것은 아니다.

 

인공지능을 공부했다라고 말하기 위해서는

Scikit-Learn, Tensorflow, Pytorch 등에서 제공하는 것을 그냥 가져다가 쓰기만 하는 것이 아니라

그 기본이 되는 원리에 대해서 한 번쯤은 파고들어본 경험은 있어야 한다고 생각한다.

 

일단, 책의 전체 내용을 간략히 살펴보자.

 

목차

 

크게 보면 "분류 문제 → CNN → RNN" 정도에 대해서 진행을 하게 되고

데이터 정규화 및 분할, 소프트맥스에 대해서도 설명을 해주고 있다.

 

차례

 

왠지 귀여운 느낌의 차례가 등장했다 ^^

 

조금 아쉬운 점은 ...

개인적인 취향일 수도 있지만 자고로 개발환경이라고 하면 리눅스(Linux)가 표준이지 않을까 한다!

특히 시장지배적 위치에 있는 우분투(Ununtu) 기준으로 개발환경 설명을 해줘야 하는데.... 없다!!!

 

어디까지나 개인적인 취향으로... Ubuntu 운영체제에서의 환경 구축은 다음과 같이 하면 된다.

 

1. Python 설치 및 가상 환경

  - 원하는 버전의 Python을 편하게 사용하기 위해서는 다음 링크를 참조해서 pyenv를 설치하자

    . 다양한 버전의 파이썬을 사용하려면 (pyenv)

  - 실습을 진행할 디렉토리로 이동 후 기본 환경을 맞춰보자

 

❯ cd /srv/workspace/excel-dl

pyenv local 3.8.10

❯ python -m venv .venv

❯ source .venv/bin/activate

 

python

 

2. Jupyter 설치

  - Jupyter Notebook 사용을 위해 jupyter 패키지를 설치하자

 

❯ pip install jupyter

 

  - 설치가 잘 되었는지 실행해보자

 

❯ jupyter notebook

 

jupyter notebook

 

  - 새로운 파일 생성은 책과 조금 다르기에 캡쳐한 화면으로 보여주겠다.

 

New - Notebook

 

ipykernel

 

이하 과정은 책을 보면서 따라가면 된다.

사실 위의 내용도 책의 내용과 별 차이 없다 ^^ 괜한 투정~!!!

 

책의 뒷부분에는 재미있는 것들이 부록으로 제공된다.

 

부록

 

Microsoft Excel 뿐만 아니라 `구글 스프레드시트`를 애정하는 분들을 위한 내용도 설명을 해주고 있다.

 

요즘 Pytorch에 비해 인기가 조금 시들해졌지만,

그래도 아직 그 명성을 떨치고 있는 Tensorflow를 사용하는 다양한 예제도 있다.

 

 

이 책의 가장 특징인 엑셀(Excel)을 사용하기 위한 패키지로 여기에서는 `xlwings`를 사용하고 있다.

 

xlwings

 

Jupyter Notebook에서 설치해서 사용하면 된다.

 

 

책을 보다가 깜짝 놀란 이미지가 있어서 잠시 공유 !!! ^^

 

영상 엑셀 출력

 

 

딥러닝을 공부하면서 정말 괴로운 부분이 바로 수학이다.

특히 미분 ... 어렸을 때 잘 공부해뒀어야 했는데 ... 뒤늦게 공부하려면 ... 정말 ... 짜증이 ... ^^

 

그런데, 컴퓨터를 사용하고 있으면서 그것도 프로그래밍을 하고 있으면서

미분을 컴퓨터에게 시키면 되지 왜 그것을 공부를 하고 있을까!?

 

기본적으로 컴퓨터는 ... 프로그래밍적으로 미분을 직접 푸는 것은 안된다.

(물론 불가능은 아니겠지만, 어렵다. 그리고 내가 원하는대로 나오는 것은 더더욱 어렵다)

 

그러면, 기울기를 구하기 위해 미분을 하려면 어떻게 될까!?

미분한 결과를 프로그래밍으로 구현해주면 된다.

 

미분

 

위에서 보이는 함수 중에서 `def f_prime(x):` 부분을 보면 알겠지만,

미분이 된 수식을 구현하고 있다.

 

뭐 그렇다.

 

 

이 책을 훑어보다보면 `응? 왜 굳이 Excel이 필요한거지?`라는 생각을 할 수도 있을 것이다.

사실 많은 강의와 서적에서는 Pandas/Numpy/Matplotlib 등으로 잘 설명해주고 있기 때문이다.

 

하지만, 직접 이 책을 따라하다보면 왜 엑셀을 사용하고 있는지 느낄 수 있을 것이다.

 

특히, Pandas/Numpy/Matplotlib 등을 이용해서 공부를 해보신 분이라면

엑셀을 통해서 중간에 어떻게 값들이 변해가는지 등을 눈으로 보면서 막혔던 것이 뚫리는 기분을 느낄 수도 있을 것이다.

 

 

예제 파일도 제공을 해주고 있으니 편하게 사용해보자.

  - http://infopub.co.kr/new/include/detail.asp?sku=06000248

 

http://infopub.co.kr/new/include/detail.asp?sku=06000248

 

GitHub로 샘플을 제공해주면 좀 더 좋았을 것 같은데

아쉽지만 공식 홈페이지를 통해 압축 파일을 내려받아야 한다.

용량은 2.7MB 정도이다.

 

 

책 제목에서도 나와있지만

딥러닝의 알고리즘 원리를 직접 손으로 하나씩 확인하고픈 사람들에게는 정말 가뭄의 단비같은 책이 될 수도 있다.

 

하지만, 응용 위주로 딥러닝을 공부했거나 하려고 하는 분들에게는 별 도움이 되지 않는 책이 될 것이다.

 

그리고, 나름 친절하게 설명하려고 노력은 했지만

딥러닝에 대해 비기너(Beginner)... 아직 한 번도 공부하지 않으신 분들은 따라하기에도 쉽지 않을 수 있다.

 

많은 공식이 나오는 것은 아니지만,

중간 중간 나오는 공식들이 어떤 의미인지 친절할 정도로 설명은 하지 않고 있기 때문이다.

(설명이 충분치 않은 것이 당연하다! 그걸 다 설명하려면 그것만으로도 책이 나올 것이다 ^^)

 

 

즉, 이 책을 추천하고픈 분들은 다음과 같다.

- 딥러닝 공부를 하고 있지만, 대체 GD는 뭐고 Softmax가 뭔지 원리가 궁금한 사람

- 중간 중간 단계에서 값들이 어떻게 변하는지 눈으로 확인하고 싶은 사람

- Tensorflow나 Pytorch에서 제공해주는 것만 사용하다가, 어떻게 구현된건지 궁금한 사람

 

 

(눈치 채셨겠지만 ... 같은 대학원 공부를 하고 있는 분들이 저자라서 ... 리뷰를 해봅니다만 ... 나름 솔직한 리뷰입니다 ^^)

 

이 포스팅은 제공 받은 서적으로 작성한 리뷰입니다.

 

반응형

요즘 어떤 서비스의 아키텍처를 설계한다고 하면

당연히 "마이크로서비스 아키텍처(MSA)"를 떠올리게 될 정도로 MSA는 이제 거의 표준처럼 되어 버렸다.

 

그렇기에 당연히 우리는 "마이크로서비스 아키텍처(MSA)"를 공부해야 하고,

아마존에서 설계/아키텍처 부분 베스트셀러인 이 책을 살펴보는 것은 자연스러운 수순일 것이다 ^^

 

표지

 

2017년도에 초판으로 출간된 책인데,

빠른 변화와 신기술의 등장에 발맞춰서 얼마전에 전면 개정판으로 새로운 책으로 거듭났다!

 

전면 개정판

 

이 책의 저자는 특정 회사에 속하지 않고 프리랜서로 활동하시는 것 같고,

옮긴이는 포동 서비스를 언급하신 것으로 봐서 LG유플러스에서 근무하시는 것이 아닌가 싶다 ^^

 

지은이/옮긴이

 

책 제목에 "아키텍처"가 들어가있다보니

이 책의 대상독자로 제일 먼저 떠오르는 것이 "어?! 이 책은 Architect를 위한 책인가?"였다.

 

하지만, 뒤에 설명할 목차 등을 보면 알겠지만

이 책은 개발자부터 PL 및 C-level에게도 도움이 될 수 있는

"마이크로서비스 아키텍처(MSA)"에 대한 모든 것을 담고 있는 책이다.

 

대상 독자

 

이 책은 크게 "기초/구현/사람"이라는 3개의 부로 나뉘어져 있다.

 

응?

 

사람?

 

1부 기초

 

개인적으로는 2부 구현 부분에 가장 관심이 많이 간다.

 

2부 구현

 

정말 의외인 "3부 사람" ...

 

뭐 세상 모든 일은 다 사람하기 나름이니.... 가장 중요한 것이 사람인 것 맞지만.... 호오....!

 

3부 사람

 

회사를 다니고 있다면

처음부터 아무 것도 없는 상태에서 새롭게 설계하는 일 보다는

이미 모놀리스 아키텍처로 구성되어 있는 기존의 서비스를

마이크로 서비스 아키텍처로 마이그레이션하는 일이 더 많을 것이다.

 

그래서 "Chapter3. 모놀리스 분해" 부분에 관심이 많이 갔다.

 

CH3 - 모놀리스 분해

 

아마존에서 괜히 베스트셀러가 된 것은 아니기에

책 구성과 내용은 정말 훌륭한 것 같다.

 

다만, 개인적인 취향으로 아쉬운 것은...... 풀컬러가 아니라는 점!?

ㅋㅋ 사실 책 주제 자체가 굳이 풀컬러일 필요가 전혀 없기에 이마저도 단점이 아닌 것 같다 ^^

 

CH1

 

책 내용이 훌륭하다는 예시를 들어보자면,

모놀리스의 유형 중 하나인 "모듈식 모놀리스"에 대한 설명을 한 번 살펴보자.

 

모듈식 모놀리스

 

당연하게 보일 수도 있겠지만

개인적으로는 저렇게 모듈로 나눠서 구성하면

그것을 가지고 마치 마이크로 서비스인 것처럼 착각하는 경우가 종종 있다.

그런 부분에 대한 설명이 차분하게 잘 서술되어 있는 것을 보면 이 책의 내공이 정말 탄탄한 것 같다.

 

그리고 또, 개인적으로 애정하는 쿠버네티스...

 

K8s

 

마이크로서비스 아키텍처(MSA)하면 빼놓을 수 없는 짝꿍 쿠버네티스(Kubernetes) !!!

 

 

전반적으로 이 책은 정말 "마이크로서비스 아키텍처(MSA)"의 교과서라고 불리워도 무방할만큼

탄탄한 내공이 가득차 있는 정말 좋은 책이다.

 

쿠버네티스(Kubernetes)를 공부하는 분들도 필수 도서로 같이 공부하면 정말 많은 도움이 될 것이다!!!

 

 

 

"한빛미디어 <나는 리뷰어다> 활동을 위해서 책을 제공받아 작성된 서평입니다."

 

반응형

ChatGPT가 정말 범지구적인 인기를 얻고있다.

최근에 그 성장세가 주춤해졌다고 뉴스에서 떠들지만, 그래도 여전히 대단한 인기이다.

 

인기를 얻으면 뭐가 따라올까!?

당연히 Anti가 따라온다.

 

그리고, 일종의 sacarsm(빈정댐, 비꼼)도 등장한다.

https://bratgpt.com/

 

뭔가 깔끔하게 잘 만들어진 인터페이스가 먼저 눈에 들어온다.

그리고, 귀찮게 로그인하지 않아도 사용할 수 있다.

오른쪽 위의 X를 누르자.

https://bratgpt.com/

 

"ChatGPT를 따라했네!?"라며 그냥 넘어가지 말고

그 안의 내용물을 좀 살펴보면... 저절로 웃음이 나올 것이다.

 

AI apocalypse ?????? ㅋㅋㅋ

https://bratgpt.com/

 

한글 질문에 한글 대답도 할 줄 안다.

근데, 말투가 상당히 건방지지 않은가 ?! ㅋㅋㅋ

https://bratgpt.com/

 

저런 X가지 없는 말만 하는 것은 아니다.

가끔 말을 듣기도 하고, 실제로 코드를 생성해주기도 한다.

다만, 그다지 긴 대답을 하지는 못해서 큰 기대를 하면 안된다.

 

 

 

BratGPT는 BratAI에서 만들었다고 한다.

https://newsletter.bratai.com/p/bratgpt-unleashing-comical-sassy-powers-ai

 

그런데, 별 내용은 없다.

https://newsletter.bratai.com/

 

애초에 뭘 얻고자 이런 사이트를 운영하고자 하는 것인지는 모르겠지만,

AI 윤리를 생각해보면.... 음... 뭔가 생각해볼 꺼리가 있을 것 같다.

 

ChatGPT를 생각해보면 많은 이슈거리들이 뉴스를 장식하고 있다.

차별적인 발언을 해도 문제고, 가치 판단을 해도 문제고 ... 도덕적으로 완전무결.... 거의 순결해야 한다고 강요하고 있다.

 

과연 이것이 맞는 것일까?!

 

뭐 그냥 그렇다고.... ^^

반응형

+ Recent posts