TechTogetWorld


 daviduino.co.kr

techtogetworld.com

 david201207.blog.me

cafe.naver.com/3dpservicedavid


기존에 작성했던 투표관련 웹 "vote" Django WEB 을  pythonanywhere에 배포하는 과정입니다.

특히 디렉토리 구조에 신경쓰지 않으면, 배포시 에러가 발생하므로, 유심히 볼 필요가 있습니다.

글의 순서는 아래와 같습니다.


===========================================================================

[ 배포하기]==> PythonAnywhere
1. GIT, GITHUB를 설치하고, 저장소를 만들어서 저장한다
2. GitHub에서 PythonAnywhere로 코드 가져오기
3. PythonAnywhere에서 가상환경(virtualenv) 생성하기
4. PythonAnywhere에서 데이터베이스 생성하기
5. web app으로 블로그 배포하기

6. 가상환경(virtualenv) 설정하기

7. WSGI 파일 설정하기

8. 구현된 모습 : 정상작동중

   ==>http://david20120720.pythonanywhere.com/

9. 참고 : pythonanywhere 가입후 자동설치되는 화일 구조

10. source file

vote.zip




[ 참고자료

     https://programmers.co.kr/learn/courses/6

===========================================================================




[ 배포하기]==> PythonAnywhere

1. GIT, GITHUB를 설치하고, 저장소를 만들어서 저장한다

   ==> 참고글 http://daviduino.co.kr/86

  - github에 올려진 형태 : 디렉토리 구조가 틀리면 web 실행시 에러 발생함, 구조를 맞추어야 함.


2. GitHub에서 PythonAnywhere로 코드 가져오기

  - 배시(Bash)" 콘솔을 실행해서, 콘솔화면으로 들어간다

  - PythonAnywhere command-line

   . $ git clone https://github.com/david20120720/vote.git

   . $ tree vote 명령어를 입력  ==> 화일이 제대로 불러와졌는지 확인가능 , 디렉토리 구조가 틀리면 배포시 에러 발생함

PythonAnywhere command-line

$ tree vote

13:27 ~ $ tree vote 

vote

├── db.sqlite3

├── elections

│   ├── __init__.py

│   ├── __pycache__

│   │   ├── __init__.cpython-36.pyc

│   │   ├── admin.cpython-36.pyc

│   │   ├── models.cpython-36.pyc

│   │   ├── urls.cpython-36.pyc

│   │   └── views.cpython-36.pyc

│   ├── admin.py

│   ├── apps.py

│   ├── migrations

│   │   ├── 0001_initial.py

│   │   ├── 0002_auto_20170910_1447.py

│   │   ├── 0003_auto_20170910_1714.py

│   │   ├── __init__.py

│   │   └── __pycache__

│   │       ├── 0001_initial.cpython-36.pyc

│   │       ├── 0002_auto_20170910_1447.cpython-36.pyc

│   │       ├── 0003_auto_20170910_1714.cpython-36.pyc

│   │       └── __init__.cpython-36.pyc

│   ├── models.py

│   ├── templates

│   │   └── elections

│   │       ├── area.html

│   │       └── index.html

│   ├── tests.py

│   ├── urls.py

│   └── views.py

├── manage.py

└── mysite

    ├── __init__.py

    ├── __pycache__

    │   ├── __init__.cpython-36.pyc

    │   ├── settings.cpython-36.pyc

    │   ├── urls.cpython-36.pyc

    │   └── wsgi.cpython-36.pyc

    ├── settings.py

    ├── urls.py

    └── wsgi.py


3. PythonAnywhere에서 가상환경(virtualenv) 생성하기

  - PythonAnywhere command-line

$ cd vote

$ virtualenv --python=python3.6 myvenv

Running virtualenv with interpreter /usr/bin/python3.6

[...]

Installing setuptools, pip...done.

$ source myvenv/bin/activate

(myvenv) $  pip install django~=1.11.0

Collecting django

[...]

Successfully installed django-1.11.3

5분정도 시간이 소요될수 있음


4. PythonAnywhere에서 데이터베이스 생성하기

 - pythonAnywhere command-line

   . (mvenv) $ python manage.py migrate

Operations to perform:

[...]

     Applying sessions.0001_initial... OK

   . (mvenv) $ python manage.py createsuperuser


5. web app으로 블로그 배포하기

  - PythonAnywhere 대시보드 ==>Web==>Add a new web app

  - 도메인 이름을 확정한 후, 대화창에 수동설정(manual configuration)

  - Python 3.6을 선택하고 다음(Next)을 클릭하면 마법사가 종료됩니다.

    . Note "Django"가 아니라  "수동설정(Manual configuration)"을 선택해야함

    . 기본 PythonAnywhere Django 설정을 위해서 이방법이 유리함.



6. 가상환경(virtualenv) 설정하기

 - "가상환경(Virtualenv)" 섹션에서 가상환경 경로를 입력(Enter the path to a virtualenv) ==> /home/david20120720/vote/myvenv/

    라고 입력

7. WSGI 파일 설정하기

 - "WSGI 설정 파일(WSGI configuration file)" ==> /var/www/<your-username>_pythonanywhere_com_wsgi.py부분) 클릭

 - 모든내용을 삭제==>아래 내용으로 기록

import os

import sys

path = '/home/david20120720/vote/'  # PythonAnywhere 계정으로 바꾸세요. ==> vote까지만 입력한다, mysite 까지 들어가면 에러 발생함.

if path not in sys.path:

    sys.path.append(path)

os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'

from django.core.wsgi import get_wsgi_application

from django.contrib.staticfiles.handlers import StaticFilesHandler

application = StaticFilesHandler(get_wsgi_application())

8 directories, 32 files


  - 저장=> WEB 클릭

  - 모두 끝았음. RELOAD 및 홈페이지 실행시 웹이 실행됨


8. 구현된 모습 : 정상작동중   



9. 참고 : pythonanywhere 가입후 자동설치되는 화일 구조

    


 10. source file





[ 참고자료]


    


 daviduino.co.kr

techtogetworld.com

 david201207.blog.me

cafe.naver.com/3dpservicedavid


[web sever 구축_파이선_DJANGO #3 ]Django WEB 배포하기


글의 순서는 아래와 같습니다.


===========================================================================


[ 장고 설치하기] ==> 기존글과 동일

[ 설정변경하기]

[ 데이터베이스 설정하기]

[ 어플리케이션 만들기]

[ 블로그글 모델 만들기]

[ 장고 관리자 등록]

[ 배포하기]

 -PythonAnywhere

[참고자료 ]  

https://tutorial.djangogirls.org/ko/deploy/

https://tutorial.djangogirls.org/ko/installation/

============================================================================


[ 장고 설치하기] ==> 기존글과 동일


아나콘다 콘솔화면에서 ==> pip install django

=> 장고설치는 비주얼한 화면등은 없음, 장고설치후 아래 명령어 실행시 프로젝트 틀을 만들어 주는 역할을 함

django-admin startproject <프로젝트이름> => mysite

=> "<c:\anaconda36>c:\>django-admin startproject mysite " 로 입력하면, c 드라이브에 mysite 폴더가 생성되면서, 

관련 파일들이 같이 생성이되어 디렉토리에 저장이 된다.

이 화일을들을 아래와 같이 수정해 나가면 됨

python manage.py runserver

웹브로우저 실행: http://127.0.0.1:8000/


[ 설정변경하기]

mysite/settings.py

    TIME_ZONE = 'Asia/Seoul'

mysite/settings.py

STATIC_URL = '/static/'

STATIC_ROOT = os.path.join(BASE_DIR, 'static')

mysite/settings.py

ALLOWED_HOSTS = ['127.0.0.1', '.pythonanywhere.com'] 


[ 데이터베이스 설정하기]

mysite/settings.py

DATABASES = {

    'default': {

        'ENGINE': 'django.db.backends.sqlite3',

        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),

    }

}


데이터베이스 생성 => 프롬프트에서 python manage.py migrate 실행


[ 어플리케이션 만들기]

python manage.py startapp blog =>blog라는 이름의 어플리케이션 만들기

mysite/settings.py 화일 수정

INSTALLED_APPS = [

    'django.contrib.admin',

    'django.contrib.auth',

    'django.contrib.contenttypes',

    'django.contrib.sessions',

    'django.contrib.messages',

    'django.contrib.staticfiles',

    'blog',


[ 블로그글 모델 만들기]

blog/models.py

from django.db import models

from django.utils import timezone

class Post(models.Model):

    author = models.ForeignKey('auth.User')

    title = models.CharField(max_length=200)

    text = models.TextField()

    created_date = models.DateTimeField(

            default=timezone.now)

    published_date = models.DateTimeField(

            blank=True, null=True)


    def publish(self):

        self.published_date = timezone.now()

        self.save()


    def __str__(self):

        return self.title

python manage.py makemigrations blog ==> 데이터베이스 반영전 마이그레이션 화일 준비함

python manage.py migrate blog ==> 글 모델이 데이터베이스에 저장됨


[ 장고 관리자 등록]

'settings.py'중 LANGUAGE_CODE = 'en-us'를 LANGUAGE_CODE = 'ko' ==> 관리자 화면 한국어로 변경

blog/admin.py ==> 화일수정

from django.contrib import admin

from .models import Post

admin.site.register(Post)==> 모델 등록하기

python manage.py createsuperuser : 아래는 예시임
command-line
(myvenv) ~/djangogirls$ python manage.py createsuperuser
Username: admin
Email address: admin@admin.com
Password:
Password (again):
Superuser created successfully.


사이트 접속하기
    - http://127.0.0.1:8000/admin/  으로 접속하고
    - 아이디로 로그인 하면 아래 위에서 만들었던 블로그 어플리케이션이 실행이 된다.


   상기내용들은 복습성격이 강함

[ 배포하기]==> PythonAnywhere

1. GIT, GITHUB를 설치하고, 저장소를 만들어서 저장한다

  - GIT 을 설치한다

  - 소스코드를 COMMIT하여, GIT에 버전관리 등록한다

  - GITHUB 설치한다

  - GITHUB에 저장소를 만들어, GIT의 화일을 싱크해 온다 ( GIT에서 PUSH 하기) 

  - 세부방법은 이전글 http://daviduino.co.kr/85 을 참고한다


2. PythonAnywhere에 블로그 설정하기

  - 회원가입한다(무료)

3. GitHub에서 PythonAnywhere로 코드 가져오기

  - 배시(Bash)" 콘솔을 실행해서, 콘솔화면으로 들어간다

  - PythonAnywhere command-line

   . $ git clone https://github.com/<your-github-username/my-first-blog.git

   . $ tree my-first-blog 명령어를 입력  ==> 화일이 제대로 불러와졌는지 확인가능

PythonAnywhere command-line

$ tree my-first-blog

my-first-blog/

├── blog

│   ├── __init__.py

│   ├── admin.py

│   ├── migrations

│   │   ├── 0001_initial.py

│   │   └── __init__.py

│   ├── models.py

│   ├── tests.pyㅊㅇ  ㅡ

│   └── views.py

├── manage.py

└── mysite

    ├── __init__.py

    ├── settings.py

    ├── urls.py

    └── wsgi.py


4. PythonAnywhere에서 가상환경(virtualenv) 생성하기

  - PythonAnywhere command-line

$ cd my-first-blog

$ virtualenv --python=python3.6 myvenv

Running virtualenv with interpreter /usr/bin/python3.6

[...]

Installing setuptools, pip...done.

$ source myvenv/bin/activate  ==> 위에서 설치한 가상환경을 활성화 함

(myvenv) $  pip install django~=1.11.0 => 가상환경 안에서 장고를 설치함

Collecting django

[...]

Successfully installed django-1.11.3

5분정도 시간이 소요될수 있음


5. PythonAnywhere에서 데이터베이스 생성하기

 - ythonAnywhere command-line

   . (mvenv) $ python manage.py migrate

Operations to perform:

[...]

     Applying sessions.0001_initial... OK

   . (mvenv) $ python manage.py createsuperuser


6. web app으로 블로그 배포하기

  - PythonAnywhere 대시보드 ==>Web==>Add a new web app

  - 도메인 이름을 확정한 후, 대화창에 수동설정(manual configuration)

  - Python 3.6을 선택하고 다음(Next)을 클릭하면 마법사가 종료됩니다.

    . Note "Django"가 아니라  "수동설정(Manual configuration)"을 선택해야함

    . 기본 PythonAnywhere Django 설정을 위해서 이방법이 유리함.



7. 가상환경(virtualenv) 설정하기

 - "가상환경(Virtualenv)" 섹션에서 가상환경 경로를 입력(Enter the path to a virtualenv) ==> /home/<your-username>/my-first-blog/myvenv/ 

    라고 입력

8. WSGI 파일 설정하기

 - "WSGI 설정 파일(WSGI configuration file)" ==> /var/www/<your-username>_pythonanywhere_com_wsgi.py부분) 클릭

 - 모든내용을 삭제==>아래 내용으로 기록

import os

import sys

path = '/home/david2012/my-first-blog/mysite2/'  # PythonAnywhere 계정으로 바꾸세요.(하기 청색부분 참고바람)

if path not in sys.path:

    sys.path.append(path)

os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite2.settings'

from django.core.wsgi import get_wsgi_application

from django.contrib.staticfiles.handlers import StaticFilesHandler

application = StaticFilesHandler(get_wsgi_application())


** 특히 " path = '/home/david2012/my-first-blog/mysite2/'  # PythonAnywhere 계정으로 바꾸세요. " 요 부분을 설정할때 주의를 요한다

   본 글에서는 아래와 같이 설정했을때(/home/david20120720/mtsite, 정상작동을 했음 . 예전에 상기와 같이 했을때 정상작동을 했음

   즉 프로그램의 디렉토리 저장상태에 따라 결정하면 됨.

   아래 그림은

david20120720 계정의 mysite 프로젝트를 path 로 지정하고

path안의 폴더 mysite안의 setting (mysite.settings) 화일에 접근하는것을 나타내고 있음.




  - 저장=> WEB 클릭

  - 모두 끝았음. RELOAD 및 홈페이지 실행시 웹이 실행됨


9. 구현된 모습 : 정상작동중

http://david20120720.pythonanywhere.com/ 로 접속하면 아래 화면이 나오고


    david20120720.pythonanywhere.com/admin/으로 접속하고, 로긴 하면  아래와 같이 어플리케이션이 실행됨





    



[참고자료 ]


https://programmers.co.kr/learn/courses/6

http://daviduino.co.kr/85



 daviduino.co.kr

techtogetworld.com

 david201207.blog.me

cafe.naver.com/3dpservicedavid


[web sever 구축_파이선_DJANGO #2 ] 버전/백업관리를 위한 GIT 활용


글의순서는 아래와 같습니다.

==========================================

1. GIT에 등록하기(commit)

2. GITHUB 원격저장소 만들기

3. GITHUB 원격저장소에  git 에 commit 되어있는 file을 원격 저장하기]

4. 참고자료

https://opentutorials.org/course/1492

https://programmers.co.kr/learn/courses/6

http://hackersstudy.tistory.com/41

==========================================


[GIT에 등록하기]


SOURCETREE  설치하기

 - 그래픽환경의 GIT 프로그램

GIT 저장소 만들기

 - FILE ==>CLONE,NEW... ==> Create new respository

 - type : git

 - destination path : 노트북에 프로젝트 폴더를 만든다

GIT 저장소에 화일 저장하기

 - 웹프로그램 화일을 프로젝트 폴더에 넣는다.

 - unstaged 상태인 화일을 선택해서, staged 상태로 만들고, commit을 한다

 - commit과 동시에 버전관리가 시작된다

편집기(atom)에 프로젝트 폴더 등록하기

 - add project folder

 - atom에서 작업하는 내용은 git 프로젝트에 실시간으로 동기화 된다.


[GITHUB 원격저장소 만들기]

GITHUB 계정을 만든다

NEW rapositiry

 - rapagitory name 지정

 - public

 - create rapository

NEW rapositiry 접근 주소 확인 (http용)...............A



[GITHUB 원격저장소에  git 에 commit 되어있는 file을 원격 저장하기]


git 프로그램(sourcetree)으로 이동해서 

rapository => add remote ==> url/path 지정(글의 A 주소 지정) =>Remote name 지정 ( 최초시 origial 선택) ==>ok

sourcetree 좌측 메뉴에 remote 부분에 origin 등록된건 확인

llocal 저장소의 화일을 원격저장소로 옮기기 위해

 - push 버튼 실행

github 화면으로 화서 화면 refresh를 하면, 화일이 저장되어있는것을 확인


 








[ 참고자료 ]


https://opentutorials.org/course/1492

https://programmers.co.kr/learn/courses/6


 daviduino.co.kr

techtogetworld.com

 david201207.blog.me

cafe.naver.com/3dpservicedavid

 

web sever 구축_파이선 장고로 웹 사이트 구축하기


===================================================================

[ 장고 설치하기]

 - 파이선 웹프로그램 : 파이선의 패키중에 웹 프로그래밍 전문 패키지임

[hello  출력하기]

[ elections data db에 저장하기]

[ elections data db에 data 추가하기]

[ DATA 보여주기]

[아나콘다 prompt에서 manage.py 실행하기]

[탬플릿으로 html 불러오기]

[탬플릿에 정보채우기]

[여론조사 모델]

[ url 다루기]

[ 여론조사 화면 구현]

[ 여론조사 결과를 DB에 저장 ]

[ 참고자료 ]

 ==>https://programmers.co.kr/learn/courses/6

==================================================================

mysite.zip


[ 장고 설치하기]

아나콘다 콘솔화면에서 ==> pip install django django-admin startproject <프로젝트이름> => 프로젝트 이름은 mysite 로 한다 python manage.py runserver ==> 서버가 실행이 됨 웹브로우저 실행하여 접속함: http://127.0.0.1:8000/


서버가 실행중이면, 콘솔로 다른 작업이 불가능함, 콘솔에서 ctrl+c 로 종료를 해주어야 다른 작업이 가능해짐


[hello 출력하기] python manage.py startapp <앱이름> ==> 앱 이름은 elections 로 한다 views.py 작성: 자동으로 생성된 views.py를 아래 내용으로 수정한다     from django.shortcuts import render     from django.http import HttpResponse     def index(request):r     return HttpResponse("Hello world") mysite 내의 urls.py 수정 ==> 웹 실행시 실행될 app 지정     urlpatterns = [     url(r'^', include('elections.urls')),         ==> http://127.0.0.1:8000 으로 접속했을때, elections.urls을 실행하라고 지정해주는 것이다

==> include실행을 위해서는 mysite내의 urls.py 내에서 from django.conf.urls import include를 선언해주어야 함     url(r'^admin/', admin.site.urls),

  ==> admin으로 접속했을때, admin 화면으로 접속하게된다 ] elections 폴더에 urls.py 화일 작성 ==> http://127.0.0.1:8000/ 접속시 view.py내의 index 함수를 실행하라고 지정을 해줌

=> 그러면 최종적으로는 view.index 화일이 실행이 됨     from django.conf.urls import url     from . import views     urlpatterns = [      url(r'^$', views.index), ]

[ elections data db에 저장하기] models.py 수정==>     class Candidate(models.Model): ==> 후보자 data 정의      name=models.CharField(max_length=10)      introduction=models.TextField()      area=models.CharField(max_length=15)      party_number=models.IntegerField(default=1) db에 models.py의 data를 저장한다=> 시스템 off시 화일이 없어지지 않고, 저장케 하는 방법은 db에 저장하는것이다. mysite 내의 settings.py     INSTALLED_APPS = [     'django.contrib.admin',     'django.contrib.auth',     'django.contrib.contenttypes',     'django.contrib.sessions',      'django.contrib.messages',      'django.contrib.staticfiles',      'elections' ==> 추가해 준다     ] mysite 에서 python manage.py makemigrations 실행

==>model data를 db에 어떤형식으로 쓸것인가에 대해 정의함

==> db 항목의 변화가 있때마다 실행을 해줘야 반영이 됨 python manage.py migrate ==> 실제로 db를 만들어줌, ==> db 항목의 변화가 있때마다 실행을 해줘야 반영이 됨

[ elections data db에 data 추가하기] >python manage.py createsuperuser name : david     비밀번호 2번 입력 : a1a1a1aa1 >python manage.py reunserver 웹브러우저에서 127.0.0.1:8000/admin admin.py 화일 수정     from django.contrib import admin     # Register your models here.     from .models import Candidate ==> models.py화일에서 Candidate를 불러다 쓰겠다는 내용임     admin.site.register(Candidate)     Candidate가 추가되었음을 볼수있음.

    

data 추가를 하면 candidate object로 구분이 되지 않음.     이를 해결하기 위해, model.py화일에 name으로 식별하겠다고 정의해줌         def __str__(self): ==> def 뒤에 한칸을 띄고, 줄마춤을 맞추어야 한다.         return self.name




[ DATA 보여주기] view.py 수정하기 def index(request): candidates = Candidate.objects.all() str = "" for candidate in candidates: str += "<p>{}기호 {}번 ({})<BR>".format(candidate.name, candidate.party_number, candidate.area) str += candidate.introduction + "</P>" return HttpResponse(str)



[아나콘다 prompt에서 manage.py 실행하기]

>python manage.py shell 이후 나타는 [1]. [2] 라인에 코딩을 하면, 실행이 됨 [1]from elections.models import Candidate [2] new_candidate = Candidate(name = "홍명순") [3]new_candidate.save()

[4]Candidate.objects.all()
[5] no1 = Candidate.objects.filter(party_number = 1)
[6] no1[0].party_number
[7] no1[0].name

[탬플릿으로 html 불러오기]

템플릿 추가하기 templates 폴더 생성 (\mysite\elections\templates) elecetions 폴더 생성(\mysite\elections\templates\elections) index.html 파일 생성 (\mysite\elections\templates\elections\index.html)

index.html 화일 수정하기


<!DOCTYPE html> <html lang="en"> <head> <title>선거 후보</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <table class="table table-striped"> <thead> <tr> <td><B>이름</B></td> <td><B>소개</B></td> <td><B>출마지역</B></td> <td><B>기호</B></td> </tr> </thead> <tbody> <tr> <td>가후보</td> <td>후보입니다.</td> <td>우리나라</td> <td>기호1번</td> </tr> <tr> <td>나후보</td> <td>후보입니다.</td> <td>우리나라</td> <td>기호2번</td> </tr> <tbody> </table> </body>


VIEW.PY 화일 수정

from django.shortcuts import render from django.http import HttpResponse from .models import Candidate def index(request): candidates = Candidate.objects.all() return render(request,'elections/index.html')

   



[탬플릿에 정보채우기]


cadidate의 내용을 cpntext 매개로해서, html에 전달함

views.py 화일 수정


 def index(request):

     candidates = Candidate.objects.all()

     context={'candidates':candidates} ==>사전만들기

     return render(request,'elections/index.html',context)



index.html 화일 수정 ==> 데이터를 동적으로 받아 출력함

<body>

<div class="container">

    <table class="table table-striped">

        <thead>

        <tr>

            <td><B>이름</B></td>

            <td><B>소개</B></td>

            <td><B>출마지역</B></td>

            <td><B>기호</B></td>

        </tr>

        </thead>

        <tbody>

        {% for candidate in candidates %}

        <tr>

            <td>{{candidate.name}}</td>

            <td>{{candidate.introduction}}</td>

            <td>{{candidate.area}}</td>

            <td>기호{{candidate.party_number}}번</td>

        </tr>

        {% endfor %}

        <tbody>

    </table>

</body>

  



[여론조사 모델]

model.py 화일 수정


class Poll(models.Model):

    start_date = models.DateTimeField()

    end_date = models.DateTimeField()

    area = models.CharField(max_length = 15)


class Choice(models.Model):

    poll = models.ForeignKey(Poll) #Poll 모델의 id를 이용

    candidate = models.ForeignKey(Candidate)

    votes = models.IntegerField(default = 0)


admin.py 화일 수정


from django.contrib import admin


# Register your models here.

from .models import Candidate,Poll ==> poll 추가


admin.site.register(Candidate)

admin.site.register(Poll) ==> poll 추가등록


아나콘다 프롬프트에서 실행 ==> 모델 생성후 추가로 실행해야하는 코드임
python manage.py makemigrations
python manage.py migrate
python manage.py runserver
 



[ url 다루기]


index 화일 수정

<td> {{candidate.area}} </td>

==> <td> <a href = "areas/{{candidate.area}}/">{{candidate.area}}</a> </td>


urs.py 화일 수정

  url(r'^areas/(?P<area>.+)/$', views.areas)


views.py 화일 수정

def areas(request, area) :

return HttpResponse(area)

[ 여론조사 화면 구현]


area.html 화일 작성

<!DOCTYPE html>

<html lang="en">

<head>

  <title>지역구</title>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

</head>

<body>

<div class="container">

<h1>지역구</h1>

<br>

    <table class="table table-striped">

        <thead>

        <tr>

            <td><B>이름</B></td>

            <td><B>소개</B></td>

            <td><B>기호</B></td>

            <td><B>지지하기</B></td>

        </tr>

        </thead>

        <tbody>

        <tr>

            <td> 후보1</td>

            <td> 후보소개 </td>

            <td> 기호1번 </td>

            <td>

                <form action = "#" method="post">

                    <button name="choice" value="#">선택</button>

                </form>

            </td>

        </tr>

        <tr>

            <td> 후보2</td>

            <td> 후보소개 </td>

            <td> 기호2번 </td>

            <td>

                <form action = "#" method="post">

                    <button name="choice" value="#">선택</button>

                </form>

            </td>

        </tr>

        </tbody>

    </table>

</div>

</body>



view.py file 수정

def areas(request, area):

    candidates = Candidate.objects.filter(area = area) #Candidate의 area와 매개변수 area가 같은 객체만 불러오기

    context = {'candidates': candidates,

    'area' : area}

    return render(request, 'elections/area.html', context)


area.html 화일 수정

<!DOCTYPE html>

<html lang="en">

<head>

  <title>{{area}}</title>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

</head>

<body>

<div class="container">

<h1>{{area}}</h1>

<br>

    <table class="table table-striped">

        <thead>

        <tr>

            <td><B>이름</B></td>

            <td><B>소개</B></td>

            <td><B>기호</B></td>

            <td><B>지지하기</B></td>

        </tr>

        </thead>

        <tbody>

        {% for candidate in candidates %}

        <tr>

            <td> {{candidate.name}}</td>

            <td> {{candidate.introduction}}</td>

            <td> 기호{{candidate.party_number}}번 </td>

            <td>

                <form action = "#" method = "post">

                    <button name="choice" value="#">선택</button>

                </form>

            </td>

        </tr>

        {% endfor %}

        </tbody>

    </table>

</div>

</body>



area에 현재 진행 중인 poll이 있는지 확인하기


views.py 화일 수정

from .models import Candidate, Poll, Choice import datetime


area.html 화일 수정

<!DOCTYPE html>

<html lang="en">

<head>

  <title>{{area}}</title>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

</head>

<body>

<div class="container">

<h1>{{area}}</h1>

<br>

{% if poll %}

    <table class="table table-striped">

        <thead>

        <tr>

            <td><B>이름</B></td>

            <td><B>소개</B></td>

            <td><B>기호</B></td>

            <td><B>지지하기</B></td>

        </tr>

        </thead>

        <tbody>

        {% for candidate in candidates %}

        <tr>

            <td> {{candidate.name}}</td>

            <td> {{candidate.introduction}}</td>

            <td> 기호{{candidate.party_number}}번 </td>

            <td>

                <form action = "#" method = "post">

                    <button name="choice" value="#">선택</button>

                </form>

            </td>

        </tr>

        {% endfor %}

        <tbody>

    </table>

{% else %}

여론조사가 없습니다

{% endif %}

</div>

</body>



[ 여론조사 결과를 DB에 저장 ]


웹사이트에서 결과를 전달


<!-- C:\Code\mysite\templates\elections\area.html -->

<!DOCTYPE html>

<html lang="en">

<head>

  <title>{{area}}</title>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

</head>

<body>

<div class="container">

<h1>지역구</h1>

<br>

{% if poll %}

    <table class="table table-striped">

        <thead>

        <tr>

            <td><B>이름</B></td>

            <td><B>소개</B></td>

            <td><B>기호</B></td>

            <td><B>지지하기</B></td>

        </tr>

        </thead>

        <tbody>

        {% for candidate in candidates %}

        <tr>

            <td> {{candidate.name}}</td>

            <td> {{candidate.introduction}}</td>

            <td> 기호{{candidate.party_number}}번 </td>

            <td>

                <form action = "/polls/{{poll.id}}/" method = "post">

                {% csrf_token %}

                    <button name="choice" value="{{candidate.id}}">선택</button>

                </form>

            </td>

        </tr>

        {% endfor %}

        <tbody>

    </table>

{% else %}

여론조사가 없습니다

{% endif %}

</div>

</body>



action에서 지정한 url을 등록

코드추가

urlpatterns = [

    # 기존 url 유지

    url(r'^polls/(?P<poll_id>\d+)/$', views.polls)

]


view.polls 구현 => views.py 수정

코드추가


def polls(request, poll_id):

    poll = Poll.objects.get(pk = poll_id)

    selection = request.POST['choice']

    try: 

        choice = Choice.objects.get(poll_id = poll.id, candidate_id = selection)

        choice.votes += 1

        choice.save()

    except:

        choice = Choice(poll_id = poll.id, candidate_id = selection, votes = 1)

        choice.save()

    return HttpResponse("finish")






[ 참고자료 ]


https://programmers.co.kr/learn/courses/6

보호되어 있는 글입니다.
내용을 보시려면 비밀번호를 입력하세요.

확인

샘플 챗봇 만들기 입니다.

글의 순서는 아래와 같습니다.


============================================================================

1. 개발환경 구성

2. 채팅 테스트 하기

3. 참고자료

============================================================================


[샘플 쳇봇 만들기]


1. 챗봇의 이름 : dorothy

2. filesdorothy.txt 화일 만든다

   -화일 내용

      # underlying conversation system

      ../dorothy/

      ../dorothy/LiveData

    - 화일위치  dorothy 폴더와 동일 레벨

3. 샘플챗봇의 폴더를 만든다

   -폴더 이름 : dorothy

    . 폴더위치 : chatscrip와 동일레벨 위치에 만든다. 

4. 폴더안에 화일 만들기

   - 기존의 harry 챗봇 폴더안의 화일 4개를 복사해 온다

   - simpleControl.top 화일을 열어서 Harry라는 단어를 모두 지우고, dorothy로 바꾼다(3개소)

   - Introductions.top 파일을 열어 맨 아랫 줄의 “My name is Harry”를 “제 이름은 도로시에요”로 바꾼다(저장은 UTF-8 형식).

6.  CS 를 실행한다 : chatscript.exe를 실행한다

5.dorothy를 빌드( 컴파일부터 실행가능한 상태로 만들어 주는 모든 과정)한다

    -콘솔1번 창에서 “:build Dorothy” 

 6. test : 콘설창에서 " what is your name? "을 쳐서, "내이름은 도로시예요" 라고 나오면 정상임

 7. 실행종료

   . chatscript 끝내기 : :quit

   . 콘솔끝내기 : exit

 8. 화일구조

   


 




[ kpop 쳇봇 만들기]

진행중....





[참고자료]

https://sourceforge.net/projects/chatscript/files/ ==> cs 다운로드

https://www.fosshub.com/ConEmu.html ==>ConEmu64.exe 다운로드

http://exagen.tistory.com/m ==> 챗봇만들기 블로그




챗봇만들기 입니다.

글의 순서는 아래와 같습니다.


============================================================================

1. 개발환경 구성

2. 채팅 테스트 하기

3. 참고자료

============================================================================


[개발환경 구성]


1. CS (chatScript) 설치하기 ==> https://sourceforge.net/projects/chatscript/files/

2. 문서 편집기 ==> UTF-8 형식으로 저장할수 있으면, 편집기 종류 제한은 없음. 익숙한 프로그램 설치사용하면 됨.

3. 콘솔 설치

   - ConEmu64.exe 설치 ==>https://www.fosshub.com/ConEmu.html

   - evirenment 설정 ==> 작동이 잘 않되므로, st.bat을 별도로 만들어 실행시킴

     . chcp 65001

     . alias cs = cd C:\Users\dhp\Documents\20170827SoftBotProject\ChatScript754\BINARIES\

       -. cs라고 입력하고 엔터키를 누르면 chatscript의 binaries폴더로 바로 이동가능

   - st.bat 화일 만들기==> alias는 리눅스 명령어 이므로, doskey로 변경함

    . set PATH=%ConEmuBaseDir%\Scripts;%PATH%

    . chcp 65001

    . doskey cs=cd C:\Users\dhp\Documents\20170827SoftBotProject\ChatScript754\BINARIES\    . 


4.웹서버 및 PHP 파일 설치

   - 기존에 설치한 bitnami에 docs 폴더에 2개의 화일(아래 유첨)을 저장한다(C:\Bitnami\wampstack-7.0.13-1\apache2\htdocs)

     .  CS_Interface_PHP.zip

      ==>압축을 풀면 총 3개의 화일이 나올텐데 먼저 readme.txt를 읽은 후, 나머지 2개의 화일(TESTBOT.phpui_TESTBOT.php을 웹서버의   “htdocs” 폴더에 복사해 넣는다.

   - 동작확인  ==> 웹브로우져 창에   http://127.0.0.1/testbot.php 입력실행한다

4.테스트 준비하기

   - 콘솔창실행 : onEmu64.exe실행 ( 설치형과 이동형이 있는데, 설치형을 권장함, 본글은 이동형 기준임)

   - CS 서버 가동 : 폴더이동(cd C:\Users\dhp\Documents\20170827SoftBotProject\ChatScript754\BINARIES\) ==>cs 실행(콘솔창에 "chatscript port=1024 userlog "  입력) 

   - 웹서버 가동(웹서버 아이콘 더블클릭 ==> bitnami 서버 실행중이면 됨)

   - php 실행 ; 웹 주소창에 " http://127.0.0.1/testbot.php " 입력

5. 테스트 실시하기

   - 이름을 입력하고, 채팅을 해 본다

   - 영어로 채팅이 가능하다( 마이크 장착하면 음성으로 채팅이 가능함)



   


[참고자료]

https://sourceforge.net/projects/chatscript/files/ ==> cs 다운로드

https://www.fosshub.com/ConEmu.html ==>ConEmu64.exe 다운로드

http://exagen.tistory.com/m ==> 챗봇만들기 블로그

https://notepad-plus-plus.org/

http://conemu.github.io/

인공지능의 실전입문에 관한 글입니다.

알고리즘을 만드는것이 아니고, 만들어진 알로리즘을 활용하는 방법에 관한 글입니다.

자동차 운전을 위해 자동차를 만드는방법을 알필요는 없습니다. 물론 알면 좋기는 하겠지만, 서로 별도의 분야라고 할수있습니다.


본글은 언어구분 방법에 대한 글입니다.

글의 순서는 아래와 같습니다.


=========================================================================================


1. 동작구현 ==> [# 170820 4 lang-train-project_v03 ]

  - 프로그램을 실행하면, 프로그램에서 자동으로 독일어 사이트에서 9개의 독일어

    원문을 크롤링 해옵니다.

  - 별도로 저장한 프랑스어 txt 화일과 함께 학습을 합니다(학습용 5개 : fr-1 ~ fr-5 )

  - 프랑스어 4개( fr6~fr9)로 테스트를 실행합니다.

  - 평가합니다.

  - 특기사항

     . 크롤링 프로그램의 경우는 초반에 잘 되다가도, 중간에 인터넷 사이트의 뉴스기사가

        바뀌면  간혹 크롤링이 잘 않되는경우가 발생하는것 같습니다 (단순 텍스트만 바뀌면

        상관이 없지만, 글의 구조가 바뀌는경우입니다), 감안해서 코딩이 필요합니다.

2. Source code


170820 4 lang-train-project_v03.py

fr---6.txt

fr---7.txt

fr---8.txt

fr---9.txt

fr--1.txt

fr--2.txt

fr--3.txt

fr--4.txt

fr--5.txt


3. 참고자료    


==========================================================================================


 [# 170820 4 lang-train-project_v03 ]


import urllib.request

from bs4 import BeautifulSoup

import time

from sklearn import svm, metrics

import glob, os.path ,re, json


# train data

# HTML 가져오기

url = "http://www.zeit.de/index"

response = urllib.request.urlopen(url)

# HTML 분석하기

soup = BeautifulSoup(response, "html.parser")

# 원하는 데이터 추출하기 --- (※1)

results = soup.select("#main > div > div.cp-area.cp-area--major  div > h2 > a")

i=0

for result in results:

  i=i+1

  print(i,"st article")

  print("title:" , result.attrs["title"])

  url_article=result.attrs["href"]

  response = urllib.request.urlopen(url_article)

  soup_article=BeautifulSoup(response, "html.parser")

  content=soup_article.select_one("p")


  output=""

  for item in content.contents:

    stripped=str(item).strip()

    if stripped == "":

      continue

    if stripped[0] not in ["<","/"]:

      output+=str(item).strip()

      print(output)


# 추출한 data를 txt 화일로 저장하기

  fn= "de" +"--"+ str(i)+ ".txt"

  fw = open(fn, 'w', encoding='UTF-8', newline='')

 # f = open("C:/Python/새파일.txt", 'w')

  result_text = output

  fw.write(result_text)

  fw.close()

  # 1초휴식 : 초당 서버호츨 횟수가 늘어나면, 아이디 차단당할수 있음. 휴식시간이 필요함

  time.sleep(1.5)


# 학습시키기

files=glob.glob("*--*.txt")

train_data=[]

train_label=[]

i=0

for file_name in files :

    i=i+1

    print(i)

    basename=os.path.basename(file_name)

    lang=basename.split("-")[0]

    file=open(file_name,"r",encoding="utf-8")

    text=file.read()

    text=text.lower()

    file.close()

    code_a = ord("a")

    code_z = ord("z")

    count = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

    for character in text:

        code_current=ord(character)

        if code_a<=code_current <=code_z :

            count[code_current-code_a] +=1

    total=sum(count)+0.00001

    count=list(map(lambda n : n/total,count))

#리스트에 넣기

    train_label.append(lang)

    train_data.append(count)



# 테스트 하기: 프랑스어 4개 화일(6~9번)을 테스용 데이터로 사용함

i=0

files=glob.glob("*---*.txt")

test_data=[]

test_label=[]

for file_name in files :

    i=i+1

    print(i)

    basename=os.path.basename(file_name)

    lang=basename.split("-")[0]

    file=open(file_name,"r",encoding="utf-8")

    text=file.read()

    text=text.lower()

    file.close()

    code_a = ord("a")

    code_z = ord("z")

    count = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

    for character in text:

        code_current=ord(character)

        if code_a<=code_current <=code_z :

            count[code_current-code_a] +=1

    total=sum(count)+0.00001

    count=list(map(lambda n : round(n/total,3),count))

#리스트에 넣기

    test_label.append(lang)

    test_data.append(count)


# 평가하기

clf = svm.SVC()

clf.fit(train_data, train_label)

predict=clf.predict(test_data)

score=metrics.accuracy_score(test_label, predict)

print("score=",score)

print("=========================================================================")

print("test_data=",test_data)

print("predict=",predict)




[참고자료]


https://www.data.go.kr/main.do

http://konlpy-ko.readthedocs.io/ko/v0.4.3/

https://ithub.korean.go.kr/user/total/database/corpusView.do

인공지능의 실전입문에 관한 글입니다.

알고리즘을 만드는것이 아니고, 만들어진 알로리즘을 활용하는 방법에 관한 글입니다.

자동차 운전을 위해 자동차를 만드는방법을 알필요는 없습니다. 물론 알면 좋기는 하겠지만, 서로 별도의 분야라고 할수있습니다.


본글은 한글 형태소 분석 방법에 대한 글입니다.

글의 순서는 아래와 같습니다.


=========================================================================================


1.프로그램 설치

 - 아나콘다 기준임

 - conda install openjdk

 - conda install python

 - pip install konlpy

 - 상기 프로그램 설치후 jvm 관련 에러가 발생할경우 아래 프로그램 추가로 설치한다

    .jdk-8u144-windows-x64.exe  ==> http://docs.oracle.com/cd/E19182-01/820-7851/inst_cli_jdk_javahome_t/index.html

 - jupyter notebook 설치실행하기

    . pip install jupyter

    . 실행 :아나콘도 프롬프트에서 명령어 입력: jupyter notebook ==> 노트북이 열림 ( http://localhost:8888/tree# )

    . 에러 처리 :  셀에 코드 입력후 cell run을 해도 반응이 없을경우, 인터넷 브로우져를 " 크롬"으로 변경한다.

    . 기타 옵션 활성화는 "ipythoen.config 화일을 에서 필요한 항목을 주석해제 한다(활성화 한다)

      -C:\Users\dhp\.ipython\profile_default


2.한글 형태소 분석[ # 170819 10 toji_count ]

 - 단어별 등장빈도를 분석함

 - 소설의 장르구분, 글의 종류등을 구분하는데  많은 응용이 가능함

    


3. 소설 "togi" 내용을 형태소 적용 출력하고, 단어별 가까운 단어 사용빈도를 출력해줌 =>[ # 170820 1 word2vec-toji ]

 - 아래 2 라인은 jupyter 에서는 실행이 잘 되는데, 본 에디터(pycharm)여기서는 실행이 않되는 문제가 있음,확인필요함

    model1 = word2vec.Word2Vec.load("toji.model")

    model1.most_similar(positive=["땅"])


4. 베이지안필터로 텍스트 분류하기 ==? [ #bayes170820 ] [#170820 3bayes_test]

  - 광고성 스팸분류등.



5. MLP(다중 퍼셉트론 ,Multi layers perceptron)을 이용한 텍스트 분류 ==> [#170826 1 mlp2-seq] [# 170826 2 mlp3-classify]

  - 화일(- data.json  data-mini,josn  word-dic.json) 은  "http://wikibook.co.kr/python-machine-learning/ " 참조

 


6. Next Step

 - 문장의 유사도를 n-gram으로 분석하기 ==>[#170826 3 lev-distance]

 - 마르코프 체인과 LSTM으로 문장생성하기 ==>170826 5 markov , 170826 4 lstm-text-gen

 - 챗봇 만들기 =>170826 6 chatbot

 - 이미지와 딥러닝

  . 유사이미지 검출하기

  . cnn으로 caltech101 의 이미지 분류하기

  . opencv로 얼굴 인식하기

  . 이미지  ocr- 연속된 문자 인식하기


7. 참고자료


=========================================================================================


[ # 170819 10 toji_count ]


import codecs

from bs4 import BeautifulSoup

from konlpy.tag import Twitter

# utf-16 인코딩으로 파일을 열고 글자를 출력하기 --- (※1)

fp = codecs.open("170819 8.txt", "r", encoding="utf-16")

soup = BeautifulSoup(fp, "html.parser")

body = soup.select_one("text > body")

text = body.getText()

# 텍스트를 한 줄씩 처리하기 --- (※2)

twitter = Twitter()

word_dic = {}

lines = text.split("\r\n")

for line in lines:

    malist = twitter.pos(line)

    for word in malist:

        if word[1] == "Noun": #  명사 확인하기 --- (※3)

            if not (word[0] in word_dic):

                word_dic[word[0]] = 0

            word_dic[word[0]] += 1 # 카운트하기

# 많이 사용된 명사 출력하기 --- (※4)

keys = sorted(word_dic.items(), key=lambda x:x[1], reverse=True)

for word, count in keys[:50]:

    print("{0}({1}) ".format(word, count), end="")

print()



[ # 170820 1 word2vec-toji ]


"""

아래 2 라인은 jupyter 에서는 실행이 잘 되는데, 본 에디터(pycharm)여기서는 실행이 않되는 문제가 있음

확인필요함

model1 = word2vec.Word2Vec.load("toji.model")

model1.most_similar(positive=["땅"])

"""



import codecs

from bs4 import BeautifulSoup

from konlpy.tag import Twitter

from gensim.models import word2vec


# utf-16 인코딩으로 파일을 열고 글자를 출력하기 --- (※1)

fp = codecs.open("170819 8.txt", "r", encoding="utf-16")

soup = BeautifulSoup(fp, "html.parser")

body = soup.select_one("text > body")

text = body.getText()

# 텍스트를 한 줄씩 처리하기 --- (※2)

twitter = Twitter()

results = []

lines = text.split("\r\n")

for line in lines:

    # 형태소 분석하기 --- (※3)

    # 단어의 기본형 사용

    malist = twitter.pos(line, norm=True, stem=True)

    r = []

    for word in malist:

        # 어미/조사/구두점 등은 대상에서 제외 

        if not word[1] in ["Josa", "Eomi", "Punctuation"]:

            r.append(word[0])

    rl = (" ".join(r)).strip()

    results.append(rl)

    print(rl)

# 파일로 출력하기  --- (※4)

wakati_file = 'toji.wakati'


with open(wakati_file, 'w', encoding='utf-8') as fp:

    fp.write("\n".join(results))


# Word2Vec 모델 만들기 --- (※5)

data = word2vec.LineSentence(wakati_file)


model = word2vec.Word2Vec(data, 

    size=200, window=10, hs=1, min_count=2, sg=1)

model.save("toji.model")

print("ok")



model1 = word2vec.Word2Vec.load("toji.model")

model1.most_similar(positive=["땅"])



[ #bayes170820 ]

"베이지안 필터로 텍스트 분류하기"

import math, sys

from konlpy.tag import Twitter

class BayesianFilter:

    """ 베이지안 필터 """

    def __init__(self):

        self.words = set() # 출현한 단어 기록

        self.word_dict = {} # 카테고리마다의 출현 횟수 기록

        self.category_dict = {} # 카테고리 출현 횟수 기록

    # 형태소 분석하기 --- (※1)

    def split(self, text):

        results = []

        twitter = Twitter()

        # 단어의 기본형 사용

        malist = twitter.pos(text, norm=True, stem=True)

        for word in malist:

            # 어미/조사/구두점 등은 대상에서 제외 

            if not word[1] in ["Josa", "Eomi", "Punctuation"]:

                results.append(word[0])

        return results

    # 단어와 카테고리의 출현 횟수 세기 --- (※2)

    def inc_word(self, word, category):

        # 단어를 카테고리에 추가하기

        if not category in self.word_dict:

            self.word_dict[category] = {}

        if not word in self.word_dict[category]:

            self.word_dict[category][word] = 0

        self.word_dict[category][word] += 1

        self.words.add(word)

    def inc_category(self, category):

        # 카테고리 계산하기

        if not category in self.category_dict:

            self.category_dict[category] = 0

        self.category_dict[category] += 1

    

    # 텍스트 학습하기 --- (※3)

    def fit(self, text, category):

        """ 텍스트 학습 """

        word_list = self.split(text)

        for word in word_list:

            self.inc_word(word, category)

        self.inc_category(category)

    

    # 단어 리스트에 점수 매기기--- (※4)

    def score(self, words, category):

        score = math.log(self.category_prob(category))

        for word in words:

            score += math.log(self.word_prob(word, category))

        return score

    

    # 예측하기 --- (※5)

    def predict(self, text):

        best_category = None

        max_score = -sys.maxsize 

        words = self.split(text)

        score_list = []

        for category in self.category_dict.keys():

            score = self.score(words, category)

            score_list.append((category, score))

            if score > max_score:

                max_score = score

                best_category = category

        return best_category, score_list

    # 카테고리 내부의 단어 출현 횟수 구하기

    def get_word_count(self, word, category):

        if word in self.word_dict[category]:

            return self.word_dict[category][word]

        else:

            return 0

    # 카테고리 계산

    def category_prob(self, category):

        sum_categories = sum(self.category_dict.values())

        category_v = self.category_dict[category]

        return category_v / sum_categories

        

    # 카테고리 내부의 단어 출현 비율 계산 --- (※6)

    def word_prob(self, word, category):

        n = self.get_word_count(word, category) + 1 # ---(※6a)

        d = sum(self.word_dict[category].values()) + len(self.words)

        return n / d



[#170820 3bayes_test]


from bayes170820 import BayesianFilter

bf = BayesianFilter()

# 텍스트 학습

bf.fit("파격 세일 - 오늘까지만 30% 할인", "광고")

bf.fit("쿠폰 선물 & 무료 배송", "광고")

bf.fit("현데계 백화점 세일", "광고")

bf.fit("봄과 함께 찾아온 따뜻한 신제품 소식", "광고")

bf.fit("인기 제품 기간 한정 세일", "광고")

bf.fit("오늘 일정 확인", "중요")

bf.fit("프로젝트 진행 상황 보고","중요")

bf.fit("회의 일정이 등록되었습니다.","중요")

bf.fit("오늘 일정이 없습니다.","중요")

# 예측

pre, scorelist = bf.predict("재고 정리 할인, 무료 배송")

print("결과 =", pre)

print(scorelist)




[#170826 1 mlp2-seq]


import os, glob, json

root_dir = "./newstext"

dic_file = root_dir + "/word-dic.json"

data_file = root_dir + "/data.json"

data_file_min = root_dir + "/data-mini.json"

# 어구를 자르고 ID로 변환하기 ---(※1)

word_dic = { "_MAX": 0 }

def text_to_ids(text):

    text = text.strip()

    words = text.split(" ")

    result = []

    for n in words:

        n = n.strip()

        if n == "": continue

        if not n in word_dic:

            wid = word_dic[n] = word_dic["_MAX"]

            word_dic["_MAX"] += 1

            print(wid, n)

        else:

            wid = word_dic[n]

        result.append(wid)

    print(result)

    return result

# 파일을 읽고 고정 길이의 배열 리턴하기 ---(※2)

def file_to_ids(fname):

    with open(fname, "r") as f:

        text = f.read()

        return text_to_ids(text)

# 딕셔너리에 단어 모두 등록하기 --- (※3)

def register_dic():

    files = glob.glob(root_dir+"/*/*.wakati", recursive=True)

    for i in files:

        file_to_ids(i)

# 파일 내부의 단어 세기 --- (※4)

def count_file_freq(fname):

    cnt = [0 for n in range(word_dic["_MAX"])]

    with open(fname,"r") as f:

        text = f.read().strip()

        ids = text_to_ids(text)

        for wid in ids:

            cnt[wid] += 1

    return cnt

# 카테고리마다 파일 읽어 들이기 --- (※5)

def count_freq(limit = 0):

    X = []

    Y = []

    max_words = word_dic["_MAX"]

    cat_names = []

    for cat in os.listdir(root_dir):

        cat_dir = root_dir + "/" + cat

        if not os.path.isdir(cat_dir): continue

        cat_idx = len(cat_names)

        cat_names.append(cat)

        files = glob.glob(cat_dir+"/*.wakati")

        i = 0

        for path in files:

            print(path)

            cnt = count_file_freq(path)

            X.append(cnt)

            Y.append(cat_idx)

            if limit > 0:

                if i > limit: break

                i += 1

    return X,Y

# 단어 딕셔너리 만들기 --- (※5)

if os.path.exists(dic_file):

     word_dic = json.load(open(dic_file))

else:

    register_dic()

    json.dump(word_dic, open(dic_file,"w"))

# 벡터를 파일로 출력하기 --- (※6)

# 테스트 목적의 소규모 데이터 만들기

X, Y = count_freq(20)

json.dump({"X": X, "Y": Y}, open(data_file_min,"w"))

# 전체 데이터를 기반으로 데이터 만들기

X, Y = count_freq()

json.dump({"X": X, "Y": Y}, open(data_file,"w"))

print("ok")


[# 170826 2 mlp3-classify]


from keras.models import Sequential

from keras.layers import Dense, Dropout, Activation

from keras.wrappers.scikit_learn import KerasClassifier

from keras.utils import np_utils

from sklearn.model_selection import train_test_split

from sklearn import model_selection, metrics

import json

max_words = 56681 # 입력 단어 수: word-dic.json 파일 참고

nb_classes = 9    # 9개의 카테고리

batch_size = 64 

nb_epoch = 20

# MLP 모델 생성하기 --- (※1)

def build_model():

    model = Sequential()

    model.add(Dense(512, input_shape=(max_words,)))

    model.add(Activation('relu'))

    model.add(Dropout(0.5))

    model.add(Dense(nb_classes))

    model.add(Activation('softmax'))

    model.compile(loss='categorical_crossentropy',

        optimizer='adam',

        metrics=['accuracy'])

    return model

# 데이터 읽어 들이기--- (※2)

data = json.load(open("./newstext/data-mini.json"))

#data = json.load(open("./newstext/data.json"))

X = data["X"] # 텍스트를 나타내는 데이터

Y = data["Y"] # 카테고리 데이터

# 학습하기 --- (※3)

X_train, X_test, Y_train, Y_test = train_test_split(X, Y)

Y_train = np_utils.to_categorical(Y_train, nb_classes)

model = KerasClassifier(

    build_fn=build_model, 

    nb_epoch=nb_epoch, 

    batch_size=batch_size)

model.fit(X_train, Y_train)

print(len(X_train),len(Y_train))

# 예측하기 --- (※4)

y = model.predict(X_test)

ac_score = metrics.accuracy_score(Y_test, y)

cl_report = metrics.classification_report(Y_test, y)

print("정답률 =", ac_score)

print("리포트 =\n", cl_report)




[#170826 3 lev-distance]


# 레벤슈타인 거리 구하기

def calc_distance(a, b):

    ''' 레벤슈타인 거리 계산하기 '''

    if a == b: return 0

    a_len = len(a)

    b_len = len(b)

    if a == "": return b_len

    if b == "": return a_len

    # 2차원 표 (a_len+1, b_len+1) 준비하기 --- (※1)

    matrix = [[] for i in range(a_len+1)]

    for i in range(a_len+1): # 0으로 초기화

        matrix[i] = [0 for j in range(b_len+1)]

    # 0일 때 초깃값을 설정

    for i in range(a_len+1):

        matrix[i][0] = i

    for j in range(b_len+1):

        matrix[0][j] = j

    # 표 채우기 --- (※2)

    for i in range(1, a_len+1):

        ac = a[i-1]

        for j in range(1, b_len+1):

            bc = b[j-1]

            cost = 0 if (ac == bc) else 1

            matrix[i][j] = min([

                matrix[i-1][j] + 1,     # 문자 삽입

                matrix[i][j-1] + 1,     # 문자 제거

                matrix[i-1][j-1] + cost # 문자 변경

            ])

    return matrix[a_len][b_len]

# "가나다라"와 "가마바라"의 거리 --- (※3)

print(calc_distance("가나다라","가마바라"))

# 실행 예

samples = ["신촌역","신천군","신천역","신발","마곡역"]

base = samples[0]

r = sorted(samples, key = lambda n: calc_distance(base, n))

for n in r:

    print(calc_distance(base, n), n)




[참고자료]


https://www.data.go.kr/main.do

http://konlpy-ko.readthedocs.io/ko/v0.4.3/

https://ithub.korean.go.kr/user/total/database/corpusView.do

인공지능의 실전입문에 관한 글입니다.

알고리즘을 만드는것이 아니고, 만들어진 알로리즘을 활용하는 방법에 관한 글입니다.

자동차 운전을 위해 자동차를 만드는방법을 알필요는 없습니다. 물론 알면 좋기는 하겠지만, 서로 별도의 분야라고 할수있습니다.


본글은 지금까지 한 머신러닝에  딥러닝을 적용하는 방법에 대한 글입니다.

글의 순서는 아래와 같습니다.


=========================================================================================


1. 머신러닝에 딥러닝 적용 ==>[ # 170819 5 keras-bmi ]

  - 모델구조를 정의하고 , 모델을 컴파일 하고 , 모델을 이용해서 학습을 시킴,  이외 과정은 딥 러닝과 동일함.

  - 즉 딥러닝은 머신러닝의 한 부분임을 알수있음.

170819 6 bmi.csv


4. 참고자료


=========================================================================================


[ # 170819 5 keras-bmi ]


from keras.models import Sequential

from keras.layers.core import Dense, Dropout, Activation

from keras.callbacks import EarlyStopping

import pandas as pd, numpy as np

# BMI 데이터를 읽어 들이고 정규화하기 --- (※1)

csv = pd.read_csv("bmi.csv")

# 몸무게와 키 데이터

csv["weight"] /= 100

csv["height"] /= 200

X = csv[["weight", "height"]].as_matrix() # --- (※1a)

# 레이블

bclass = {"thin":[1,0,0], "normal":[0,1,0], "fat":[0,0,1]}

y = np.empty((20000,3))

for i, v in enumerate(csv["label"]):

    y[i] = bclass[v]

# 훈련 전용 데이터와 테스트 전용 데이터로 나누기 --- (※2)

X_train, y_train = X[1:15001], y[1:15001]

X_test,  y_test  = X[15001:20001], y[15001:20001] 

# 모델 구조 정의하기 --- (※3)

model = Sequential()

model.add(Dense(512, input_shape=(2,)))

model.add(Activation('relu'))

model.add(Dropout(0.1))

model.add(Dense(512))

model.add(Activation('relu'))

model.add(Dropout(0.1))

model.add(Dense(3))

model.add(Activation('softmax'))

# 모델 구축하기 --- (※4)

model.compile(

    loss='categorical_crossentropy',

    optimizer="rmsprop",

    metrics=['accuracy'])

# 데이터 훈련하기 --- (※5)

hist = model.fit(

    X_train, y_train,

    batch_size=100,

    nb_epoch=20,

    validation_split=0.1,

    callbacks=[EarlyStopping(monitor='val_loss', patience=2)],

    verbose=1)

# 테스트 데이터로 평가하기 --- (※6)

score = model.evaluate(X_test, y_test)

print('loss=', score[0])

print('accuracy=', score[1])




[참고자료]


https://www.docker.com/products/docker-toolbox  ==> docker 설치방법

https://www.data.go.kr/main.do