Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Thursday, April 23, 2015

Instagram auto like a new post of friend's

Google App Engine 提供的免费服务可以很容易的拿来实现一些自己的小想法,比如下面的两个例子。
Instagram自动点赞
自动为你Instagram上关注的一个或几个朋友发布的新照片点赞

1. 注册成为[Instagram Developer](http://instagram.com/developer). Register Client 获得Client ID 和 Client Secret.
2. 在[Google App Engine](https://appengine.google.com/)上新建一个Application.
3. 调用Instagram的API 实现点赞功能。首先在[Jelled](http://jelled.com/instagram/lookup-user-id)上获得需要关注点赞用户的UserID. 获得用户的info, 然后找到用户最新发布的一张照片,判断是否已经点赞,若是没有,则调用like的API点赞。将整个脚本用GAE支持的webapp2 RequestHandler实现get和post。我用的是Instagram的 Media Endpoints 和 Like Endpoints API.
https://api.instagram.com/v1/users/UserID/media/recent/?access_token=ACCESS-TOKEN&count=1
返回的是Json数据,从返回的数据中得到mediaID,也就是关注用户最新照片的ID。然后like这张图片。
setLike_req = "https://api.instagram.com/v1/media/%s/likes" %(mi)
values = {'access_token':ACCESS_TOKEN}
setLike_return = json.loads(urllib2.urlopen(urllib2.Request(setLike_req,urllib.urlencode(values))).read())
4. Google App Engine Configure, Deploy. GAE方便之处就在于configure和deploy都很简单,只需在app.yaml中添加application即可。
application: your-app-id
version: 1
runtime: python27
api_version: 1
threadsafe: true
handlers:
- url: /.*
  script: likeinsta.application
然后建立后台cron job,只要新建一个cron.yaml然后可设置schedule时间,如every 1 mins,程序每隔一分钟检测一下关注对象的Instagram有没有新照片。
cron: 
- description: main job 
  url: /likeinsta 
  schedule: every 1 mins 
Code: likeinsta-Github
Useful link: python-instagram
Related: 为女神微博点赞

获得自己的知乎专栏上的订阅列表

主要涉及登录和爬虫,使用BeautifulSoup

Github上已经有大神实现了用python获得知乎信息的库zhihu-python,看了一下发现没有专栏的部分,于是参考获得关注者的code写了获得关注专栏的部分。

测试结果,以我自己知乎账号为例:

from zhuanlan import Zhuanlan

user_id = "xiwan" #userID
zhuanlan = Zhuanlan(user_id)
print zhuanlan.get_zhuanlan_num()#获得关注专栏数目
zhuanlan.get_zhuanlan_list()#打印关注专栏名称
结果如下:

凝创摄影小课堂  摄影的那些事儿  摄影笔记  豚食记  喂,两千块牛排  知乎日报  幸福课   我的太阳  木易聊影  王路的粽子铺  White Room设计日报  YADI, Running Bravely !  汇贤雅叙  Pinapps  祇园  量子世界  如何做你所爱  知乎周刊  caoz的梦呓 与时间无关的故事李故事  软件测试  那些我想和你们分享的事  触乐-移动游戏新媒体  那个谜一样的生物  微醺之美  黑白漫文化  游戏时代 乌云知识库  今日最佳  Akira 研究所  琉森:抽油烟少女  你可能不知道的香港  女院的教室  Hacker's log  笑忘书的笑忘书  《偏方》非周刊
林建入的软件设计之路  宋世泊  中国游戏幕后史  热璞科技  万物为师  锦衣小筑  酷爱撒泼  看不同  匡靖  我们的征途是星辰大海  理财牛  懒人在思考  走遍岛国  三元手闲录  彩云追悦  大豆,音乐以及其他  瓜园耕读  【一片胡言乱语】  比生活简单多了 与食巨近贱多食广地蹦跶在不列颠  谢熊猫出没注意  知影  瞎胡啰啰  张佳玮写字的地方  最美应用  All About Apple  如何处理一千张废纸 道哥的黑板报  鸡汤、励志、三流成功学集中营。  MacTalk

同样的可以获得专栏的其他信息,如赞同数,评论,链接等等。

Source code: zhihuzhuanlan-Github
Reference: zhihu-python

Monday, May 12, 2014

tkinter callback update GUI

Tkinter is a python standard GUI package, it is easy to use if you want to do some simple GUI tasks. To control the widget action, we need to add callback method. while the GUI won't update until the callback method finished. For example, if I want to display a image in a window, and click a button to change to photo to another one.
class ClientGUI(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()
    def initUI(self):
        self.parent.title("demo")
        self.pack(fill=BOTH, expand=1)
        self.changeButton = Button(self, text="changePic", width = 10, height = 1, command=self.onClick)
        self.changeButton.place(x=10,y=100)
        self.initialImage = Image.open('pic1.jpg')
        tkimage = ImageTk.PhotoImage(self.initialImage)
        self.imgLabel = Label(self,image=tkimage)
        self.imgLabel.image = tkimage
        self.imgLabel.place(x=10,y=150)
       
    def onClick(self):
        imagedata = Image.open("pic2.jpg")
        img = ImageTk.PhotoImage(imagedata)
        print img,"\n"
        self.imgLabel.configure(image = img)
        self.imgLabel.image = img
This code works fine to display the picture and change the picture when button clicked. But if we add some code in the onClick method, like this:
for i in range(0,10):
    time.sleep(1)
Then after clicking the button, it will take 10 seconds before the image change. Same thing happens when there is a loop in the callback method, unless the loop is finished, this method won't callback. So what if we want to update the picture immediately we click the button, it means update the GUI, actually we only need to add one single line to solve this problem, add
self.update()

Wednesday, April 2, 2014

list update

If you need to modify the sequence you are iterating over while inside the loop (for example to duplicate selected items), it is recommended that you first make a copy. Iterating over a sequence does not implicitly make a copy. The slice notation makes this especially convenient:

for w in words[:]:  # Loop over a slice copy of the entire list.
    if len(w) > 6:
        words.insert(0, w)

#words: ['defenestrate', 'cat', 'window', 'defenestrate']

Monday, July 8, 2013

Record from mic by Python

There are many module you can use to do this.


1. PyAudio

import pyaudio
import wave

CHUNK = 1024 
FORMAT = pyaudio.paInt16 #paInt8
CHANNELS = 2 
RATE = 44100 #sample rate
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"

p = pyaudio.PyAudio()

stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK) #buffer

print("* recording")

frames = []

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data) # 2 bytes(16 bits) per channel

print("* done recording")

stream.stop_stream()
stream.close()
p.terminate()

wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()

2. PyMedia

import time, sys
import pymedia.audio.sound as sound
import pymedia.audio.acodec as acodec

def voiceRecorder( secs, name ):
  f= open( name, 'wb' )
  # Minimum set of parameters we need to create Encoder

  cparams= { 'id': acodec.getCodecId( 'mp3' ),
             'bitrate': 128000,
             'sample_rate': 44100,
             'channels': 2 } 
  ac= acodec.Encoder( cparams )
  snd= sound.Input( 44100, 2, sound.AFMT_S16_LE )
  snd.start()
  
  # Loop until recorded position greater than the limit specified

  while snd.getPosition()<= secs:
    s= snd.getData()
    if s and len( s ):
      for fr in ac.encode( s ):
        # We definitely should use mux first, but for

        # simplicity reasons this way it'll work also

        f.write( fr )
    else:
      time.sleep( .003 )
  
  # Stop listening the incoming sound from the microphone or line in

  snd.stop()

# -------------------------------------------------------------------
# Record stereo sound from the line in or microphone 
# and save it as mp3 file
# Specify length and output file name
# http://pymedia.org/

if __name__ == "__main__":
  if len( sys.argv )!= 3:
    print 'Usage: voice_recorder  '
  else:
    voiceRecorder( int( sys.argv[ 1 ] ), sys.argv[ 2 ]  )

3. alsaaudio

import sys
import time
import getopt
import alsaaudio

def usage():
    sys.stderr.write('usage: recordtest.py [-c ] \n')
    print 'haha4'
    sys.exit(2)

if __name__ == '__main__':
    
    print 'haha1'
    
    card = 'default'

    opts, args = getopt.getopt(sys.argv[1:], 'c:')
    for o, a in opts:
        if o == '-c':
            card = a

        if not args:
            usage()
    f = open(args[0], 'wb')
    # Open the device in nonblocking capture mode. The last argument could
    # just as well have been zero for blocking mode. Then we could have
    # left out the sleep call in the bottom of the loop
    
    inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NONBLOCK, card)
    
    # Set attributes: Mono, 44100 Hz, 16 bit little endian samples
    
    inp.setchannels(1)
    inp.setrate(44100)
    inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)
    
    # The period size controls the internal number of frames per period.
    # The significance of this parameter is documented in the ALSA api.
    # For our purposes, it is suficcient to know that reads from the device
    # will return this many frames. Each frame being 2 bytes long.
    # This means that the reads below will return either 320 bytes of data
    # or 0 bytes of data. The latter is possible because we are in nonblocking
    # mode.
    
    inp.setperiodsize(48)

    print 'haha2'
    loops = 100
    while loops > 0:
        print 'haha3'
        loops -= 1
        # Read data from device
        l, data = inp.read()
        print len(data)
        print l
        if l:
            f.write(data)
            time.sleep(.001)

Wednesday, July 3, 2013

Thursday, June 13, 2013

Install PyQt on Mac OSX Lion 10.8.4

I have been searching for ways to successfully install PyQt4 on my macbook pro with Lion 10.8.4. Following are the steps:
source from http://blog.csdn.net/watsy/article/details/8857252, thanks to watsy.
1. Download and install Qt: http://qt-project.org/downloads What I downloaded is Qt 5.0.2 for Mac(404MB), Decompress and follow the steps, quite easy.
2. Download SIP: http://www.riverbankcomputing.co.uk/software/sip/download
I download the development snapshots sip-4.14.7-snapshot-74e1df1d9940.tar.gz
Decompress it. Commands in Terminal:
cd sip-4.14.7-snapshot-74e1df1d9940
python configure.py -d /Library/Python/2.7/site-packages --arch=x86_64
(change the arch to i386 if your mbp is 32 bits)
make
sudo make install
3.Download PyQt4: http://www.riverbankcomputing.co.uk/software/pyqt/download
I downloaded PyQt-mac-gpl-4.10.2-snapshot-11b3001947c9.tar.gz
cd PyQt-mac-gpl-snapshot-4.10.2-ffcf323516fc
python configure-ng.py -q /Users/qqli/Qt5.0.2/5.0.2/clang_64/bin/
make -d /Library/Python/2.7/site-packages/ --sip /System/Library/Frameworks/Python.framework/Versions/2.7/bin/sip
make
sudo make install
After all the steps, you can try from PyQt4 import QtGui if there is no error message, Congratulation. Have fun with PyQt :)

Wednesday, June 12, 2013

Real time voice chat example in python using pyaudio

PyAudio home page:

http://people.csail.mit.edu/hubert/pyaudio

There is download links and install instructions for windows/OSX/linux. Following is the code for the audio transmission between server and client in one direction. First the client records the audio from the mic and store in a buffer and then transmit by TCP socket. The server receives the data and play out by speaker.
For Client:

import socket
import pyaudio
import wave

#record
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SECONDS = 40

HOST = ''    # The remote host
PORT = 50007              # The same port as used by the server

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))

p = pyaudio.PyAudio()

stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK)

print("*recording")

frames = []

for i in range(0, int(RATE/CHUNK*RECORD_SECONDS)):
 data  = stream.read(CHUNK)
 frames.append(data)
 s.sendall(data)

print("*done recording")

stream.stop_stream()
stream.close()
p.terminate()
s.close()

print("*closed")

For Server:


# Echo server program
import socket
import pyaudio
import wave
import time

CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SECONDS = 4
WAVE_OUTPUT_FILENAME = "server_output.wav"
WIDTH = 2
frames = []

p = pyaudio.PyAudio()
stream = p.open(format=p.get_format_from_width(WIDTH),
                channels=CHANNELS,
                rate=RATE,
                output=True,
                frames_per_buffer=CHUNK)


HOST = ''                 # Symbolic name meaning all available interfaces
PORT = 50007              # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
data = conn.recv(1024)

i=1
while data != '':
    stream.write(data)
    data = conn.recv(1024)
    i=i+1
    print i
    frames.append(data)

wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()

stream.stop_stream()
stream.close()
p.terminate()
conn.close()

In the server part, I store the received audio into an wav file just for record. If you want to do voice chat, you can add another process and deal with the echo cancellation. Also for better audio quality and noise reduction, you may add threshold at the client. Also for better performance under worse network situation, you may need to try compress the audio before transmission.