tfliteをマルチコア(ラズパイ5)で動かした時の性能改善

従来のコードからの変更箇所、

    1. サーバーにFlaskではなく正式運用推奨のWSGIサーバーに変更
    2. スレッド数をsingleからラズパイ5のコア数である4に変更(num_threads)
# work on Flask server
# server will be activated only when client request is occured
#
#
from flask import Flask, jsonify
import cv2
import numpy as np
import tflite_runtime.interpreter as tflite
from picamera2 import Picamera2
from waitress import serve

app = Flask(__name__)

# モデル・ラベル初期化
interpreter = tflite.Interpreter(model_path="efficientdet_lite0.tflite", num_threads=4)
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
with open("coco_labels.txt", "r") as f:
    labels = [line.strip() for line in f.readlines()]

# カメラ初期化
picam2 = Picamera2()
picam2.preview_configuration.main.size = (640, 480)
picam2.preview_configuration.main.format = "RGB888"
picam2.preview_configuration.align()
picam2.configure("preview")
picam2.start()

def preprocess_image(image):
    resized = cv2.resize(image, (320, 320))
    resized = resized[:, :, [2, 1, 0]]  # BGR→RGB
    return np.expand_dims(resized, axis=0).astype(np.uint8)

def postprocess_results(boxes, scores, classes, count, image_shape, labels):
    detections = []
    for i in range(count):
        if scores[i] > 0.4:
            ymin, xmin, ymax, xmax = boxes[i]
            left, right, top, bottom = (
                int(xmin * image_shape[1]),
                int(xmax * image_shape[1]),
                int(ymin * image_shape[0]),
                int(ymax * image_shape[0])
            )
            detections.append({
                'box': [left, top, right, bottom],
                'class_id': int(classes[i]),
                'score': float(scores[i]),
                'label': labels[int(classes[i])] if int(classes[i]) < len(labels) else f"id:{int(classes[i])}"
            })
    return detections

def detect_once():
    frame = picam2.capture_array()
    input_data = preprocess_image(frame)
    interpreter.set_tensor(input_details[0]['index'], input_data)
    interpreter.invoke()
    boxes = interpreter.get_tensor(output_details[0]['index'])[0]
    classes = interpreter.get_tensor(output_details[1]['index'])[0]
    scores = interpreter.get_tensor(output_details[2]['index'])[0]
    count = int(interpreter.get_tensor(output_details[3]['index'])[0])
    detections = postprocess_results(boxes, scores, classes, count, frame.shape, labels)
    return detections

@app.route('/detect', methods=['GET'])
def detect_route():
    detections = detect_once()
    return jsonify(detections)

if __name__ == '__main__':
	# when you limit access only from the local machine, use a loopback address instead of 0.0.0.0
    #app.run(host='0.0.0.0', port=5000)
    serve(app, host='0.0.0.0', port=5000)

時間測定用のスクリプトは、

#
# test script for image detect function(tflite server)
#

import requests
import time

if __name__ == '__main__':
    time1 = time.time()
    result = requests.get('http://rasp5.local:5000/detect').json()
    time2 = time.time()
    print('func1: {:.3f} sec'.format(time2 - time1))
    # 'label'が'person'を含んでいるかを判定
    person_detected = any(item['label'] == 'person' for item in result)
    
    if person_detected:
        print("Person detected!")
    else:
        print("No person detected.")

測定結果、

    1. 最初のアクセスはmDNSが動作して遅くなる、以降はキャッシュが有効になるのでアドレス引きの時間は見えなくなる
    2. マルチコアでの改善率は2.5倍ぐらい高速化だから、こんなもんかのレベルで良くてもせいぜい3倍ぐらいかと思っていたので
    3. サーバーにWSGI使っても見かけレスポンス時間が早くなったとは感じない

70m secぐらいでレスが返るということは、efficientdet_lite0.tfliteモデル使えばラズパイ5で十数フレームぐらいの動作は可能ということが言える

 

admin

ラズパイ5のchatbot機能を統合

一月末からほぼ100日プロジェクトでしたが、ようやく全ての機能を統合できました

具体的には、画像認識で人の認識を行う、音声認識と音声出力でLLMと会話する、カメラは眼球に仕込んで瞼の動きは状態(起動表示、レスポンス内容の喜怒哀楽)を返す手段とする、というところですが、LLMをラズパイ5のローカル動作は割と早めに断念してそこはクラウドを使用(API KEYはローカルのDifyへのアクセス用でGeminiのKEYは明には見えないようになっています)

現状のコード等は以下のリンクに、

https://github.com/chateight/rasp5_bot

まだいくつかbuggyなところは残ってますが、追加機能の現状のアイディアとしては顔画像から表情を読み取ることですね

現状の機能としては、

① アプリが立ち上がったら音声メッセージを出す

② カメラが人(person)検出したらこれも音声メッセージを出して③に移行する

③ Dify経由でLLMとチャットモードで問い合わせのやり取りを行う

 

admin

tfliteをFlaskで動かしてクライアントからのリクエストで起動させる

tfliteは軽量とはいえ常時稼働させるのは、ラズパイ5のリソース的にも熱的には厳しいだろうから、ワンショットで動かすようにする

手段としてはFlaskでサーバー建てて、クライアントから認識リクエストが来たらカメラから画像取り込み、画像認識してその結果を返すという流れになります

<現状のサーバーで動くコード>

今は全てのリクエスト受けるアドレスになっている(MacBookからリクエスト出すから)けど、最終的にはローカルアドレスからだけ受けるようにします

# work on Flask server
# server will be activated only when client request is occured
#
#
from flask import Flask, jsonify
import cv2
import numpy as np
import tflite_runtime.interpreter as tflite
from picamera2 import Picamera2
from waitress import serve

app = Flask(__name__)

# モデル・ラベル初期化
interpreter = tflite.Interpreter(model_path="efficientdet_lite0.tflite")
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
with open("coco_labels.txt", "r") as f:
    labels = [line.strip() for line in f.readlines()]

# カメラ初期化
picam2 = Picamera2()
picam2.preview_configuration.main.size = (640, 480)
picam2.preview_configuration.main.format = "RGB888"
picam2.preview_configuration.align()
picam2.configure("preview")
picam2.start()

def preprocess_image(image):
    resized = cv2.resize(image, (320, 320))
    resized = resized[:, :, [2, 1, 0]]  # BGR→RGB
    return np.expand_dims(resized, axis=0).astype(np.uint8)

def postprocess_results(boxes, scores, classes, count, image_shape, labels):
    detections = []
    for i in range(count):
        if scores[i] > 0.4:
            ymin, xmin, ymax, xmax = boxes[i]
            left, right, top, bottom = (
                int(xmin * image_shape[1]),
                int(xmax * image_shape[1]),
                int(ymin * image_shape[0]),
                int(ymax * image_shape[0])
            )
            detections.append({
                'box': [left, top, right, bottom],
                'class_id': int(classes[i]),
                'score': float(scores[i]),
                'label': labels[int(classes[i])] if int(classes[i]) < len(labels) else f"id:{int(classes[i])}"
            })
    return detections

def detect_once():
    frame = picam2.capture_array()
    input_data = preprocess_image(frame)
    interpreter.set_tensor(input_details[0]['index'], input_data)
    interpreter.invoke()
    boxes = interpreter.get_tensor(output_details[0]['index'])[0]
    classes = interpreter.get_tensor(output_details[1]['index'])[0]
    scores = interpreter.get_tensor(output_details[2]['index'])[0]
    count = int(interpreter.get_tensor(output_details[3]['index'])[0])
    detections = postprocess_results(boxes, scores, classes, count, frame.shape, labels)
    return detections

@app.route('/detect', methods=['GET'])
def detect_route():
    detections = detect_once()
    return jsonify(detections)

if __name__ == '__main__':
	# when you limit access only from the local machine, use a loopback address instead of 0.0.0.0
    app.run(host='0.0.0.0', port=5000)

立ち上げのメッセージ

$ python tflite_flask.py
INFO: Created TensorFlow Lite XNNPACK delegate for CPU.
[0:43:36.818382413] [87808]  INFO Camera camera_manager.cpp:327 libcamera v0.4.0+53-29156679
[0:43:36.825774869] [87830]  INFO RPI pisp.cpp:720 libpisp version v1.1.0 e7974a156008 27-01-2025 (21:50:51)
[0:43:36.914007444] [87830]  INFO RPI pisp.cpp:1179 Registered camera /base/axi/pcie@1000120000/rp1/i2c@88000/imx708@1a to CFE device /dev/media0 and ISP device /dev/media1 using PiSP variant BCM2712_C0
[0:43:36.916831533] [87808]  INFO Camera camera.cpp:1202 configuring streams: (0) 640x480-RGB888 (1) 1536x864-BGGR_PISP_COMP1
[0:43:36.916945996] [87830]  INFO RPI pisp.cpp:1484 Sensor: /base/axi/pcie@1000120000/rp1/i2c@88000/imx708@1a - Selected sensor format: 1536x864-SBGGR10_1X10 - Selected CFE format: 1536x864-PC1B
 * Serving Flask app 'tflite_flask'
 * Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on all addresses (0.0.0.0)
 * Running on http://127.0.0.1:5000
 * Running on http://192.168.1.19:5000
Press CTRL+C to quit
192.168.1.18 - - [26/Apr/2025 19:16:35] "GET /detect HTTP/1.1" 200 -

本番運用はWSGI server使ってと言われてますが、ずっとそのままの可能性もあり、最後の行はリクエストに対する応答ですね

<クライアントからのリクエストコード>

import requests

if __name__ == '__main__':
    result = requests.get('http://rasp5.local:5000/detect').json()
    print(result)

クライアントはMacBook Proからリクエストすると、

<人がカメラから見える位置>
% python tfreq.py
[{'box': [3, -1, 636, 481], 'class_id': 0, 'label': 'person', 'score': 0.9375}]


<体をカメラからずらすと>
% python tfreq.py
[{'box': [143, 23, 607, 472], 'class_id': 81, 'label': 'id:81', 'score': 0.4765625}]

こんな感じで帰ってきます、レスポンス時間は体感1秒だから、まあこんなものかというレベルでアプリから考えたらこれで十分だし、ほとんどtfliteに負荷かけないから熱問題も起こらないでしょう

topでCPU負荷見てると、認識処理が走ってる時に瞬間的に%CPUが10%に近づくけどその程度で収まってるということ

 

admin

Pythonで感情分析

chatbotの瞼を感情(悲しい、嬉しい)で動きを作るための仕掛け、

Pythonで形態素解析と、事象を参照してスコア化できるライブラリがあるのでそれを使う

辞書(wago.121808.pn)はLLMが教えてくれた東北大のサイトからダウンロードしてます

<Python script : LLM会話での現在形態>

必要なライブラリは、spacy/jaconv/ja-ginzaをpip install、spacyは多言語の形態素解析のできるライブラリでラズパイ5でもそこそこの速度で動作可能、辞書のサイズはおよそ五千語です

import spacy
import jaconv

# --- 辞書ロード関数 ---
def normalize_to_hiragana(text):
    """表記をひらがなに正規化"""
    return jaconv.kata2hira(jaconv.z2h(text, kana=True, digit=True, ascii=True))

def load_combined_sentiment_dict(paths):
    sentiment = {}
    for path in paths:
        with open(path, encoding='UTF-8') as f:
            for line in f:
                cols = line.strip().split('\t')
                if len(cols) < 2: continue label = cols[0] # "ポジ"や"ネガ"を抽出 word = cols[1] # 単語を抽出 # スコアをラベルに応じて決定 if "ネガ" in label: score = -1.0 elif "ポジ" in label: score = 1.0 else: score = 0.0 # 中立の場合 sentiment[word] = score # 単語とスコアを登録 return sentiment # --- 感情分析処理 --- def analyze_sentiment(text, sentiment_dict, nlp): doc = nlp(text) positive_count = 0 negative_count = 0 print("=== マッチ単語とスコア ===") for token in doc: lemma = token.lemma_ # 語幹 print(f"処理中: {token.text}({lemma})") # 辞書に単語がマッチした場合 if lemma in sentiment_dict: score = sentiment_dict[lemma] print(f"マッチ: {lemma} → {score:+.1f}") if score > 0:
                positive_count += 1
            elif score < 0: negative_count += 1 total_words = len([token for token in doc if not token.is_punct]) # 句読点を除く単語数 sentiment_score = positive_count - negative_count # ポジティブ単語数 - ネガティブ単語数 normalized_score = sentiment_score / total_words * 10 if total_words > 0 else 0  # スコアの正規化

    result = "neutral"
    if normalized_score > 0:
        result = "positive"
    elif normalized_score < 0:
        result = "negative"

    print(f"\n感情スコア: {normalized_score:+.1f}")
    print(f"判定結果: {result}")
    print(f"ポジティブ単語数: {positive_count}")
    print(f"ネガティブ単語数: {negative_count}")

    return {
        "score": normalized_score,
        "positive_count": positive_count,
        "negative_count": negative_count,
        "result": result
    }

# --- メイン関数 ---
def main():
    text = """シンドラーとはね、第二次世界大戦中に、ユダヤ人をナチスから守った人だよ。彼は、ドイツのオースヴィッツ強制収容所から、たくさんのユダヤ人を助けたんだ。すごい人だよね!"""

    print("GiNZAロード中...")
    nlp = spacy.load("ja_ginza")

    print("辞書読み込み中...")
    sentiment_dict = load_combined_sentiment_dict([
        "wago.121808.pn"
    ])

    print(f"\n分析対象: {text}\n")
    analyze_sentiment(text, sentiment_dict, nlp)

if __name__ == "__main__":
    main()

<実行結果>

クリスマスのことを語っている文章を入力にすると、

% python emotion.py
GiNZAロード中...
辞書読み込み中...

分析対象: うん、そうだよ!プレゼントとか、クリスマスツリーとか、すごく楽しいよね!

=== マッチ単語とスコア ===
処理中: うん(うん)
処理中: 、(、)
処理中: そう(そう)
処理中: だ(だ)
処理中: よ(よ)
処理中: !(!)
処理中: プレゼント(プレゼント)
処理中: と(と)
処理中: か(か)
処理中: 、(、)
処理中: クリスマスツリー(クリスマスツリー)
処理中: と(と)
処理中: か(か)
処理中: 、(、)
処理中: すごく(すごい)
処理中: 楽しい(楽しい)
マッチ: 楽しい → +1.0
処理中: よ(よ)
処理中: ね(ね)
処理中: !(!)

感情スコア: +0.7
判定結果: positive
ポジティブ単語数: 1
ネガティブ単語数: 0

感情スコアは+1 ~ -1の間に治るようにしたいから乗算してます、上限と下限もこの値で区切るようにした方がいいだろうね、

 

admin

ドライバ不要の有線LANアダプタにした

以下のリンクの通り、

https://isehara-3lv.sakura.ne.jp/blog/2025/04/17/tp-link-usb-lanアダプタ/

ドライバインスト必要なアダプタは今のMacの世界では異端らしいから、正道を行くことにして新規に調達

ラズパイで新規のSSIDに接続必要な時には、Macで中継機設定して有線でLANに接続後にVNCでWi-Fi設定という手順になります、MacのUSB-LANアダプタはこの作業には必需品ではなくて、単にMacでの回線高速化の可能性だけですが

 

admin

ラズパイ5のWi-Fi不具合はSSD原因らしい

以前からラズパイ5のWi-Fiが不調、他のSSIDに切り替えられない、でしたがついにデフォルトのSSIDでも動作不安定になってリブートしても程なく通信が切れてVNCが使えない、あるいはターミナルが開くのにやたら時間かかるとかで使えないので数週間前にバックアップしてたSDカードでなおかつ有線LANにつないで調べてみると、

経緯は、

https://isehara-3lv.sakura.ne.jp/blog/2025/04/16/ラズパイ5のwi-fi不具合/

① 実はバックアップのSDカードから立ち上げるとSSIDの切り替えはできた

② ラズパイ5でSSDにSDカードからImagerでデータ転送してコピーあるいはラズパイ5でサラのイメージ書き込みしようとしても途中で失敗、MacでOSイメージ書き込んで(これは正常に終了)ラズパイ5に持ってきても立ち上がらない

ということで、極めて寿命が短かった(一月ちょっとか)けれどもSSDの不良というのが現段階の結論です(Macでは書き込めるからHATに原因という可能性もあるけれども)

P.S. とは言ってもMacBookではまともに扱えているから、ラズパイ5での使い方に問題と考えるべきかな、俗にいう相性と言われるやつだけど、Silicon Powerはイマイチらしいから

まあ筒の中に収納されて、温度もかなり上がるからSSDは今回は諦めかな

ラズパイ5のブラウザでSpeedTest実行するとラズパイ5のacモードの転送でも200Mbps以下で、有線LAN はn規格のアダプタ経由でも200Mbps以上は出てるから(有線LANはgiga Lanだから)、ラズパイ5のWi-Fiの性能は低すぎ故にWi-Fiは非常用と考えた方がよさそうだ

P.S. 2025/4/20

この部分の記述は誤り、つまりWi-Fi中継機が100Mbpsの有線LANなのに、なぜそれ以上の速度が出るかというと実はWi-Fiを経由してしまってるから、つまりLinuxの場合にはそういうルーティングも起こるらしい

 

admin

 

TP-LINK USB-LANアダプタ

ドライバインスト必要なアダプタ、M1 MacBook Airでは使えていたけど、M4 MacBook Proではドライバがうまくインストできない

システム情報がこんな怪しげな状況にもなる、

特にTP-LINK製は最近のAppleでドライバインストールの時の条件が厳しくなっているようで、LLMに聞くとセーフモードで立ち上げてセキュリティ外せみたいなことことを言われたから、そんなもんなら使うのやめたほうがいいだろう

代替えとして、Belkinとかを紹介しているから、Macではドライバ必要な周辺デバイスは選択の対象外というのが認識となりました、そもそもUSBがType-Aだからその時点で時代遅れ(使いづらい)になっているわけですが

 

admin

 

 

ラズパイ5のWi-Fi不具合

元々の問題(今現在解決できていないので途中経過)

ラズパイ5でSSIDが追加できない、より正確に言えば以前はpreconfiguredのWi-Fi SSIDがなければ他のSSIDに接続できていたのが接続できなくなったのでその調査として、ラズパイ0でやってみたことと、ラズパイ5の振る舞い

<wpa_supplicant.confを作成必要な問題:これはラズパイ0での実行時>

昨年終わり頃にOSがbookworm版にアップされているので、ラズパイ0で最新のOSでWi-Fiの初期設定を追加(rpi imagerでラズパイ0用のヘッドレスのイメージ書き込んでやってみた)、しかし最初の壁は起動したと思える時間待ってもWi-Fi内にラズパイ0が見つからない

作成したSDカードのルートに以下のwpa_supplicant.confファイルを作成してやると見えるようになった

country=JP
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1

network={
    ssid="your SSID"
    psk="your PW"
}

<nmcli(bookwormからはこのコマンドで制御になってる)での必要コマンド>

rescanやらないとキャッシュがクリアされないから、今接続中のSSIDしか見えない
$ sudo nmcli device wifi rescan

次にlist出力させる
$ sudo nmcli device wifi list

一回の入力で済ますなら、
$ sudo nmcli device wifi rescan && sleep 2 && nmcli device wifi list

SSIDの追加設定
$ sudo nmcli device wifi connect aterm-eb69c6-g password “your PW” hidden yes
Device ‘wlan0’ successfully activated with ‘unique UUIDの値’

設定済み接続リスト(-gに切り替えている)
$ nmcli connection show

接続先を切り替える時は例えば、
$ sudo nmcli connection up preconfigured

ここまでは正常動作、自宅以外のSSIDもちゃんと見えている普通の姿

————————–

<ラズパイ5のWi-Fi問題>

1. 自宅内と周辺のセンスできるはずのSSIDがほとんど見えない、感度が低下している状態と言えなくもないが、その割には受信できてるSSIDの電波強度はかなり強い

2. かつpreconfigured以外は見え方が不安定で、見えたり見えなかったり

3. 見えてる状態でSSID切り替えしようとすると、ハング状態になるからVNC接続では電源切るしかない

4. 当初は複数のSSID登録できて、自動切り替えもできてたから、その後のシステムの変更で発生しているようにも見える、ケース(筒)の影響の可能性は?ケースに収めた後に問題発生しているように思うから

そもそもアンテナが基板(CPU側)に構成されていて、なおかつクーリングファンの影響(遮蔽)も受けるだろうから、感度がそれほど期待できないということがある

ただしwavemonで見た限りは問題ないね

原因がどうしても判明しないときにはUSB Wi-Fiドングル(多分その方が無線的な特性はまともだろうと思う)、あるいはWi-Fiアダプタ使って有線LANでつなげるという選択肢もあるかな

 

admin

画像の物体検出軽量化(ラズパイ5)

Yoloは性能的には十分すぎる感じですが、やはりリソースを相当に消費します

https://isehara-3lv.sakura.ne.jp/blog/2025/04/12/yoloとefficientnetの違いと用途/

で、目的を人検出に絞って軽量化を検討してみた

efficientdet_lite0.tfliteのモデルをTFliteで動かすのが現状の割とメジャーな選択だと思われるのでやってみた

<ターゲット>

・ラズパイ5:8GBメモリ/256GB SSD

<コード>

LLMとの対話で生成された最終的なコード、カメラ画像のデータ(RGB)の並べ替えが必要です、パッケージ競合でPython用の環境は新しく作成しています

import cv2
import numpy as np
import tflite_runtime.interpreter as tflite
from picamera2 import Picamera2

# EfficientDet Lite0 モデルロード
interpreter = tflite.Interpreter(model_path="efficientdet_lite0.tflite")
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

# ラベル読み込み
with open("coco_labels_91.txt", "r") as f:
    labels = [line.strip() for line in f.readlines()]

def preprocess_image(image):
    resized = cv2.resize(image, (320, 320))
    resized = resized[:, :, [2, 1, 0]]  # RGBに
    return np.expand_dims(resized, axis=0).astype(np.uint8)

def postprocess_results(boxes, scores, classes, count, image_shape):
    detections = []
    for i in range(count):
        if scores[i] > 0.4:
            ymin, xmin, ymax, xmax = boxes[i]
            (left, right, top, bottom) = (
                int(xmin * image_shape[1]), int(xmax * image_shape[1]),
                int(ymin * image_shape[0]), int(ymax * image_shape[0])
            )
            detections.append({
                'box': (left, top, right, bottom),
                'class_id': int(classes[i]),
                'score': float(scores[i]),
                'label': labels[int(classes[i])] if int(classes[i]) < len(labels) else f"id:{int(classes[i])}"
            })
    return detections

def draw_detections(image, detections):
    for detection in detections:
        left, top, right, bottom = detection['box']
        label = f"{detection['label']} {detection['score']*100:.1f}%"
        cv2.rectangle(image, (left, top), (right, bottom), (0, 255, 0), 2)
        cv2.putText(image, label, (left, top - 10),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1)

def main():
    # Picamera2 初期化
    picam2 = Picamera2()
    picam2.preview_configuration.main.size = (640, 480)
    picam2.preview_configuration.main.format = "RGB888"
    picam2.preview_configuration.align()
    picam2.configure("preview")
    picam2.start()

    while True:
        frame = picam2.capture_array()

        input_data = preprocess_image(frame)
        interpreter.set_tensor(input_details[0]['index'], input_data)
        interpreter.invoke()

        boxes = interpreter.get_tensor(output_details[0]['index'])[0]
        classes = interpreter.get_tensor(output_details[1]['index'])[0]
        scores = interpreter.get_tensor(output_details[2]['index'])[0]
        count = int(interpreter.get_tensor(output_details[3]['index'])[0])

        detections = postprocess_results(boxes, scores, classes, count, frame.shape)
        draw_detections(frame, detections)

        cv2.imshow("EfficientDet + PiCamera2", frame)
        if cv2.waitKey(1) & 0xFF == ord("q"):
            break

    cv2.destroyAllWindows()

if __name__ == "__main__":
    main()

<実行結果>

タブレットに写した人物画像から人検出を行っていますが、それなりの確度で検出できてます、精度そのものはYoloよりは低い

ラズパイ5のリソースはCPUが100%程度で、メモリフットプリント的にも余裕はあります、CPU温度はファンは常時回転中で60℃程度、長時間だと全体がほんわりと暖かくなりますが、夏場も何とか耐えそう

ここのパーツはほぼ決まりだろうから、全体構成図を掲載、これからパーツを結合してアプリを作ります

 

 

 

admin

 

timemachineバックアップ失敗対策のその後

以前の記事ですが、

https://isehara-3lv.sakura.ne.jp/blog/2025/04/06/apple-silicon系のmacbookでnasへのtimemachineバックアップ失敗/

この時点でまだバックアップ設定は成功していなかった

<第一段階の設定の追加>

・NASは毎日5:00AMに起動していて、数時間経過(毎日のバックアップが完了したと思う頃)したら電源オフをプログラム設定している

・MacBook設定 -> これはハズレだったので週一のリフレッシュブートに戻す

% sudo pmset repeat wakeorpoweron MTWRFSU 05:10:00

% pmset -g sched

Repeating power events:

  wakepoweron at 5:10AM every day

設定を戻した、restartと他の設定は共存できないから

% sudo pmset repeat restart S 05:00:00

% pmset -g sched

Repeating power events:

  restart at 5:00AM Saturday

・TimeMachinEditorはバックアップできなかったらリトライする設定 -> 本質ではないけどリブート後の自動スタート(ログオンしたらtimemachineが自動起動)には有効であった

・バッテリーでディスプレイオフ時にスリープさせない -> 本質ではない

<ログファイルから対策>

(2025/4/10)

今朝うまくいかなかったログをLLMに入れると、解決案として~/Logを除外するというのがあったから除外を設定

但しアプリの設定も復元したいならば全部を除外してはいけない

—————————–

~/Library/Application Support や ~/Library/Preferences を 除外しないように注意。

アプリによっては ~/Library/Containers に大事なデータを保存していることもある。

—————————–

とあったからその三つのディレクトリは対象にした

 

設定後のシステムログからtimemachineバックアップ関連を抽出

log show --predicate 'subsystem == "com.apple.TimeMachine" AND eventMessage CONTAINS "Backup"' --style syslog --info --start "2025-04-13 05:00:00" --end "2025-04-13 06:00:00" --timezone local

〜〜〜前後省略して結果だけ〜〜〜

2025-04-11 05:41:47.556152+0900  localhost backupd[504]: (TimeMachine) [com.apple.TimeMachine:CopyProgress] Finished copying from volume “Data”

      77624 Total Items Added (l: 3.7 GB p: 3.89 GB)

      23459 Total Items Propagated (shallow) (l: Zero KB p: Zero KB)

    2718279 Total Items Propagated (recursive) (l: 467.4 GB p: 236.17 GB)

    2795903 Total Items in Backup (l: 471.1 GB p: 240.06 GB)

      66165 Files Copied (l: 3.37 GB p: 3.54 GB)

       9056 Directories Copied (l: Zero KB p: Zero KB)

       2271 Symlinks Copied (l: 171 KB p: Zero KB)

      17029 Files Move Skipped (l: Zero KB p: Zero KB) | 17029 items propagated (l: 4.12 GB p: 4.1 GB)

       6430 Directories Move Skipped (l: Zero KB p: Zero KB) | 2677791 items propagated (l: 463.29 GB p: 232.06 GB)

         80 Files Cloned (l: 191 KB p: 328 KB)

         52 Files Delta Copied (l: 332.8 MB p: 346.6 MB)

この時刻がデスクトップから見える終了時刻、実際にはこの後unmount処理されて終了

以上で3日間は正常(土曜日は再起動後にtimemachineが走り始めたけど、これはTimeMachineEditorの設定が効いている)なので、とりあえず問題は回避できていると思って良さそう、要はtimemachineバックアップでLogファイルをロックできなくてバックアップ処理が途中で止まっていたのが問題で、対象(復元には無関係だろう)のLogファイルをバックアップの処理対象から除外したということ、除外した三つのLogディレクトリをバックアップ時に同じことが起こらないのかという疑問はありますが

 

admin