<commit_before>/*
The MIT License

Copyright (c) 2017-2017 <NAME>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#pragma once

#include <algorithm>
#include <array>
#include <cassert>
#include <cmath>
#include <string>
#include <tuple>
#include <vector>

#ifdef USE_CIMG
    #include <CImg.h>
#endif

#define STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_STATIC
#define STB_IMAGE_INLINE
#include "stb/stb_image.h"

#define STB_IMAGE_WRITE_IMPLEMENTATION
#define STB_IMAGE_WRITE_STATIC
#define STB_IMAGE_WRITE_INLINE
#include "stb/stb_image_write.h"

#define STB_IMAGE_RESIZE_IMPLEMENTATION
#define STB_IMAGE_RESIZE_STATIC
#define STB_IMAGE_RESIZE_INLINE
#include "stb/stb_image_resize.h"

#include "third_party/linalg.h"

#define tinymage_for1(bound,i) for (std::size_t i = 0UL; i<bound; ++i)
#define tinymage_forX(img,x) tinymage_for1( img.width(), x )
#define tinymage_forY(img,y) tinymage_for1( img.height(), y )
#define tinymage_forXY(img,x,y) tinymage_forY(img,y) tinymage_forX(img,x)

namespace tinymage_types {
    using coord_t = std::pair<size_t,size_t>;
    using quad_coord_t = std::tuple<coord_t,coord_t,coord_t,coord_t>;
}

// lightweight header only image class
template<typename T=float>
class tinymage final : private std::vector<T>
{
    // any other type of tinymage is a friend.
    template <typename U>
    friend class tinymage;

    template<typename U,typename V>
    using tinymage_if = std::enable_if_t<std::is_same<V, U>::value, tinymage<U>>;
    template<typename U,typename V>
    using tinymage_if_pair = std::enable_if_t<std::is_same<V, U>::value, std::pair<tinymage<U>,tinymage<U>>>;

    template<typename U> using tinymage_if_uchar = tinymage_if<U,unsigned char>;
    template<typename U> using tinymage_if_float = tinymage_if<U,float>;

    template<typename U> using tinymage_if_pair_float = tinymage_if_pair<U,float>;

    using std::vector<T>::at;
    using std::vector<T>::assign;
    using std::vector<T>::size;

    using std::vector<T>::begin;
    using std::vector<T>::end;

public:

    using std::vector<T>::data;

    tinymage() : m_width{0}, m_height{0} {}
    tinymage( std::size_t sx, std::size_t sy, T val = 0 ) : std::vector<T>( sx*sy, val ), m_width{sx}, m_height{sy} {}
    tinymage( uint8_t* buf, std::size_t sx, std::size_t sy, std::size_t bpp ) : m_width{sx}, m_height{sy}
    {
        assert( bpp == sizeof(T) );
        assign( buf, buf + sx*sy );
    }

    std::size_t size() const { return m_width * m_height; }

    bool load( const std::string& img_path )
    {
        int width, height, bpp;
        auto gray_image = stbi_load( img_path.c_str(), &width, &height, &bpp, 1); // force grayscale at image load
        if ( gray_image == nullptr )
            return false;
        assert( bpp == sizeof(T) );
        m_width = static_cast<std::size_t>( width );
        m_height = static_cast<std::size_t>( height );
        assign( gray_image, gray_image + m_width*m_height );
        stbi_image_free( gray_image );
        return true;
    }

    bool save_png( const std::string& img_path )
    {
        return stbi_write_png( img_path.c_str(), static_cast<int>( m_width ), static_cast<int>( m_height ), 1,
			data(), static_cast<int>( m_width * sizeof(T) ) ) != 0;
    }

    std::size_t width() const { return m_width; }
    std::size_t height() const { return m_height; }

    T& operator[]( std::size_t i )
    {
        return at( i );
    }

    T& at( std::size_t x, std::size_t y )
    {
        return at( x + m_width*y );
    }

    template<typename T2>
    T2 at( std::size_t x, std::size_t y ) const
    {
        return static_cast<T2>( at( x + m_width*y ) );
    }

    const T& c_at( std::size_t x, std::size_t y ) const
    {
        return at( x + m_width*y );
    }

    template<typename Func>
    void apply( Func f )
    {
        std::for_each( begin(), end(), f );
    }

    template<typename R>
    tinymage<R> convert() const
    {
        tinymage<R> output( m_width, m_height, 0 );
        output.assign( begin(), end() );
        return output;
    }

    void normalize( T min, T max )
    {
        _normalize( *this, min, max );
    }

    tinymage<T> get_normalize( T min, T max ) const
    {
        tinymage<T> output( *this );
        _normalize( output, min, max );
        return output;
    }

    T mean() const
    {
        auto sum = 0.;

        std::for_each( begin(), end(), [&]( const T& val )
            {
                sum += val;
            });

        return static_cast<T>( sum / ( m_width * m_height ) );
    }

    float line_centroid( size_t index )
    {
        auto _mean = 0.f;
        auto _total = 0.f;
        tinymage_forX( (*this),x )
        {
            _mean += x * c_at(x,index);
            _total += c_at(x,index);
        }
        return _mean / _total;
    }

    void threshold( T thresh )
    {
        std::for_each( begin(), end(), [&]( T& val )
            {
                val = val > thresh ? m_one : m_zero;
            });
    }

    tinymage<T> get_crop(   std::size_t startx,
                            std::size_t starty,
                            std::size_t stopx,
                            std::size_t stopy ) const
    {
        assert( stopx >= startx );
        assert( stopy >= starty );

        assert( stopx-startx <= m_width );
        assert( stopy-starty <= m_height );

        tinymage<T> output( stopx-startx, stopy-starty );

        for ( auto yin = starty,yout = std::size_t(0); yin<stopy; yin++, yout++ )
            for ( auto xin = startx,xout = std::size_t(0); xin<stopx; xin++, xout++ )
                output.at(xout,yout) = c_at(xin,yin);

        return output;
    }

    void crop(  std::size_t startx,
                std::size_t starty,
                std::size_t stopx,
                std::size_t stopy )
    {
        *this = get_crop( startx, starty, stopx, stopy );
    }

    void remove_border( std::size_t px_size )
    {
        crop( px_size, px_size, m_width - px_size, m_height - px_size );
    }

    void shift( int sx, int sy )
    {
        *this = get_shift( sx, sy );
    }

    tinymage<T> get_shift( int sx, int sy )
    {
        assert( std::abs( sx ) <= m_width );
        assert( std::abs( sy ) <= m_height );

        tinymage<T> output( m_width, m_height );

        std::size_t startx = std::max( sx, 0 );
        std::size_t stopx = std::min( m_width, m_width+sx );
        std::size_t starty = std::max( sy, 0 );
        std::size_t stopy = std::min( m_height, m_height+sy );

        for ( auto yin = starty,yout = std::size_t(0); yin<stopy; yin++, yout++ )
            for ( auto xin = startx,xout = std::size_t(0); xin<stopx; xin++, xout++ )
                output.at(xout,yout) = c_at(xin,yin);

        return output;
    }

    tinymage<T> get_columns(    std::size_t startx,<commit_msg>- added pad value management for shifting.<commit_after>/*
The MIT License

Copyright (c) 2017-2017 <NAME>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#pragma once

#include <algorithm>
#include <array>
#include <cassert>
#include <cmath>
#include <string>
#include <tuple>
#include <vector>

#ifdef USE_CIMG
    #include <CImg.h>
#endif

#define STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_STATIC
#define STB_IMAGE_INLINE
#include "stb/stb_image.h"

#define STB_IMAGE_WRITE_IMPLEMENTATION
#define STB_IMAGE_WRITE_STATIC
#define STB_IMAGE_WRITE_INLINE
#include "stb/stb_image_write.h"

#define STB_IMAGE_RESIZE_IMPLEMENTATION
#define STB_IMAGE_RESIZE_STATIC
#define STB_IMAGE_RESIZE_INLINE
#include "stb/stb_image_resize.h"

#include "third_party/linalg.h"

#define tinymage_for1(bound,i) for (std::size_t i = 0UL; i<bound; ++i)
#define tinymage_forX(img,x) tinymage_for1( img.width(), x )
#define tinymage_forY(img,y) tinymage_for1( img.height(), y )
#define tinymage_forXY(img,x,y) tinymage_forY(img,y) tinymage_forX(img,x)

namespace tinymage_types {
    using coord_t = std::pair<size_t,size_t>;
    using quad_coord_t = std::tuple<coord_t,coord_t,coord_t,coord_t>;
}

// lightweight header only image class
template<typename T=float>
class tinymage final : private std::vector<T>
{
    // any other type of tinymage is a friend.
    template <typename U>
    friend class tinymage;

    template<typename U,typename V>
    using tinymage_if = std::enable_if_t<std::is_same<V, U>::value, tinymage<U>>;
    template<typename U,typename V>
    using tinymage_if_pair = std::enable_if_t<std::is_same<V, U>::value, std::pair<tinymage<U>,tinymage<U>>>;

    template<typename U> using tinymage_if_uchar = tinymage_if<U,unsigned char>;
    template<typename U> using tinymage_if_float = tinymage_if<U,float>;

    template<typename U> using tinymage_if_pair_float = tinymage_if_pair<U,float>;

    using std::vector<T>::at;
    using std::vector<T>::assign;
    using std::vector<T>::size;

    using std::vector<T>::begin;
    using std::vector<T>::end;

public:

    using std::vector<T>::data;

    tinymage() : m_width{0}, m_height{0} {}
    tinymage( std::size_t sx, std::size_t sy, T val = 0 ) : std::vector<T>( sx*sy, val ), m_width{sx}, m_height{sy} {}
    tinymage( uint8_t* buf, std::size_t sx, std::size_t sy, std::size_t bpp ) : m_width{sx}, m_height{sy}
    {
        assert( bpp == sizeof(T) );
        assign( buf, buf + sx*sy );
    }

    std::size_t size() const { return m_width * m_height; }

    bool load( const std::string& img_path )
    {
        int width, height, bpp;
        auto gray_image = stbi_load( img_path.c_str(), &width, &height, &bpp, 1); // force grayscale at image load
        if ( gray_image == nullptr )
            return false;
        assert( bpp == sizeof(T) );
        m_width = static_cast<std::size_t>( width );
        m_height = static_cast<std::size_t>( height );
        assign( gray_image, gray_image + m_width*m_height );
        stbi_image_free( gray_image );
        return true;
    }

    bool save_png( const std::string& img_path )
    {
        return stbi_write_png( img_path.c_str(), static_cast<int>( m_width ), static_cast<int>( m_height ), 1,
			data(), static_cast<int>( m_width * sizeof(T) ) ) != 0;
    }

    std::size_t width() const { return m_width; }
    std::size_t height() const { return m_height; }

    T& operator[]( std::size_t i )
    {
        return at( i );
    }

    T& at( std::size_t x, std::size_t y )
    {
        return at( x + m_width*y );
    }

    template<typename T2>
    T2 at( std::size_t x, std::size_t y ) const
    {
        return static_cast<T2>( at( x + m_width*y ) );
    }

    const T& c_at( std::size_t x, std::size_t y ) const
    {
        return at( x + m_width*y );
    }

    template<typename Func>
    void apply( Func f )
    {
        std::for_each( begin(), end(), f );
    }

    template<typename R>
    tinymage<R> convert() const
    {
        tinymage<R> output( m_width, m_height, 0 );
        output.assign( begin(), end() );
        return output;
    }

    void normalize( T min, T max )
    {
        _normalize( *this, min, max );
    }

    tinymage<T> get_normalize( T min, T max ) const
    {
        tinymage<T> output( *this );
        _normalize( output, min, max );
        return output;
    }

    T mean() const
    {
        auto sum = 0.;

        std::for_each( begin(), end(), [&]( const T& val )
            {
                sum += val;
            });

        return static_cast<T>( sum / ( m_width * m_height ) );
    }

    float line_centroid( size_t index )
    {
        auto _mean = 0.f;
        auto _total = 0.f;
        tinymage_forX( (*this),x )
        {
            _mean += x * c_at(x,index);
            _total += c_at(x,index);
        }
        return _mean / _total;
    }

    void threshold( T thresh )
    {
        std::for_each( begin(), end(), [&]( T& val )
            {
                val = val > thresh ? m_one : m_zero;
            });
    }

    tinymage<T> get_crop(   std::size_t startx,
                            std::size_t starty,
                            std::size_t stopx,
                            std::size_t stopy ) const
    {
        assert( stopx >= startx );
        assert( stopy >= starty );

        assert( stopx-startx <= m_width );
        assert( stopy-starty <= m_height );

        tinymage<T> output( stopx-startx, stopy-starty );

        for ( auto yin = starty,yout = std::size_t(0); yin<stopy; yin++, yout++ )
            for ( auto xin = startx,xout = std::size_t(0); xin<stopx; xin++, xout++ )
                output.at(xout,yout) = c_at(xin,yin);

        return output;
    }

    void crop(  std::size_t startx,
                std::size_t starty,
                std::size_t stopx,
                std::size_t stopy )
    {
        *this = get_crop( startx, starty, stopx, stopy );
    }

    void remove_border( std::size_t px_size )
    {
        crop( px_size, px_size, m_width - px_size, m_height - px_size );
    }

    void shift( int sx, int sy, T pad_val = 0 )
    {
        *this = get_shift( sx, sy, pad_val );
    }

    tinymage<T> get_shift( int sx, int sy, T pad_val = 0 )
    {
        assert( std::abs( sx ) <= m_width );
        assert( std::abs( sy ) <= m_height );

        tinymage<T> output( m_width, m_height, pad_val );

        std::size_t startx = std::max( sx, 0 );
        std::size_t stopx = std::min( m_width, m_width+sx );
        std::size_t starty = std::max( sy, 0 );
        std::size_t stopy = std::min( m_height, m_height+sy );

        for ( auto yin = starty,yout = std::size_t(0); yin<stopy; yin++, yout++ )
            for ( auto xin = startx,xout = std::size_t(0); xin<stopx; xin++, xout++ )
                output.at(xout,yout) = c_at(xin,yin);

        return output;
    }

    tinymage<T> get_columns(    std::size_t startx,
{'fraction_non_alphanumeric': 0.12480061251834365, 'fraction_numerical': 0.0042110636125821475, 'mean_word_length': 2.72215625742104, 'pattern_counts': {'":': 0, '<': 133, '<?xml version=': 0, '>': 121, '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': '4082029', 'n_tokens_mistral': 5605, 'n_tokens_neox': 5433, 'n_words': 1459}