[WordPress] MTS Simple Bookingを使う

MTS Simple Bookingのhpで、Dowloadページからzipファイルをダウンロードします。
http://mtssb.mt-systems.jp/downloadp/

そして、Wordpress管理画面のプラグインページでPluginのアップロードフォームから先ほどダウンロードしたzipファイルをuploadします。

すると、管理画面上に予約システムが表示されたことがわかります。

続いてスタートガイドを参考に各種設定をしていきます。

### 予約システム各種設定
「各種設定」のページで予約機能の設定をしていきます。
予約パラメータ、施設情報、予約メール、その他のタブメニューがあります。
施設情報は予約メールに記載される内容を書きます。
予約メールには、入力項目の設定と、メール後文には「施設情報」のタブで入力した変数を入力する。

### 予約品目
予約条件設定で、件数、人数などの条件を設定できる。時間割(スタートタイム)、制約タイプなども併せて設定する。
edit時のパラメータ post=${num} をコピーしておく。

### スケジュール登録
予約システムのスケジュールに表示する

### フロントページへの登録
固定ページにbooking-formとスラックを名付ける
併せて、booking-thanksの予約完了ページを作成する

### 管理画面側
予約リストで予約状況を確認できる。
ほう、中々凄い

パラメータのutm=1618826400はlinuxtimeですね。
問題はどうやってクレジットカード決済を導入するかだな。。
mtssb-booking-form.phpでbooking-formの処理を行なっているけど、submitせずに、決済画面にパラメータも一緒に飛ばしたい。

[python3] フォームのデータを受信し表示

index.html

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
</head>
<body>
	<h1>翻訳したい言語を入力してください</h1>
	<form method="POST" action="result.py">
		<label>テキスト:</label>
		<textarea name="text"></textarea>
		<button type="submit">送信</button>
	</form>
</body>
</html>

result.py

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import cgi
import cgitb
import sys

cgitb.enable()

form = cgi.FieldStorage()

print("Content-Type: text/html; charset=UTF-8")
print("")

if "text" not in form:
	print("<h1>Erro!</h1>")
	print("<br>")
	print("テキストを入力してください!")
	print("<a href='/'><button type='submit'>戻る</button></a>")
	sys.exit()

text = form.getvalue("text")
print(text)

ん。。。なんか上手くいかんな。

[CentOS8]ビルトインサーバにアクセス出来ない時

vagrant & CentOS8でビルトインサーバを起動します。

$ python3 -m http.server 8000
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) …

なんでやねん。

Vagrantifle

  config.vm.network "private_network", ip: "192.168.34.10"

プロキシの設定等はしていない。どうやらfirewallが怪しい、ということで
$ sudo firewall-cmd –list-all
public (active)
target: default
icmp-block-inversion: no
interfaces: eth0 eth1
sources:
services: cockpit dhcpv6-client ssh
ports:
protocols:
masquerade: no
forward-ports:
source-ports:
icmp-blocks:
rich rules:

あ、やっぱり。http, 8000がアクセス出来ません。

$ sudo firewall-cmd –add-service=http –zone=public –permanent
$ sudo firewall-cmd –add-port=8000/tcp –zone=public –permanent
$ firewall-cmd –reload

出来ました。アホみたいなミスでした。
CentOS8だとデフォルトでfirewallがonになってるんですね。そういえば、sakuraのvpsなどもポートフィルタリングがデフォルトでonになってます。クワバラクワバラ

[python3] googletransで日本語->英語に翻訳する

$ sudo pip3 install googletrans
Successfully installed chardet-3.0.4 contextvars-2.4 googletrans-3.0.0 h11-0.9.0 h2-3.2.0 hpack-3.0.0 hstspreload-2020.12.22 httpcore-0.9.1 httpx-0.13.3 hyperframe-5.2.0 immutables-0.15 rfc3986-1.4.0 sniffio-1.2.0

# -*- coding: utf-8 -*-
from googletrans import Translator
translator = Translator()

translation = translator.translate("こんにちは", src='ja', dest="en")
print(translation.text)

$ python3 app.py
AttributeError: ‘NoneType’ object has no attribute ‘group’

どうやら3.0.0ではなく、4系が動いているとのこと
$ sudo pip3 uninstall googletrans
$ sudo pip3 install googletrans==4.0.0-rc1

# -*- coding: utf-8 -*-
from googletrans import Translator
translator = Translator()

translation = translator.translate("h音楽アーティストやレコードレーベルが保有する楽曲を NFT 化し世界中に販売", src='ja', dest='en')
print(translation.text)

$ python3 app.py
Music artists and songs owned by record labels NFT and sell worldwide

なかなか凄いな
formからpostして翻訳して返却したいな

[python3] 日本語⇄英語の翻訳を作りたい

機械翻訳とは、入力に対し最もらしい答えをレスポンスする

1. ルールベースの機械翻訳
原言語を構文解析し、文法構造を把握した後、辞書を用いて文節単位で目的言語へ翻訳して、最後に目的言語の文法へ翻訳した文字列を並び変える。

2. 統計的機械翻訳
原言語と目的言語の対話文から意味的な等価性、目的言語からその言語らしさを学習して確率モデルを作成し、作成したモデルから意味的な等価性と目的言語らしさの確率が最大となるような文を翻訳結果として出力する

– 翻訳確率
– 言語モデル

$ vagrant init ubuntu/focal64
vagrantfile

Vagrant.configure("2") do |config|

  config.vm.network "private_network", ip: "192.168.33.10"

  config.vm.provider "virtualbox" do |vb|
  #   # Display the VirtualBox GUI when booting the machine
  #   vb.gui = true
  #
  #   # Customize the amount of memory on the VM:
  #   vb.memory = "1024"
    vb.customize ["modifyvm", :id, "--memory", "4096"]
  end

  if Vagrant.has_plugin?("vagrant-vbguest")
      config.vbguest.auto_update = false  
  end
end

$ vagrant up
$ vagrant ssh
$ sudo apt update

### Mosesのインストール
翻訳モデルと言語モデルから翻訳結果を出力するデコーダの役割をするMosesをインストールする

– パッケージインストール
$ sudo apt-get install build-essential git-core pkg-config automake libtool wget zlib1g-dev python-dev libbz2-dev
– Mosesのコンパイルに必要なboostのセットアップ
$ wget http://downloads.sourceforge.net/boost/boost_1_59_0.tar.bz2
$ tar jxvf boost_1_59_0.tar.bz2
$ cd boost_1_59_0
$ ./bootstrap.sh
$ ./b2 -j4 –prefix=$PWD –libdir=$PWD/lib64 –layout=system link=static install || echo FAILURE

### Mosesセットアップ
$ git clone https://github.com/moses-smt/mosesdecoder.git
$ cd mosesdecoder
$ ./bjam –with-boost=/home/vagrant/nlp/boost_1_59_0 -j4
You MUST do 3 things before sending to the mailing list:
1. Subscribe to the mailing list at http://mailman.mit.edu/mailman/listinfo/moses-support
2. Attach build.log.gz to your e-mail
3. Say what is the EXACT command you executed when you got the error
ERROR
ん????

[python3] twitterのつぶやきからmecabとwordcloudで解析する

# -*- coding: utf-8 -*-
import MeCab
import matplotlib.pyplot as plt
import csv
from wordcloud import WordCloud

dfile = "test.txt"

fname = r"'" + dfile + "'"
fname = fname.replace("'","")

mecab = MeCab.Tagger("-Owakati")

words = []

with open(fname, 'r', encoding="utf-8") as f:

	reader = f.readline()

	while reader:

		node = mecab.parseToNode(reader)

		while node:
			word_type = node.feature.split(",")[0]

			if word_type in ["名詞", "動詞", "形容詞", "副詞"]:

				words.append(node.surface)

			node = node.next

		reader = f.readline()

font_path = "NotoSansMonoCJKjp-Regular.otf"

txt = "	".join(words)

stop_words = ['そう', 'ない', 'いる', 'する', 'まま', 'よう', 'てる', 'なる', 'こと', 'もう', 'いい', 'ある', 'ゆく', 'れる', 'ん', 'の']

wordcloud = WordCloud(background_color="black", font_path=font_path, stopwords=set(stop_words),
	width=800, height=600).generate(txt)

wordcloud.to_file('./wordcloud.png')

なるほど、一応できたか
キーワードを自然言語処理ではなく、「自民 -RT」でstop_wordsに自民を指定してやってみる

政党名が多くて、ちょっと期待してたのと違うな。。。

[python3] twitterのつぶやきを取得

pythonでtwitterのつぶやきを取得して、wordcloudでの表示をやってみます。

$ sudo pip3 install tweepy
// mecab, wordcloudはインストール済

import tweepy
import datetime

keyword = "自然言語処理 -RT"
dfile = "test.txt"

jsttime = datetime.timedelta(hours=9)

Consumer_key = ''
Consumer_secret = ''
Access_token = ''
Access_secret = ''

auth = tweepy.OAuthHandler(Consumer_key, Consumer_secret)
auth.set_access_token(Access_token, Access_secret)

api = tweepy.API(auth, wait_on_rate_limit = True)

q = keyword

tweets_data = []


for tweet in tweepy.Cursor(api.search, q=q, count=5,tweet_mode='extended').items():

	tweets_data.append(tweet.full_text + '\n')

fname = r"'" + dfile + "'"
fname = fname.replace("'", "")

with open(fname, "w", encoding="utf-8") as f:
	f.writelines(tweets_data)

twitterのdevアカウントがあれば、取得は容易

[python3] BeautifulSoupでプロキシ経由でスクレイピングする

beautifulsoupでUserAgentとProxyを設定する

# -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
from pprint import pprint

URL = 'https://news.yahoo.co.jp/'
USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36"

proxies = {
	'http':'http://43.248.24.158:51166/',
	'https':'http://43.128.23.107:8080/'
}
headers = {"User-Agent": USER_AGENT}

resp = requests.get(URL, proxies=proxies, headers=headers, timeout=10)
resp.encoding = 'utf8' 
soup = BeautifulSoup(resp.text, "html.parser")

titles = soup.select('.sc-esjQYD a')
titles = [t.contents[0] for t in titles]

pprint(titles)

$ python3 app.py
[‘春の嵐 太平洋側激しい雷雨も’,
‘コロナワクチン種類選択OKに’,
‘北ミサイル 安保理緊急協議へ’,
‘生息域40年で倍 減らぬシカ’,
‘中国の謎の文明 黄金仮面発見’,
‘羽生まるで別人 専門家の目’,
‘みちょぱ 結婚の話している’,
‘水卜アナ 局アナ続ける理由’]

なるほど、BSでも行けますね、OK

[Python3] 歌詞をスクレイピングして頻出単語をwordcloudで表示

$ sudo pip3 install pandas

# -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
import pandas as pd
import time

list_df = pd.DataFrame(columns=['歌詞'])

for page in range(1, 3):

	base_url = 'https://hogehoge'

	url = 'https://hogehoge/' + str(page) + '/'
	response = requests.get(url)
	soup = BeautifulSoup(response.text, 'lxml')
	links = soup.find_all('td', class_='side td1')
	for link in links:
		a = base_url + (link.a.get('href'))

		response = requests.get(a)
		soup = BeautifulSoup(response.text, 'lxml')
		song_lyrics = soup.find('div', itemprop='lyrics')
		song_lyric = song_lyrics.text
		song_lyric = song_lyric.replace('\n', '')
		time.sleep

		tmp_se = pd.DataFrame([song_lyric], index=list_df.columns).T
		list_df = list_df.append(tmp_se)

print(list_df)
list_df.to_csv('list.csv', mode='a', encoding='cp932')

### janomeによる形態素解析
$ sudo pip3 install janome

# -*- coding: utf-8 -*-
from janome.tokenizer import Tokenizer
import pandas as pd
import re

df_file = pd.read_csv('list.csv', encoding='cp932')

song_lyrics = df_file['歌詞'].tolist()

t = Tokenizer()

results = []

for s in song_lyrics:
	tokens = t.tokenize(s)

	r = []

	for tok in tokens:
		if tok.base_form == '*':
			word = tok.surface
		else:
			word = tok.base_form

		ps = tok.part_of_speech

		hinshi = ps.split(',')[0]

		if hinshi in ['名詞','形容詞','動詞', '副詞']:
			r.append(word)

	rl = (' '.join(r)).strip()
	results.append(rl)
	result = [i.replace('\u3000', '') for i in results]
	print(result)

text_file = 'wakati_list.txt'
with open(text_file, 'w', encoding='utf-8') as fp:
	fp.write("\n".join(result))

### wordcloud
$ sudo pip3 install wordcloud
https://www.google.com/get/noto/
Noto Sans CJK JPをダウンロードしてNotoSansMonoCJKjp-Regular.otfを使います。

# -*- coding: utf-8 -*-
from wordcloud import WordCloud

text_file = open('wakati_list.txt', encoding='utf-8')
text = text_file.read()

fpath = 'NotoSansMonoCJKjp-Regular.otf'

stop_words = ['そう', 'ない', 'いる', 'する', 'まま', 'よう', 'てる', 'なる', 'こと', 'もう', 'いい', 'ある', 'ゆく', 'れる', 'ん', 'の']

wordcloud = WordCloud(background_color='white',
	font_path=fpath, width=800, height=600, stopwords=set(stop_words)).generate(text)

wordcloud.to_file('./wordcloud.png')

$ python3 word_cloud.py

LunaSeaでやった場合

lunaseaは「夜」が多いなwww

なるほど、面白いなこれ。
応用としては、、、
エンジニアだと技術情報だけど、ファッション、旅行、スポーツなどでやりたい。特に旅行は万人受けするからなー