PiMagの自動・外部制御にむけて(1)

イメージ
PiMag(ポータブル40テスラ装置)にはraspberry piが搭載されていて、そこにに置いた自作pythonプログラムで制御しています。そこでtkinterというpython標準のGUIを使用しています。そのGUI特有の機能を使っています。 問題は外部でリモートコントロールしたり、自動計測することを考えたときに、GUIベースなのは微妙と言うことです。今のソフトはtkinterの機能を駆使しているので、フレキシブルじゃないです。そこで 「テキスト設定ファイル」に値を読み書きすることを基本とする、というプログラムにしようと思います。ボタンを押しても、まずはテキストファイルの値を書き換え、それを別のプログラムが参照して次の動きを作る、ということです。 そうすれば、GUIのボタンを押さなくても、外部からテキストファイルを書き換えることで、ボタンを押すようなことができそうです。 そのテキストファイルは複数のプログラムが参照する可能性があるので、ファイルを安全に読み書きできる必要があります。 ファイル名readerwriter.pyとして下記を作ります。 from filelock import FileLock def safe_write(filename, content): lock_file = filename + ".lock" with FileLock(lock_file): with open(filename, 'w') as f: f.write(content) def safe_read(filename): lock_file = filename + ".lock" with FileLock(lock_file): with open(filename, 'r') as f: return f.read() 実行結果は下記です。 これを応用して、望みのプログラムを作ろうと思います。

arxivの記事をpythonとmacの機能で英語音声に変換する

使っているのは、

  • python
  • arxivライブラリ(pip install arxivでok)
  • sayコマンド(macでテキストファイルを音声m4aファイルに変換できる)
  • ffmpeg(m4aをmp3に変換できる。macではhomebrewでインストールできる)
  • apple siliconのmac

pythonでarxivのAPIをつかい、cond-matで3日前に発表された論文の情報をもらってきます。ローカルにテキストファイルにして保存します。

https://info.arxiv.org/help/api/index.html

# making text file

import arxiv
import numpy as np
import datetime


def spaceinsert(tin):
    t2 = ' ' * len(tin)
    tout = ''
    for i in range(len(tin)):
        tout += tin[i] + t2[i]
    return tout

lastdays = 3
day = datetime.date.today() - datetime.timedelta(days=lastdays)
fday = day.strftime ( '%Y%m%d' )

floc = f'./dat/arxiv_cm_{fday}'
txtloc = floc + '.txt'


f = open(txtloc, 'w')

print(f'date: {day.strftime ( '%B %d, %Y' )}.')
f.write(f'Date: {day.strftime ( '%B %d, %Y' )}.\n\n\n\n')

# Construct the default API client.
client = arxiv.Client()

# Search for the 10 most recent articles matching the keyword "quantum."
search = arxiv.Search(
  query = f'cat:cond-mat.* AND submittedDate:[{fday}0000 TO {fday}2359]',
  max_results = 300,
  sort_order = arxiv.SortOrder.Descending,
  sort_by = arxiv.SortCriterion.SubmittedDate
)

results = client.results(search)


i = 1
for r in client.results(search):
    f.write(f'article number: {i}\n\n')
    f.write(f'entry ID: {spaceinsert(r.entry_id[21:])}.\n\n')
    
    print(f'{i}: {r.title.replace('$', '').replace('\\', '')}')
    f.write(f'Title:\n\n{r.title.replace('$', '').replace('\\', '')}\n\n')
    
    f.write('Summary \n\n')
    f.write(f'{r.summary.replace('$', '').replace('\\', '')}\n\n')
    
    f.write('Authors: \n\n')
    lim = len(r.authors)
    j = 1
    for author in r.authors:
        f.write(f'{author.name}\n\n')
        if j < lim:
            f.write('and \n\n')
            j += 1

    if r.comment == None:
        pass
    else:
        f.write('comment \n\n')
        f.write(f'{r.comment}\n\n')

    if r.journal_ref == None:
        pass
    else:
        f.write('journal references \n\n')
        f.write(f'{r.journal_ref}\n\n\n')

    f.write('\n'*3)
    i += 1

f.close()

下記はタイトルだけ表示された実行結果。排出されたテキストファイルには、タイトル、著者、アブストラクト、コメントが羅列されています。

date: April 30, 2025.
1: Diffusion and instabilities in large-N holographic Fermi liquids: the vector fluctuations of the electron star
2: A probabilistic approach to system-environment coupling
3: Thermodynamic potentials from a probabilistic view on the system-environment interaction energy
4: Expanding Active Matter to the Third Dimension: Exploring Short and Long-Range Particle-Wall Interactions
5: Roadmap on Advancements of the FHI-aims Software Package
6: Twist Engineering of Anisotropic Excitonic and Optical Properties of a Two-Dimensional Magnetic Semiconductor
7: Symmetry induced pairing in dark excitonic condensate at finite temperature
8: Interlayer Coupling-Induced Quantum Phase Transition in Quantum Anomalous Hall Multilayers
9: Rare Trajectories in a Prototypical Mean-field Disordered Model: Insights into Landscape and Instantons
10: Contemporary tensor network approaches to gapless and topological phases in an extended Bose-Hubbard ladder


次は、テキストファイルを音声に変換します。macのsayコマンドを使って、テキストファイルをm4aにしてます。最後にffmpegを使って、m4aをmp3にしてます。これはなくても良いです。

 

# making audio file

# import datetime

import arxiv
import numpy as np
import datetime

lastdays = 3
day = datetime.date.today() - datetime.timedelta(days=lastdays)
fday = day.strftime ( '%Y%m%d' )
floc = f'./dat/arxiv_cm_{fday}'
txtloc = floc + '.txt'

outloc = floc + '.m4a'
!say -f $txtloc -o $outloc

mp3out = floc + '.mp3'
!ffmpeg -i $outloc $mp3out
!mv $mp3out /Users/akihiko/Library/Mobile\ Documents/com\~apple\~CloudDocs/arxiv
!rm $outloc

ファイルの保存場所は適当に変えてください。

 

以上です。これであなたも、英語のリスニングと先端物理に強くなれそうですね!!

 

コメント

このブログの人気の投稿

しばらく、うまく見られなかった・・・・しかし解決の兆し

いろんなデータがではじめたか?