最近の更新

関連


その他いろいろ

多機能フィードリーダSynapse製作中

2月までは目が回るほど忙しい

MODxでつくる! 最強のCMSサイト カバー
MODxでつくる! 最強のCMSサイト

YouTubeのfmt22をタイトルつきで保存したかったので手抜きPythonスクリプトを書いてみた。

$ python yt.py -d ./  'http://..../watch?=....'  'http://..../watch?=....' 

とか

$ python yt.py -d ./
(標準入力に1行1URLでURLのリストを渡す)

のようにして使う。
-dで指定したディレクトリ(省略時はカレントディレクトリ)に”元のタイトル (YouTube HD).mp4″というファイル名で保存。

昔書いたダウンローダを直しても良かったのだが、ソースを見るのも面倒だったので書き下ろし。汚い。
あとJavaScriptの辞書をPythonの辞書にするのにevalを使うという恐ろしいことをしている。

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

import os, sys, re, urllib2, getopt

def dodownload(url, path):
        """download [url] to [path]"""
        v = urllib2.urlopen(url)
        fo = file(path, 'wb')
        buf = []
        while True:
                buf = v.read(1024*1024)
                if len(buf)==0:
                        break
                fo.write(buf)
                sys.stdout.write(u'.')
                sys.stdout.flush()
        print
        fo.close()
        v.close()
        return True

def clean_title(title):
        title = re.sub(ur':|\||\\|/', '', title)
        title = re.sub(ur'&', '&', title)
        return title

def download(url, dir):
        headers = {
                'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; ja; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5'
                }
        # get html
        req = urllib2.Request(url, None, headers)
        res = urllib2.urlopen(req)
        html = res.read()
        res.close()
        # get title
        title_mo = re.compile(ur'<meta name="title" content="(.*?)">').search(html)
        title = title_mo.group(1)
        title = clean_title(title)
        # get swfArgs
        swfArgs_mo = re.compile(ur'var swfArgs = ({.*?});', re.S).search(html)
        swfArgs_js = swfArgs_mo.group(1).replace('null', 'None')
        swfArgs = eval(swfArgs_js)
        # get Video
        video_url = 'http://jp.youtube.com/get_video?video_id=%(video_id)s&t=%(t)s&el=detailpage&ps=&fmt=22' % swfArgs
        print title, video_url

        # download video
        dlpath = os.path.join(dir, title+'(YouTube HD).mp4')
        if not os.access(dlpath, os.F_OK):
                return dodownload(video_url, dlpath)
        return False

options, rest = getopt.getopt(sys.argv[1:], 'd:h')
opt_dict = {
        'dir': './'
        }
for o, v in options:
        if o=='-d':
                opt_dict['dir'] = v
        if o=='-h':
                print 'usage: echo URLS | python yt.py -d SAVE_DIR'
                sys.exit(0)

url_list = rest

if len(url_list)==0:
        url_list = sys.stdin.readlines()

for u in url_list:
        try:
                if download(u, opt_dict['dir']):
                        continue
        except Exception, e:
                print e
        print 'failed'

あふ的操作感+Python拡張可能な2画面ファイラ、内骨格
config.pyを弄ることでキー割り当てなどのきめ細かい設定が可能ですが、ファイラというアプリの特性上、ローカルな環境に応じた設定(ジャンプ先リストなど)が多くなります。

複数の環境で内骨格を使う場合、共通部分とローカルな部分に分けられたら便利だと思い、extentionsに置いたlocal_config.pyをconfig.pyの後に読み込むデコレータを書いてみました。

config.pyのdef configure前に以下のコードを書き、


# ローカル設定を読み込むデコレータ
def localize(f):
    def localized_configure(window):
        f(window)
        try:
            import local_config
            reload(local_config)
            eval("local_config.%s(window)" % f.__name__)
        except ImportError:
            print "no local configure file."
    return localized_configure

configure(_*)にデコレータを適用します。


# 設定処理
@localize ←これ
def configure(window):
       (略)

extentions/local_configure.pyに普通のconfig.pyと同様にconfigure(_*)を書けば、
config.pyに書かれたconfigure(_*)が呼び出された後にlocal_configure.py上の対応する関数が呼ばれます。

もしかしたらもっと上手い方法があるかもしれませんが、一応これでも不便無く使えています。

PythonのTwitter APIラッパー、python-twitterを使ってみました。

% sudo easy_install python-twitter

import twitter
api = twitter.Api()
statuses = api.GetUserTimeline('user_name')
print 'statuses'
print statuses
print '-'*20
for s in statuses:
        print 'status:'
        print s.text
return statuses

発言は取れますが、twitter.Statusにin_reply_to_user_id, in_reply_to_status_idが無いので、会話の流れがよくわからない。

ということでパッチを書きました。


--- twitter.py  2007-07-16 02:38:54.000000000 +0900
+++ twitter.py     2008-09-11 13:50:12.000000000 +0900
@@ -41,7 +41,9 @@
                id=None,
                text=None,
                user=None,
-               now=None):
+               now=None,
+               in_reply_to_user_id=None,
+               in_reply_to_status_id=None):
     '''An object to hold a Twitter status message.

     This class is normally instantiated by the twitter.Api class and
@@ -66,6 +68,8 @@
     self.text = text
     self.user = user
     self.now = now
+    self.in_reply_to_user_id = in_reply_to_user_id
+    self.in_reply_to_status_id = in_reply_to_status_id

   def GetCreatedAt(self):
     '''Get the time this status message was posted.
@@ -281,7 +285,9 @@
     return Status(created_at=data.get('created_at', None),
                   id=data.get('id', None),
                   text=data.get('text', None),
-                  user=user)
+                  user=user,
+                  in_reply_to_user_id=data.get('in_reply_to_user_id', None),
+                  in_reply_to_status_id=data.get('in_reply_to_status_id', None))

 class User(object):

これで返信先も表示できます。


import twitter
def run():
        api = twitter.Api()
        statuses = api.GetUserTimeline('user_name')
        for s in statuses:
                print 'status:'
                if s.in_reply_to_status_id:
                        status = api.GetStatus(s.in_reply_to_status_id)
                        print '> (%s) ' % status.user.screen_name, status.text
                print s.text
        return statuses

if __name__=='__main__':
        run()

サムネイルも併せて保存するオプション-tを新設。

詳細・ダウンロードはこちらから。dlnico
例によってWindows exeバージョンはdlnico 2.72から。

リスト保存の順番を保持、ニコニコ動画の仕様変更(20080305)に対応

詳細・ダウンロードはこちらから。dlnico
例によってWindows exeバージョンはdlnico 2.71から。

2008 02 26

Stage6終了

2/28にStage6がサービス終了するそうですね。保存し忘れた動画のためのDL補助スクリプト書きました。st6.zip
> st6.py output_file stage6_url [max_page_no]
のようにして検索結果やユーザVideoのURLを渡すと、"Next"を辿って全ての.divxを列挙してIrvineリスト(irv)形式で保存します。

ニコニコ動画の仕様変更(20080209動作確認)に対応。

詳細・ダウンロードはこちらから。dlnico
例によってWindows exeバージョンはdlnico 2.61から。

2008 02 8

flvcat v1.10

FLVファイルを結合するPythonスクリプト、flvcat v1.10を公開しました。py2exeで固めたWindows exe版もあります。
flvcat

–audio-offsetオプションにより、音声を指定ミリ秒遅らせることができます。

2008 02 1

flvcat v1.00

FLVファイルを結合するPythonスクリプト(CUI)、flvcat v1.00を公開しました。py2exeで固めたWindows exe版もあります。
flvcat

> flvcat.py -o 出力ファイル名 [入力ファイル名1, 2, ..]
で入力ファイルを与えた順番に結合したFLVを生成します。

cygwin上のPython2.5、windowsコマンドプロンプト上のPython2.5で動作を確認。

雑なコードをそのうち一新してflvcat, dlnico, dlyouku, YouTubeList2irvを纏めたいと思ったりもしますが、暇はなかなかありません。

2008 01 31

dlyouku v1.00

Pythonで書いたyouku.comのflvダウンローダ、dlyoukuを公開しました。

分割されている動画にも一応対応しています。Windows exe版もあります。

次のページ »