Skip to content

Offline gym log for Android. No account, no ads, no internet.

Import workouts from JEFIT and StrongLifts

InlitX0f9fa12d681b
diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart
index ec40d00..3069969 100644
--- a/lib/screens/settings_screen.dart
+++ b/lib/screens/settings_screen.dart
@@ -1402,8 +1402,11 @@ class SettingsScreen extends StatelessWidget {
('Hevy', 'workout_data.csv'),
('Strong', 'strong.csv'),
('Lyfta', 'LyftaExport.csv'),
+ ('Liftosaur', '.csv'),
+ ('JEFIT', '.csv'),
+ ('StrongLifts', '.csv'),
('FitNotes', '.fitnotes'),
- ('openGym', 'opengym-backup.json'),
+ ('openGym', '.json · .zip'),
('CSV', ''),
].indexed) ...[
if (i > 0) Divider(height: 1, thickness: 1, indent: 16, endIndent: 16, color: gc.border),
@@ -1500,7 +1503,7 @@ class SettingsScreen extends StatelessWidget {
String? raw;
try {
if (bytes.length > 2 && bytes[0] == 0x50 && bytes[1] == 0x4B) {
- raw = weightCsvFromZip(bytes);
+ raw = openGymBackupFromZip(bytes) ?? weightCsvFromZip(bytes);
if (raw == null) {
_snack(context, t.importZipNoWeights);
return;
diff --git a/lib/services/workout_import.dart b/lib/services/workout_import.dart
index 9d709a5..f0b9c74 100644
--- a/lib/services/workout_import.dart
+++ b/lib/services/workout_import.dart
@@ -13,6 +13,8 @@ enum ImportFormat {
lyfta,
fitbod,
liftosaur,
+ stronglifts,
+ jefit,
fitnotes,
gymmane,
openGym,
@@ -216,8 +218,12 @@ const _dateCols = ['date', 'fecha', 'start_time', 'time'];
ImportFormat detectFormat(String csv) {
if (_backupOf(csv) != null) return ImportFormat.openGym;
+ if (_isJefit(csv)) return ImportFormat.jefit;
final cols = _header(csv);
if (cols.isEmpty) return ImportFormat.unknown;
+ if (cols.contains('date (yyyy/mm/dd)') && cols.contains('exercise') && cols.any(_slRepsCol.hasMatch)) {
+ return ImportFormat.stronglifts;
+ }
if (cols.contains('exercise_title') && cols.contains('start_time')) return ImportFormat.hevy;
if (cols.contains('workout datetime') && cols.contains('is warmup set?')) return ImportFormat.liftosaur;
if (cols.contains('exercise name') && cols.contains('set order')) return ImportFormat.strong;
@@ -255,6 +261,7 @@ ImportFormat detectFormat(String csv) {
bool needsUnitChoice(String csv) {
final format = detectFormat(csv);
+ if (format == ImportFormat.jefit) return true;
final cols = _header(csv);
if (format.isWeights) {
if (_pick(cols, _weightKgCols) != null || _pick(cols, _weightLbCols) != null) return false;
@@ -267,6 +274,169 @@ bool needsUnitChoice(String csv) {
return _pick(cols, fmt.weightPlain ?? const []) != null;
}
+final _slRepsCol = RegExp(r'^set (\d+) \(reps\)$');
+
+String _cell(List<String> row, int i) => i < 0 || i >= row.length ? '' : row[i].trim();
+
+(int, int)? _clock(String s) {
+ final m = RegExp(r'^(\d{1,2}):(\d{2})\s*([ap])?\.?\s*m?\.?$', caseSensitive: false).firstMatch(s.trim());
+ if (m == null) return null;
+ var h = int.parse(m.group(1)!);
+ final min = int.parse(m.group(2)!);
+ final half = m.group(3)?.toLowerCase();
+ if (half != null) h = h % 12 + (half == 'p' ? 12 : 0);
+ return h < 24 && min < 60 ? (h, min) : null;
+}
+
+ImportResult _parseStrongLifts(String csv) {
+ final rows = _rows(csv, _delimiter(csv));
+ if (rows.length < 2) return ImportResult(ImportFormat.stronglifts, const []);
+ final head = rows.first.map(_norm).toList();
+ final date = head.indexOf('date (yyyy/mm/dd)');
+ final number = head.indexOf('workout');
+ final exercise = head.indexOf('exercise');
+ final start = head.indexOf('start time (h:mm)');
+ final end = head.indexOf('end time (h:mm)');
+ final notes = head.indexOf('notes');
+ final pairs = <(int, int, bool)>[];
+ for (var i = 0; i < head.length; i++) {
+ final m = _slRepsCol.firstMatch(head[i]);
+ if (m == null) continue;
+ final kg = head.indexOf('set ${m.group(1)} (kg)');
+ final lb = head.indexOf('set ${m.group(1)} (lb)');
+ if (kg >= 0) {
+ pairs.add((i, kg, false));
+ } else if (lb >= 0) {
+ pairs.add((i, lb, true));
+ }
+ }
+ final sessions = <String, ParsedSession>{};
+ for (final row in rows.skip(1)) {
+ final day = RegExp(r'^(\d{4})[/-](\d{1,2})[/-](\d{1,2})$').firstMatch(_cell(row, date));
+ final name = _cell(row, exercise);
+ if (day == null || name.isEmpty) continue;
+ final from = _clock(_cell(row, start));
+ final to = _clock(_cell(row, end));
+ final session = sessions.putIfAbsent('${_cell(row, date)}#${_cell(row, number)}', () {
+ final when = DateTime(int.parse(day.group(1)!), int.parse(day.group(2)!), int.parse(day.group(3)!),
+ from?.$1 ?? 0, from?.$2 ?? 0);
+ var seconds = 0;
+ if (from != null && to != null) {
+ final minutes = (to.$1 * 60 + to.$2) - (from.$1 * 60 + from.$2);
+ if (minutes > 0) seconds = minutes * 60;
+ }
+ return ParsedSession(when, seconds);
+ });
+ final parsed = ParsedExercise(name, null);
+ final note = _setNote(_cell(row, notes));
+ for (final (repsCol, weightCol, lb) in pairs) {
+ final reps = double.tryParse(_cell(row, repsCol).replaceAll(',', '.'))?.round() ?? 0;
+ if (reps <= 0) continue;
+ final weight = double.tryParse(_cell(row, weightCol).replaceAll(',', '.')) ?? 0;
+ parsed.sets.add(ParsedSet(reps, lb ? weight / _lbPerKg : weight, note: parsed.sets.isEmpty ? note : ''));
+ }
+ if (parsed.sets.isNotEmpty) session.exercises.add(parsed);
+ }
+ return ImportResult(ImportFormat.stronglifts, [
+ for (final s in sessions.values)
+ if (s.exercises.isNotEmpty) s,
+ ]);
+}
+
+bool _isJefit(String text) =>
+ RegExp(r'^\s*###\s*EXERCISE LOGS\s*###\s*$', multiLine: true, caseSensitive: false).hasMatch(text);
+
+Map<String, List<List<String>>> _jefitSections(String text) {
+ final lines = <String, List<String>>{};
+ List<String>? current;
+ for (final line in text.replaceFirst('', '').split(RegExp(r'\r?\n'))) {
+ final m = RegExp(r'^\s*###\s*(.*?)\s*###\s*$').firstMatch(line);
+ if (m != null) {
+ current = lines.putIfAbsent(m.group(1)!.toLowerCase(), () => []);
+ continue;
+ }
+ if (current != null && line.trim().isNotEmpty) current.add(line);
+ }
+ return {
+ for (final e in lines.entries)
+ if (e.value.isNotEmpty) e.key: _rows(e.value.join('\n'), ','),
+ };
+}
+
+ImportResult _parseJefit(String text, bool isLb) {
+ final sections = _jefitSections(text);
+ final logs = sections['exercise logs'];
+ if (logs == null || logs.length < 2) return ImportResult(ImportFormat.jefit, const []);
+ final head = logs.first.map(_norm).toList();
+ final sessionCol = head.indexOf('belongsession');
+ final nameCol = head.indexOf('ename');
+ final dateCol = head.indexOf('mydate');
+ final logsCol = head.indexOf('logs');
+ if (nameCol < 0 || dateCol < 0 || logsCol < 0) return ImportResult(ImportFormat.jefit, const []);
+ final starts = <String, (DateTime, int)>{};
+ final info = sections['workout sessions'];
+ if (info != null && info.length > 1) {
+ final h = info.first.map(_norm).toList();
+ final id = h.indexOf('_id');
+ final st = h.indexOf('starttime');
+ final total = h.indexOf('total_time');
+ if (id >= 0 && st >= 0) {
+ for (final row in info.skip(1)) {
+ final seconds = int.tryParse(_cell(row, st));
+ if (seconds == null || seconds <= 0) continue;
+ starts[_cell(row, id)] =
+ (DateTime.fromMillisecondsSinceEpoch(seconds * 1000), int.tryParse(_cell(row, total)) ?? 0);
+ }
+ }
+ }
+ final sessions = <String, ParsedSession>{};
+ final setPattern = RegExp(r'^\s*(\d+(?:\.\d+)?)?\s*x\s*(\d+)\s*$', caseSensitive: false);
+ for (final row in logs.skip(1)) {
+ final d = RegExp(r'^(\d{4})-(\d{2})-(\d{2})$').firstMatch(_cell(row, dateCol));
+ final name = _cell(row, nameCol);
+ if (d == null || name.isEmpty) continue;
+ final day = DateTime(int.parse(d.group(1)!), int.parse(d.group(2)!), int.parse(d.group(3)!));
+ final id = sessionCol >= 0 ? _cell(row, sessionCol) : '';
+ final start = starts[id];
+ final sameDay = start != null && _dayId(start.$1) == _dayId(day);
+ final session = sessions.putIfAbsent(
+ id.isEmpty ? _dayId(day) : id, () => ParsedSession(sameDay ? start.$1 : day, sameDay ? start.$2 : 0));
+ final parsed = ParsedExercise(name, null);
+ for (final part in _cell(row, logsCol).split(',')) {
+ final m = setPattern.firstMatch(part);
+ if (m == null) continue;
+ final reps = int.parse(m.group(2)!);
+ if (reps <= 0) continue;
+ final weight = double.tryParse(m.group(1) ?? '') ?? 0;
+ parsed.sets.add(ParsedSet(reps, isLb ? weight / _lbPerKg : weight));
+ }
+ if (parsed.sets.isNotEmpty) session.exercises.add(parsed);
+ }
+ return ImportResult(ImportFormat.jefit, [
+ for (final s in sessions.values)
+ if (s.exercises.isNotEmpty) s,
+ ]);
+}
+
+String? openGymBackupFromZip(List<int> bytes) {
+ Archive archive;
+ try {
+ archive = ZipDecoder().decodeBytes(bytes);
+ } catch (_) {
+ return null;
+ }
+ for (final file in archive.files) {
+ if (!file.isFile || file.name.split('/').last != 'opengym-backup.json') continue;
+ try {
+ final text = utf8.decode(file.content as List<int>, allowMalformed: true);
+ return _backupOf(text) == null ? null : text;
+ } catch (_) {
+ return null;
+ }
+ }
+ return null;
+}
+
String? weightCsvFromZip(List<int> bytes) {
Archive archive;
try {
@@ -334,6 +504,8 @@ List<ParsedWeight> parseWeights(String csv, {bool isLb = false}) {
ImportResult parseImport(String csv, {bool isLb = false}) {
final format = detectFormat(csv);
if (format == ImportFormat.openGym) return _parseOpenGym(_backupOf(csv)!);
+ if (format == ImportFormat.stronglifts) return _parseStrongLifts(csv);
+ if (format == ImportFormat.jefit) return _parseJefit(csv, isLb);
if (format.isWeights) {
return ImportResult(format, const [], weights: parseWeights(csv, isLb: isLb));
}
diff --git a/lib/widgets/import_card.dart b/lib/widgets/import_card.dart
index 8456d9a..3b8371f 100644
--- a/lib/widgets/import_card.dart
+++ b/lib/widgets/import_card.dart
@@ -6,7 +6,7 @@ import '../theme/app_colors.dart';
import '../theme/app_theme.dart';
import 'ui_kit.dart';
-const kImportApps = ['Hevy', 'Strong', 'FitNotes', 'Lyfta', 'openGym', 'CSV'];
+const kImportApps = ['Hevy', 'Strong', 'FitNotes', 'Lyfta', 'Liftosaur', 'JEFIT', 'StrongLifts', 'openGym', 'CSV'];
class ImportCard extends StatelessWidget {
const ImportCard({super.key, required this.onTap});
@@ -76,10 +76,10 @@ class AppMarquee extends StatefulWidget {
class _AppMarqueeState extends State<AppMarquee> with SingleTickerProviderStateMixin {
static const _tile = 104.0;
static const _gap = 10.0;
- static const _period = (_tile + _gap) * 6;
+ static final _period = (_tile + _gap) * kImportApps.length;
late final AnimationController _ctrl =
- AnimationController(vsync: this, duration: const Duration(seconds: 15));
+ AnimationController(vsync: this, duration: Duration(milliseconds: 2500 * kImportApps.length));
@override
void didChangeDependencies() {
@@ -112,9 +112,13 @@ class _AppMarqueeState extends State<AppMarquee> with SingleTickerProviderStateM
height: 46,
alignment: Alignment.center,
decoration: BoxDecoration(color: gc.bgRaised2, borderRadius: BorderRadius.circular(15)),
- child: Text(name,
- maxLines: 1,
- style: AppTheme.f(15, weight: FontWeight.w800, color: gc.text, letterSpacing: -0.2)),
+ padding: const EdgeInsets.symmetric(horizontal: 10),
+ child: FittedBox(
+ fit: BoxFit.scaleDown,
+ child: Text(name,
+ maxLines: 1,
+ style: AppTheme.f(15, weight: FontWeight.w800, color: gc.text, letterSpacing: -0.2)),
+ ),
),
),
],
diff --git a/test/import_test.dart b/test/import_test.dart
index a835f3c..3e86e6d 100644
--- a/test/import_test.dart
+++ b/test/import_test.dart
@@ -1,3 +1,6 @@
+import 'dart:convert';
+
+import 'package:archive/archive.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:gymmane/services/workout_import.dart';
import 'package:gymmane/state/fit_state.dart';
@@ -200,6 +203,66 @@ void main() {
});
});
+ group('StrongLifts', () {
+ const csv = 'Date (yyyy/mm/dd),Workout,Workout Name,Exercise,Start Time (h:mm),End Time (h:mm),Notes,'
+ 'Set 1 (Reps),Set 1 (KG),Set 2 (Reps),Set 2 (KG),Set 3 (Reps),Set 3 (KG)\n'
+ '2024/03/05,1,Workout A,Squat,6:30 PM,7:15 PM,felt strong,5,100,5,100,3,100\n'
+ '2024/03/05,1,Workout A,Bench Press,6:30 PM,7:15 PM,,5,60,5,60,0,60\n'
+ '2024/03/07,1,Workout B,Deadlift,7:00 AM,,,5,140,,,,\n';
+
+ test('una fila por ejercicio con sus series en columnas', () {
+ expect(detectFormat(csv), ImportFormat.stronglifts);
+ expect(needsUnitChoice(csv), isFalse);
+ final r = parseImport(csv);
+ expect(r.sessions.length, 2);
+ final a = r.sessions.first;
+ expect(a.date, DateTime(2024, 3, 5, 18, 30));
+ expect(a.durationSec, 45 * 60);
+ expect(a.exercises.first.name, 'Squat');
+ expect(a.exercises.first.sets.length, 3);
+ expect(a.exercises.first.sets.first.note, 'felt strong');
+ expect(a.exercises[1].sets.length, 2, reason: 'la serie con 0 reps no se hizo');
+ expect(r.sessions.last.date, DateTime(2024, 3, 7, 7));
+ expect(r.sessions.last.exercises.single.sets.single.weightKg, 140);
+ });
+
+ test('pasa a kg las columnas en libras', () {
+ const lb = 'Date (yyyy/mm/dd),Workout,Exercise,Set 1 (Reps),Set 1 (LB)\n2024/03/05,1,Squat,5,225\n';
+ expect(parseImport(lb).sessions.single.exercises.single.sets.single.weightKg, closeTo(102.06, 0.05));
+ });
+ });
+
+ group('JEFIT', () {
+ const text = '### WORKOUT SESSIONS ###\n'
+ '_id,starttime,total_time\n'
+ '7,1709661600,3600\n'
+ '\n'
+ '### EXERCISE LOGS ###\n'
+ '_id,belongsession,ename,mydate,logs\n'
+ '1,7,Barbell Bench Press,2024-03-05,"60x10,65x8,65x6"\n'
+ '2,7,Pull Up,2024-03-05,"0x12,0x10"\n'
+ '3,,Barbell Squat,2024-03-07,"100x5"\n';
+
+ test('lee las secciones y las series peso x reps', () {
+ expect(detectFormat(text), ImportFormat.jefit);
+ expect(needsUnitChoice(text), isTrue, reason: 'JEFIT no dice la unidad');
+ final r = parseImport(text);
+ expect(r.sessions.length, 2);
+ final s = r.sessions.first;
+ expect(s.date, DateTime.fromMillisecondsSinceEpoch(1709661600 * 1000));
+ expect(s.durationSec, 3600);
+ expect(s.exercises.first.sets.map((e) => e.reps), [10, 8, 6]);
+ expect(s.exercises.first.sets.last.weightKg, 65);
+ expect(s.exercises.last.sets.first.weightKg, 0);
+ expect(r.sessions.last.date, DateTime(2024, 3, 7));
+ });
+
+ test('convierte a kg si el usuario dice que eran libras', () {
+ final r = parseImport(text, isLb: true);
+ expect(r.sessions.first.exercises.first.sets.first.weightKg, closeTo(27.22, 0.05));
+ });
+ });
+
group('openGym', () {
test('reconoce el backup y lo parsea', () {
expect(detectFormat(_openGym), ImportFormat.openGym);
@@ -225,6 +288,18 @@ void main() {
expect(r.weights.single.kg, closeTo(81.65, 0.05));
});
+ test('saca el backup del zip con fotos y vídeos de openGym', () {
+ final data = utf8.encode(_openGym);
+ final zip = ZipEncoder().encode(Archive()
+ ..addFile(ArchiveFile('README.txt', 4, utf8.encode('hola')))
+ ..addFile(ArchiveFile('media/abc.jpg', 3, [1, 2, 3]))
+ ..addFile(ArchiveFile('opengym-backup.json', data.length, data)));
+ final raw = openGymBackupFromZip(zip)!;
+ expect(detectFormat(raw), ImportFormat.openGym);
+ expect(parseImport(raw).sessions.single.exercises.length, 3);
+ expect(openGymBackupFromZip(ZipEncoder().encode(Archive()..addFile(ArchiveFile('weight.csv', 3, [1, 2, 3])))), isNull);
+ });
+
test('no confunde un backup de GymMane con uno de openGym', () {
expect(detectFormat('{"sessions": [], "routines": []}'), ImportFormat.unknown);
});