<commit_before>from datetime import datetime, timedelta

import numpy as np
import pytz
import stravalib
from sqlalchemy.sql import func

import gpx_import
from filters import degree_to_radian, celcius_to_kelvin
from model import User, Device, Move, Sample, db

MAX_DATE_TIME_OFFSET = timedelta(hours=2, minutes=30)

SAMPLE_TYPE = 'gps-base'


def map_type(type):
    if type == 'Run':
        return 'Running'
    elif type == 'Swim':
        return 'Pool swimming'
    elif type == 'Ride':
        return 'Cycling'
    elif type == 'Hike':
        return 'Trekking'
    else:
        return type


def strava_import(current_user, activity_id):
    client = get_strava_client(current_user)
    activity = client.get_activity(activity_id=activity_id)
    stream_types = ['time', 'distance', 'latlng', 'temp', 'heartrate', 'velocity_smooth', 'altitude']
    streams = client.get_activity_streams(activity_id, types=stream_types)

    activity_string = map_type(activity.type)

    result = db.session.query(Move.activity_type).filter(Move.activity == activity_string).first()
    if result:
        activity_type, = result
    else:
        activity_type = None

    device = find_device(current_user)

    move = Move()
    move.user = current_user
    move.duration = activity.elapsed_time
    move.ascent = float(activity.total_elevation_gain)
    move.speed_avg = float(activity.average_speed)
    move.hr_avg = heart_rate(activity.average_heartrate)
    move.temperature_avg = celcius_to_kelvin(activity.average_temp)
    move.device = device
    move.date_time = activity.start_date_local
    move.activity = activity_string
    move.activity_type = activity_type
    move.distance = float(activity.distance)
    move.import_date_time = datetime.now()
    move.import_module = __name__
    move.strava_activity_id = activity_id
    move.public = False
    move.source = "Strava activity id=%d; external_id='%s'" % (activity_id, activity.external_id)

    lengths = set([len(streams[stream].data) for stream in streams])
    assert len(lengths) == 1
    length, = lengths

    move.speed_max = move.speed_avg

    all_samples = []
    for i in range(0, length):
        time = timedelta(seconds=streams['time'].data[i])
        distance = float(streams['distance'].data[i])

        if 'heartrate' in streams:
            hr = float(streams['heartrate'].data[i])
        else:
            hr = None

        if 'latlng' in streams:
            lat, lng = streams['latlng'].data[i]
        else:
            lat = None
            lng = None

        if 'altitude' in streams:
            altitude = float(streams['altitude'].data[i])
        else:
            altitude = None

        if 'velocity_smooth' in streams:
            speed = float(streams['velocity_smooth'].data[i])
        else:
            speed = None

        if 'temp' in streams:
            temperature = celcius_to_kelvin(streams['temp'].data[i])<commit_msg>Fix Strava import if activity has no streams<commit_after>from datetime import datetime, timedelta

import numpy as np
import pytz
import stravalib
from sqlalchemy.sql import func

import gpx_import
from filters import degree_to_radian, celcius_to_kelvin
from model import User, Device, Move, Sample, db

MAX_DATE_TIME_OFFSET = timedelta(hours=2, minutes=30)

SAMPLE_TYPE = 'gps-base'


def map_type(type):
    if type == 'Run':
        return 'Running'
    elif type == 'Swim':
        return 'Pool swimming'
    elif type == 'Ride':
        return 'Cycling'
    elif type == 'Hike':
        return 'Trekking'
    else:
        return type


def strava_import(current_user, activity_id):
    client = get_strava_client(current_user)
    activity = client.get_activity(activity_id=activity_id)
    stream_types = ['time', 'distance', 'latlng', 'temp', 'heartrate', 'velocity_smooth', 'altitude']
    streams = client.get_activity_streams(activity_id, types=stream_types)

    activity_string = map_type(activity.type)

    result = db.session.query(Move.activity_type).filter(Move.activity == activity_string).first()
    if result:
        activity_type, = result
    else:
        activity_type = None

    device = find_device(current_user)

    move = Move()
    move.user = current_user
    move.duration = activity.elapsed_time
    move.ascent = float(activity.total_elevation_gain)
    move.speed_avg = float(activity.average_speed)
    move.hr_avg = heart_rate(activity.average_heartrate)
    move.temperature_avg = celcius_to_kelvin(activity.average_temp)
    move.device = device
    move.date_time = activity.start_date_local
    move.activity = activity_string
    move.activity_type = activity_type
    move.distance = float(activity.distance)
    move.import_date_time = datetime.now()
    move.import_module = __name__
    move.strava_activity_id = activity_id
    move.public = False
    move.source = "Strava activity id=%d; external_id='%s'" % (activity_id, activity.external_id)

    if streams:
        lengths = set([len(streams[stream].data) for stream in streams])
        assert len(lengths) == 1
        length, = lengths
    else:
        length = 0

    move.speed_max = move.speed_avg

    all_samples = []
    for i in range(0, length):
        time = timedelta(seconds=streams['time'].data[i])
        distance = float(streams['distance'].data[i])

        if 'heartrate' in streams:
            hr = float(streams['heartrate'].data[i])
        else:
            hr = None

        if 'latlng' in streams:
            lat, lng = streams['latlng'].data[i]
        else:
            lat = None
            lng = None

        if 'altitude' in streams:
            altitude = float(streams['altitude'].data[i])
        else:
            altitude = None

        if 'velocity_smooth' in streams:
            speed = float(streams['velocity_smooth'].data[i])
        else:
            speed = None

        if 'temp' in streams:
            temperature = celcius_to_kelvin(streams['temp'].data[i])
{'fraction_non_alphanumeric': 0.10426460711887173, 'fraction_numerical': 0.0018468770987239758, 'mean_word_length': 2.960771276595745, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3562380', 'n_tokens_mistral': 1890, 'n_tokens_neox': 1825, 'n_words': 415}