AI / ML 공부를 하면 무조건(?) 사용하게 되는 "주피터 노트북(Jupyter Notebook)"

 

pandas, numpy, scikit-learn 등 착실하게 공부를 해야하는 것은 맞지만

모든 것들을 외워서 사용하기에는 어려움이 많고, 또 일일이 타이핑을 하는 것이 효율적이지도 않다.

 

그래서 Jupyter Notebook을 사용하면서 도움을 주는 기능들에 대해서 하나씩 알아보자.

 

 

① 자동 완성(auto complete) : Tab

  - IDE를 사용하거나 리눅스 커맨드 창에서 bash 또는 zsh 등을 사용할 때, 가장 많이 사용하는 tab !!!

  - 그런데, Jupyter Notebook에서 아래와 같이 타이핑을 하다가 tab을 눌러도 .... 아무런 반응이 없다.

 

 

  - import를 먼저 실행해서 "pd"가 뭔지 알려줘야 자동완성 기능을 사용할 수 있게 된다.

 

 

② 툴팁 (Tool Tip) : Shift + Tab 

  - 함수의 파라미터(parameter)들이 뭐가 있는지 확인하고 싶다면? Shift-Tab을 눌러주면 된다 !!!

 

 

③ 툴팁 (Tool Tip) : ?

  - pop-up으로 뜨는 툴팁이 조금 불편하다면, "?"를 이용해도 된다.

  - 함수명 뒤에 "?"를 타이핑하고, 실행을 시키면 밑에 출력이 된다.

 

 

 

④ Display parameter : set_config

  - scikit-learn의 model을 사용하다보면 parameter들을 확인해보고 싶을 때가 있다.

 

 

  - model에서 명시적으로 입력한 parameter 값만 확인이 되는데,

  - 현재 default로 지정된 parameter 값을 포함해서 전체 내역을 확인하고 싶을 때가 있다

 

  - scikit-learn 환경설정을 통해서 해결할 수 있다.

 

 

  - 이제 어떤 parameter로 해당 모델이 실행되는지 눈으로 확인할 수 있다 !!!

 

 

⑤ 도움말 (Help) : help

  - 자고로 도움말은 help !!!

 

 

  - 예쁘게 출력되진 않지만, 많은 정보를 보여준다.

 

반응형

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 수준을 벗어나지 못한 것 같다는.... ^^

 

아~ 내 돈 !!!!

반응형

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

 

수고 많으셨습니다!!!

반응형

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를 생각해보면 많은 이슈거리들이 뉴스를 장식하고 있다.

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

 

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

 

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

반응형

아이폰의 등장과 같은, 아니 그보다 더한 파급력을 보여주고 있는 ChatGPT !!!!

 

일부 사람만 사용할 수 있는 어려운 interface가 아니라 누구나 사용할 수 있으며

IT 분야에 제한되지 않는 모든 분야는 물론 일상적인 용도로도 사용할 수 있는

즉, 대중성을 갖고 있기에 이런 어머어마한 인기를 얻는 것이 아닌가 생각된다.

 

모든 사람을 똑똑하게 만들어 줄 수 있는 훌륭한 도구 - ChatGPT !!!

 

이런 ChatGPT의 활용도를 높여주는 많은 서비스들이 우후죽순 쏟아지고 있는데

그 중에서 논문 살펴볼 때 많은 도움을 주는 훌륭한 아이가 있어서 소개하고자 한다.

 

https://www.chatpdf.com/

 

chatpdf.com

 

PDF 문서를 입력으로 주고

그에 대해서 여러가지 질문을 던지거나 요청을 하면 ChatGPT를 이용해 답변을 해주는 서비스다.

 

가격 정책은 다음과 같다.

 

Pricing

 

그리고 로그인 하지 않아도 기본적인 사용은 가능하지만

나의 Chat 내역 기록이 필요하면 로그인 해주는 것이 좋다.

 

login

 

으음?! fIrebase로 구현을 했네!? ^^

다시 한 번 말하지만, 굳이 필요 없다면 로그인 없이도 사용할 수 있다.

 

 

그러면, 일단 오늘 살펴볼 논문을 검색해볼까!?

 

https://paperswithcode.com/

 

https://paperswithcode.com/

 

살펴볼 논문의 Paper 버튼을 통해 다운로드를 받던지

아니면 파일의 경로를 복사하던지 하면 된다.

 

Paper

 

그런 다음 ChatPDF에 파일을 등록하던지 아니면 경로를 입력하면 된다.

 

Drop PDF

 

그러면, 추천하는 질문들도 알려준다.

 

Example questions

 

그 질문 그대로 입력하면 당연히 잘 대답해준다.

 

 

혹시 한글로 물어봐도 대답 잘 해주려나?

 

 

질문은 이해하는데, 답은 영어로 하네?!

뭔가 좀 아쉬운데...

 

 

어!? 된다!!!!

조금 아쉬운데...

 

 

논문 공부하기에 정말 훌륭하지 않은가!?

설명만으로 그치지 않고, 궁금한 것에 대해서 물어볼 수도 있다는 점이 대단하다!!!

 

 

PDF를 업로드 한다고 하면 보안에 대해서는 잘 되어있을까!?

 

FAQ

 

뭐 나름 보안에 신경쓰는 것 같기는 하지만

회사 업무 문서를 업로드해서 사용하는 것에는 절대 권장할 수 없을 것 같다.

 

제목에도 쓴 것 처럼

공부를 위해 논문들을 살펴보는 용도 정도로 사용하기를 권장 드린다.

 

 

아! 그리고 아직은 GPT 3.5 기반이다.

GPT 4.0을 연결하는 것에 대해서는 계속 노력하고 있다고 한다.

반응형

ChatGPT의 인기에 힘입어

이제는 AI/ML을 공부하지 않는 분들도 누구나 알고 있다는 트랜스포머(Transformer)

 

너무나 훌륭한 공부 자료들이 많기에

여기에서는 그 자료들을 알아보도록 하겠다.

 

 

1. Paper

- "Attention Is All You Need"

  . https://arxiv.org/abs/1706.03762#

- 2017년도에 Ashish Vaswani 외 7명이 작성한 15 pages, 5 figures 구성된 논문

  . 논문에 포함된 그림의 수준이 정말 '역시 구글'이다.

 

model architecture

 

 

2. Review

- [딥러닝 기계 번역] Transformer: Attention Is All You Need (꼼꼼한 딥러닝 논문 리뷰와 코드 실습)
  . https://www.youtube.com/watch?v=AA621UofTUA 

  . 구독자가 16만명이 넘는 "동빈나"님의 멋진 리뷰

 

- Transformer 외에도 나동빈님의 많은 리뷰들이 담겨있다.

  . https://github.com/ndb796/Deep-Learning-Paper-Review-and-Practice#natural-language-processing-자연어-처리

 

 

동빈나 - Transformer 리뷰

 

- Code Practice

  . https://github.com/ndb796/Deep-Learning-Paper-Review-and-Practice/blob/master/code_practices/Attention_is_All_You_Need_Tutorial_(German_English).ipynb 

  . 위 링크에서 "Open in Colab"을 선택하면 Colab을 통해서 실행해볼 수 있다.

  . "Drive로 복사" 선택

Colab

 

  . 오래 전에 만들어진 코드이다 보니 지금 실행하면 맞지 않는 부분이 있으니 아래와 같이 수정하자.

import spacy

# spacy_en = spacy.load('en') # 영어 토큰화(tokenization)
# spacy_de = spacy.load('de') # 독일어 토큰화(tokenization)

spacy_en = spacy.load('en_core_web_sm')
spacy_de = spacy.load('de_core_news_sm')

 

 

3. More Detail

- 트랜스포머(Transformer) 심층 분석

  . https://wandb.ai/wandb_fc/korean/reports/-Transformer---Vmlldzo0MDIyNDc
  . 아래와 같이 몇 몇 부분에 대한 개선 방안을 엿볼 수 있다.

 

 

sample

 

- Transformer Positional Encoding

  . https://hongl.tistory.com/231

  . Positional Encoding에서 사용되는 sin/cos 함수에 대한 고찰

 

Transformer Positional Encoding

 

- Tensorflow 공식 가이드

  . https://www.tensorflow.org/text/tutorials/transformer?hl=ko

 

tensorflow

 

  . Colanb에서 실행을 선택하면 아래와 같이 예쁘게 표현된 encoder-decoder 애니메이션을 볼 수 있다.

 

encoder-decoder

 

 

4. Visualize

- Jay Alammar: The Illustrated Transformer

  . https://jalammar.github.io/illustrated-transformer/

 

The Illustrated Transformer

 

 

5. Extra

- Hugging Face

  . https://huggingface.co/

  . 자연어 처리를 공부/활용하는 분이라면 누구나 아는 그 곳

 

Hugging Face

 

- Transformers (신경망 언어모델 라이브러리) 강좌

  . https://wikidocs.net/book/8056

  . Hugging Face 사용법을 배울 수 있는 너무나 좋은 교재

 

Transformer 강좌

 

- Transformers.js

  . 트랜스포머를 브라우저에서 실행할 수 있도록 해주는 JS

  . https://xenova.github.io/transformers.js/

  . BERT, ALBERT, DistilBERT, T5, T5v1.1, FLAN-T5, GPT2, BART, CodeGen, Whispe 등 지원

 

Transformer.js

 

여기까지~

반응형

 

AI로 그린 그림이 엄청나게 유행이다.

카툰과 같은 그림 뿐만 아니라 이제는 사진과 같은 실사 느낌의 그림까지 나오고 있다.

 

best-inventions-2022-OpenAI-DALL-E-2

 

AI 그림이라는 것은

자연어 서술로부터 이미지를 생성하는 Machine-Learning 모델로 만들어진 것을 의미하는데,

 

요즘 ChatGPT 라는 것으로 이제는 누구나 알게 된 OpenAI라는 곳에서 개발(?)한

DALL·E 2로 인해서 AI로 그린 그림이 유명해지게 되었고

 

2022년 콜로라도의 미술대회에서 1등을 차지한 그림이

Midjourney 라는 ML 모델로 만들어진 것이라는 것이 밝혀지면서 엄청난 논란이 되었었다.

 

Midjourney

 

이렇게 AI로 그림 그리는 것이 엄청난 유행을 하고 있는데,

명색이 IT로 밥 값을 벌고 있는 입장에서 직접 한 번 다뤄봐야 하지 않을까?!

 

 

 

DALL·E 2, Midjourney 와 같은 모델들은 모두 상용으로 서비스 되고 있다.

하지만, 우리가 원하는 것은?! 오픈소스!!!

 

 

https://github.com/CompVis/stable-diffusion

 

Stable-Diffusion

 

Stable-Diffusion은 2022년 8월에

Stability AI에서 오픈소스 라이선스로 배포한 text-to-image 인공지능 모델이다.

 

오픈소스이지만 상용 모델 못지 않은 성능을 보여주며

더더군다나 비교적 낮은 컴퓨팅 파워 환경에서도 구동이 가능하다 !!!

 

 

그리고, 오픈소스 프로젝트로 공개되었다보니

이를 기반으로 파생된 정말 유용한 프로젝트들이 정말 많다.

 

 

https://github.com/AUTOMATIC1111/stable-diffusion-webui/

 

Stable Diffusion web UI

 

CLI 방식이 아니라 웹 기반의 Interface를 이용해

Stable Diffusion 모델을 편리하게 사용할 수 있도록 만들어 주는 프로젝트이다.

 

그리고 여기에 덧붙여서

Colab에서 구동 가능하도록 해주는 프로젝트도 있다!!!

 

 

https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Online-Services

 

Online Services - Colab

 

위 목록 중에서 camenduru를 선택해보자.

 

https://github.com/camenduru/stable-diffusion-webui-colab

 

 

https://github.com/camenduru/stable-diffusion-webui-colab

 

Jupyter Notebook 형태로 제공해주고 있는데,

어떤 것을 선택하면 좋을지는 README 를 참고하면 된다.

 

colab

 

카툰 스타일 보다는 실사와 같은 것들을 해보고 싶어서 "dreamlike-photoreal-2.0"을 선택해 보았다.

Huggingface에 있는 설명들을 참고하자.

 

https://huggingface.co/dreamlike-art/dreamlike-photoreal-2.0

 

음... 뭔지는 잘 모르겠지만

Stable-Diffusion 1.5 버전을 기반으로 해서 만들어진 사진과 같은 이미지를 생성하는 모델이란다.

 

이런 것들을 만들 수 있단다.

 

example

 

그러면, 원하는 모델에 있는 "Open in Colab" 아이콘을 클릭하자.

 

link

 

Colab에서 열리고 나면, "Drive에 사본 저장" 메뉴를 통해 복사해놓자.

 

Drive에 사본 저장

 

상단에 "노트북 설정"을 할 수 있다고 나오는데, 링크를 클릭하자.

 

비공개 출력

 

설정창이 열렸으니

'하드웨어 가속기' 부분에서 GPU를 선택하고

하단에 있는 체크 박스 부분도 설정 해제해놓자.

 

셀 출력

 

위 설정창은 "런타임 유형 변경" 메뉴로도 설정 확인 및 변경 가능하다.

 

런타임 유형 변경

 

자~ 이제 준비는 다 되었다.

런타임 연결(실행)하자.

 

연결중

 

그리고 코드를 실행하면 된다.

 

실행

 

엄청 오래걸리니 (5분~10분 사이) 그동안 유용한 사이트 하나 가입하자.

 

https://civitai.com/

 

https://civitai.com/

 

AI 그림들을 자랑하고 공유하는 곳이다.

 

Tifa

 

따라해보고 싶은 그림이 있으면 그림 오른쪽 하단에 있는 ⓘ 부분을 눌러보면 된다.

 

prompt

 

그러면, 어떤 Prompt, Parameter로 만들었는지 정보를 얻을 수 있다.

 

text-to-image 모델에서 그림을 그리기 위해 사용한 text를 "prompt"라고 지칭한다.

원하지 않는 내용에 대한 설명(text)는 "negative prompt"라고 한다.

 

또한, 원하는 그림에 대한 설명 외에

어떤 sampler인지, Random 함수에 대한 Seed 값이라던지 하는 온갖 설정값들 정보도 중요하다.

 

 

이쯤 했으면 Colab 실행 완료되었을테니, 계속 이어서 진행해보면 ...

 

URL

 

잘 실행이 되었으면, 위와 같은 URL 정보가 보일 것이다.

가운데에 있는 "*.gradio.app" URL을 선택해서 클릭하면 창이 뜰 것이다.

 

Run

 

와우!!!

나만의 AI 그림 생성기가 나타났다 !!!

 

 

어떻게 사용하면 되는지도 알아볼 겸해서, 남들이 만들어 놓은 것을 참조해보자.

CIVITAI에서 우리가 선택한 "dreamlike photoreal 2.0"을 검색해보자.

 

dreamlike photoreal 2.0을 이용해서 만들어진 그림을 찾기 위함이다.

 

Dreamlike Photoreal 2.0

 

찾은 다음에 마음에 드는 이미지 하나 선택해서 ⓘ를 클릭해서 정보를 확인해보자.

 

sample

 

Prompt, Negative prompt를 비롯해서 Sampling Steps, Sampling method, CFG Scale, Seed 값 등도 모두 넣어주자.

 

generate

우와~~~!!! 나온다 !!!

 

당연하게도 완전히 똑같은 그림이 나오지는 않지만, 얼추 비슷한 이미지가 나온다.

 

 

 

이제, 시간과 정신의 방으로 갈 시간이다.

다양하게 이것 저것 바꿔보면서 만들다보면 ... 날짜가 바뀌어 있을 것이다 ^^

 

반응형


나이먹은 고리타분한 아저씨가 되어버린 나...

수학이 무서워서, 새로운 것 배우기가 무서워서 피해다녔는데...

결국은 AI/ML 공부를 할 수 밖에 없게 되어버렸다.


뭐 이제와서 내가 Modeler가 되거나 Data Engineer가 될 것은 아니지만

인프라쟁이이기에 최소한 MLOps 관련되어서는 알아야 하기에

기본적인 AI/ML 공부는 해야하는 상황에 놓여졌다.


항상 SW 공부할 때 나만의 환경에서 CLI 위주로 하는 스타일이었는데...

그래서 AI/ML 공부도 그렇게 해보려고 했는데,

결국은 Jupyter Notebook의 편리함을 이용하지 않을 수가 없었다.


Jupyter Notebook도 나의 환경에서 설치해서 해볼 수 있지만,

최근 GCP를 사용해볼 이유도 있어서

Colab 환경을 사용해보기로 마음 먹었다.


그러던 中 Kaggle 에서 제공해주는 데이터를 Colab에 넣어야할 상황이 벌어졌는데

Colab과 Kaggle을 바로 연결할 수 있는 방법이 있다고 해서

한 번 알아보았다.


1. Colab

    - 구글에서 무료로 제공해주는 훌륭한 머신러닝 개발환경이다.

    - 제공해주는 환경의 스펙이 아래와 같다고 한다. 와우~!! 대박~!!

        . CPU : 제온

        . Mem : 13GB

        . HDD : 320GB

        . GPU : NVidia Tesla K80

    - https://colab.research.google.com/



2. 준비

    - Colab 접속 후 아래와 같이 "파일 - 새 Python 3 노트"를 선택하자.




3. Kaggle 설치

    - "!"를 앞에 붙이면 시스템 명령어를 사용할 수 있다.

    - 타이핑 후 왼쪽의 화살표(?)를 클릭하면 실행된다.




4. Kaggle 인증키 다운로드

    - Colab에서 Kaggle 데이터를 가져오기 위해서는 접근할 수 있는 권한이 있어야 한다.

    - Kaggle 사이트에서 내 계정에 대한 인증키를 얻어보자.



    - "Edit Profile"을 클릭한 다음



    - "Create New API Token"을 클릭하면, "kaggle.json" 파일이 다운로드 된다.



5. 인증키 업로드

    - 다운로드 받은 인증키를 Colab에 업로드하자.



    - 윗 부분의 "+ 코드"를 선택하면 새로운 라인이 추가된다.

    - 아래 코드를 넣은 뒤 왼쪽 플레이 버튼을 누르면 "파일 선택" 버튼이 나온다.


from google.colab import files

files.upload()


    - "파일 선택"을 누른 뒤 아까 다운로드 받은 Kaggle 인증키 파일을 골라주면 위와 같이 나온다.



6. 인증키 복사하기

    - 업로드된 인증키를 정해진 곳에 넣어줘야 한다.

    - kaggle을 위한 디렉토리를 우선 만들어보자.


!ls -al

!mkdir -p ~/.kaggle

!ls -al ~/


    - 인증키를 복사한 뒤 속성 변경까지 해놓자

!cp kaggle.json ~/.kaggle/kaggle.json

!chmod 600 ~/.kaggle/kaggle.json

!ls -al ~/.kaggle/


    - 위와 같이 한 번에 여러 라인을 넣을 수도 있다.



7. Kaggle 데이터 목록

    - Kaggle 데이터 목록을 살펴볼 수 있다.



!kaggle competitions list



8. Kaggle 데이터 확인하기

    - Kaggle 사이트에서 Dataset을 보면 다운로드를 받을 수 있는 API를 확인할 수 있다.




9. Titanic 데이터 다운로드

    - Colab에 다운로드 받아보자.

    - 주의할 점은 시스템 실행을 위해서 항상 앞에 "!"를 붙여야 한다.



모두들 즐거운 머신러닝 생활~~~~!!!

반응형

+ Recent posts