Skip to content

Useful import scripts

OliE edited this page Nov 17, 2024 · 7 revisions

MiFit 'BODY' file --> openScale CSV file

by Martin1887 see https://github.com/oliexdev/openScale/issues/669

#!/usr/bin/python

import argparse
import csv
import datetime

OPENSCALE_HEADER = '"biceps","bone","caliper1","caliper2","caliper3","calories","chest","comment","dateTime","fat","hip","lbm","muscle","neck","thigh","visceralFat","waist","water","weight"'

_MIFIT_BODY_HEADER = 'timestamp,weight,height,bmi,fatRate,bodyWaterRate,boneMass,metabolism,muscleRate,visceralFat,impedance'

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('mifit_BODY_csv_file_path')
    parser.add_argument('output_path')
    
    args = parser.parse_args()
    
    with open(args.mifit_BODY_csv_file_path, 'r') as inp:
        reader = csv.DictReader(inp)
        with open(args.output_path, 'w') as outp:
            writer = csv.DictWriter(outp, OPENSCALE_HEADER.replace('"', '').split(','))
            outp.write(f'{OPENSCALE_HEADER}\n')
            
            for line in reader:
                timestamp = int(line['timestamp'])
                output_date = datetime.datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M')
                weight = line['weight']
                writer.writerow({'dateTime': output_date, 'weight': weight})
                

Libra CSV file --> openScale CSV file

initial script by feclare see https://github.com/oliexdev/openScale/issues/28

modified script by abatula see https://github.com/oliexdev/openScale/issues/1050

#!/usr/bin/env python
"""
Simple script to transform libra csv file to openscale format
Optional argument to convert lbs to kg for correct import
Sample usage:
# Does not modify the Libra values
python libra_to_openscale.py Libra_2024-06-04.csv
# Convert Libra values from lbs to kg
python libra_to_openscale.py Libra_2024-06-04.csv lbs
"""
import sys
import csv
from dateutil.parser import parse

if len(sys.argv) < 2:
    print('Missing file to transform')
    sys.exit(1)

if (len(sys.argv) > 2) and (sys.argv[2] == 'lbs'):
    print('Converting Libra data from lbs to kg')
    weight_scalar = 0.453592
else:
    print('Leaving Libra data as-is (kg)')
    weight_scalar = 1


with open(sys.argv[1], 'r') as inputfile:
    r = csv.reader(inputfile, delimiter=";")
    lines = list(r)

with open('openScale_data_Libra.csv', 'w') as outputfile:
    writer = csv.writer(outputfile, delimiter=",")
    for w in lines:
        if len(w) == 0 or w[0].startswith("#"):
            continue
        time = w[0]
        weight_float = float(w[1]) * weight_scalar
        weight = f'{weight_float:.1f}'
        comment = w[5]
        d = parse(time)
        
        writer.writerow([d.strftime('%d.%m.%Y %H:%M'), weight, 0.0, 0.0, 0.0, 0.0, 0.0, comment])

openScale CSV file --> Garmin format

by jowlo see https://github.com/oliexdev/openScale/issues/777

#!/usr/bin/env python

"""
Simple script to transform openscale csv export files to a format accepted by garmin connect at
https://connect.garmin.com/modern/import-data

Note: When importing the language needs to be set to English, otherwise the import fails. 
Set everything to metric units and to YYYY-MM-DD date format.

If you want to compute BMI for the file give your height (im meters) as second parameter.
"""

import sys
import csv
from dateutil.parser import parse

if len(sys.argv) < 2:
    print ("Missing file to transform\n")
    sys.exit(1)

bmi = lambda size: 0;
if len(sys.argv) == 3:
    bmi = lambda weight: weight/(float(sys.argv[2])**2)
        

with open("openScale_garmin_connect_import.csv", "w") as outfile, open(sys.argv[1], "r") as infile:

    reader = csv.DictReader(infile, delimiter=",")
    writer = csv.writer(outfile, delimiter=",")
    
    outfile.write("Body\n")
    outfile.write("Date,Weight,BMI,Fat\n")
    for row in reader:
        writer.writerow([
            parse(row["dateTime"]).strftime('%Y-%m-%d'),
            row["weight"],
            bmi(float(row["weight"])),
            row["fat"]
            ])

Garmin format --> openScale CSV file

by antonmosich see https://github.com/oliexdev/openScale/issues/879

#!/usr/bin/python

import csv
import json
import datetime
import argparse

OPENSCALE_HEADER = '"biceps","bone","caliper1","caliper2","caliper3","calories","chest","comment","dateTime","fat","hip","lbm","muscle","neck","thigh","visceralFat","waist","water","weight"'

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("input")
    parser.add_argument("output")
    args = parser.parse_args()
    with open(args.input, 'r') as input_file:
        input_json = json.load(input_file)
    filtered = [entry for entry in input_json if "weight" in entry]
    with open(args.output, 'w') as output_file:
        writer = csv.DictWriter(output_file, OPENSCALE_HEADER.replace('"', '').split(','))
        output_file.write(f'{OPENSCALE_HEADER}\n')

        for entry in filtered:
            timestamp = datetime.datetime.fromisoformat(entry['weight']['timestampGMT'].ljust(23,'0'))
            weight = entry['weight']['weight'] / 1000
            writer.writerow({'dateTime': timestamp, 'weight': weight})

Google Fit CSV file --> openScale CSV file

by sainigma see https://github.com/oliexdev/openScale/issues/1040

#!/usr/bin/env python
import csv
from dateutil.parser import parse

with open('Daily activity metrics.csv', newline='') as input_csv:
  csv_reader = csv.reader(input_csv, delimiter=',')

  rows = []

  for row in csv_reader:
    rows.append(row)
  
  headers = rows[0]
  data = rows[1:]

  date_idx = headers.index('Date')
  weight_idx = headers.index('Average weight (kg)')

  with open('openscale_data.csv', 'w', newline='', encoding='utf-8') as output_csv:
    output_writer = csv.writer(output_csv, delimiter=',')

    output_writer.writerow(["dateTime", "weight"])

    for fragment in data:
      date = fragment[date_idx]
      weight = fragment[weight_idx]

      if (weight and date):
        output_writer.writerow([parse(date).strftime('%d.%m.%Y 08:00'), round(float(weight), 2)])