import io
from typing import Optional

import werkzeug
from flask import g
from flask_restful import Resource, reqparse

from server.api.api import analyze
from server.authentication import authenticate
from server.models import ErrorResponse
from server.services import AppServices
from text_recognition.models import TextRecognitionResult
from utils.logging_util import get_logger

logger = get_logger("ProcessImageUploadEndpoint")


class ProcessImageUploadEndpoint(Resource):
    method_decorators = [authenticate]

    IMAGE_ARG = "img"
    TYPE_ARG = "type"

    def __init__(self):
        parser = reqparse.RequestParser()
        parser.add_argument(ProcessImageUploadEndpoint.IMAGE_ARG,
                            type=werkzeug.datastructures.FileStorage,
                            help="Image to Analyze",
                            required=True,
                            location='files')
        parser.add_argument(ProcessImageUploadEndpoint.TYPE_ARG,
Пример #2
0
from nutrition_parser.models import ParsedNutritionResult
from server.models import NutritionAnalysisResponse, IngredientsAnalysisResponse, ErrorResponse, TYPE_NUTRITION, \
    TYPE_INGREDIENTS
from server.services import AppServices
from utils.logging_util import get_logger
"""
Central methods that endpoints will call to get the relevant information
- All methods MUST return a valid tuple of (response_dict, response_code?), no response_code implies a 200
"""

logger = get_logger("APIServer")


# TODO: Need to test this
def analyze(text: str, analyze_type: str,
            services: AppServices) -> (dict, int):
    if analyze_type == TYPE_NUTRITION:
        return __analyze_nutrition__(text, services)
    elif analyze_type == TYPE_INGREDIENTS:
        return __analyze_ingredients__(text, services)
    else:
        logger.info(f"Invalid request. Given analyze type: {analyze_type}")
        return ErrorResponse("Invalid analysis type").to_dict(), 400


def __analyze_nutrition__(text: str, services: AppServices) -> (dict, int):
    parse_result = services.nutrition_parser.parse(text)
    insights = services.nutrition_analyzer.get_insights(parse_result)
    # Determine the status
    status = __get_analyze_nutrition_status__(parse_result)
    response = NutritionAnalysisResponse(status=status,
Пример #3
0
from typing import Optional

from flask import g
from flask_restful import Resource, reqparse

from server.api.api import analyze
from server.authentication import authenticate
from server.models import ErrorResponse
from server.services import AppServices
from text_recognition.models import TextRecognitionResult
from utils.logging_util import get_logger

logger = get_logger("ProcessImageEndpoint")


class ProcessImageEndpoint(Resource):
    method_decorators = [authenticate]

    IMAGE_ARG = "b64_img"
    TYPE_ARG = "type"

    def __init__(self):
        parser = reqparse.RequestParser()
        parser.add_argument(ProcessImageEndpoint.IMAGE_ARG,
                            type=str,
                            help="Base64 encoded image string",
                            required=True,
                            location='json')
        parser.add_argument(ProcessImageEndpoint.TYPE_ARG,
                            type=str,
                            help="Type of label (nutrition/ingredient)",
Пример #4
0
import sys
import utils.logging_util as l_util
from apps.app_config import AppConfig
from utils.dataProvider.get_data import QuandlProvider
from utils import common_util as c_util

sys.path.append('../PythonandSQL')

l_util.config()
logger = l_util.get_logger(__name__)


@c_util.time_elapsed
def main(arg_app_name):
    if arg_app_name:
        logger.info('Triggering App: {}'.format(arg_app_name))
        app_cls = AppConfig().get_app(arg_app_name)
        app_cls(**user_opts.app_params).run()


if __name__ == "__main__":
    logger.info('Initializing Test Case')
    user_opts = c_util.UserOpts()
    main(user_opts.app_name)
"""
--APP_NAME=BONDS
--APP_PARAMS
RUN_CFG=/Users/krzysiekbienias/Documents/GitHub/Finance_Basic/run_cfg/bonds.yaml
"""

# # quandConnector=QuandlProvider(tickers=['AAPL', 'MSFT', 'GOOG', 'WMT'],startDate='2015-01-01',
import base64

from google.cloud import vision

from text_recognition.models import TextRecognitionResult
from utils.logging_util import get_logger

logger = get_logger("TextRecognitionClient")


class TextRecognitionClient:
    def __init__(self, credentials_filepath):
        self.client = vision.ImageAnnotatorClient.from_service_account_file(
            credentials_filepath)

    def detect_b64(self, b64_img_content: str) -> TextRecognitionResult:
        """
        Takes as input a Base64 encoded image string
        """
        try:
            byte_content = base64.b64decode(b64_img_content)
        except Exception as e:
            logger.error(f"Error decoding Base64 image: {e}", exc_info=True)
            return TextRecognitionResult(error="Invalid Base64 image string")
        return self.detect_bytes(byte_content)

    def detect_bytes(self, byte_img_content: bytes):
        image = vision.types.Image(content=byte_img_content)
        response = self.client.text_detection(image=image)
        return TextRecognitionResult.from_response(response)
Пример #6
0
import json
import os
import re
from typing import List, Optional

from ingredients.analysis.database.models import AdditiveInfo
from utils.logging_util import get_logger

logger = get_logger("AdditivesDatabase")


def __clean_for_comparison__(text: str):
    """
    Clean text for matching
    """
    text = text.lower()
    text = re.sub(r"[^\w\d]+", " ", text)
    return text


class AdditivesDatabase:
    def __init__(self, data_dir: str):
        """
        Requires the files to be placed in data_dir:
        - additives.json
        - sugar_synonyms.json
        """
        all_additives = []
        sugar_synonyms = []
        try:
            with open(os.path.join(data_dir, "additives.json"), "r") as f: