repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
graphiti
tests/embedder/test_openai.py
.py
""" Copyright 2024, Zep Software, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, sof...
127
4,396
graphiti
tests/embedder/embedder_fixtures.py
.py
""" Copyright 2024, Zep Software, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, sof...
21
777
graphiti
tests/embedder/test_gemini.py
.py
""" Copyright 2024, Zep Software, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, sof...
396
15,091
graphiti
tests/driver/test_falkordb_ops_routing.py
.py
"""Unit tests for FalkorDB per-group-id query routing in the operations layer. These cover the *namespace/ops* read path (e.g. ``graphiti.nodes.episode. get_by_group_ids``), which delegates to the Falkor ``*Operations`` classes with the base driver (pointed at ``default_db``). FalkorDB stores each ``group_id`` in its ...
120
4,473
graphiti
tests/driver/test_falkordb_driver.py
.py
""" Copyright 2024, Zep Software, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, sof...
432
17,532
graphiti
tests/llm_client/test_openai_generic_client.py
.py
import json from types import SimpleNamespace import openai import pytest from pydantic import BaseModel from graphiti_core.llm_client.config import LLMConfig from graphiti_core.llm_client.errors import EmptyResponseError, RateLimitError from graphiti_core.llm_client.openai_generic_client import OpenAIGenericClient f...
171
6,369
graphiti
tests/llm_client/test_anthropic_client.py
.py
""" Copyright 2024, Zep Software, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, sof...
256
9,893
graphiti
tests/llm_client/test_client.py
.py
""" Copyright 2024, Zep Software, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, sof...
109
4,484
graphiti
tests/llm_client/test_errors.py
.py
""" Copyright 2024, Zep Software, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, sof...
77
2,764
graphiti
tests/llm_client/test_azure_openai_client.py
.py
from types import SimpleNamespace import pytest from pydantic import BaseModel from graphiti_core.llm_client.azure_openai_client import AzureOpenAILLMClient from graphiti_core.llm_client.config import LLMConfig class DummyResponses: def __init__(self): self.parse_calls: list[dict] = [] async def pa...
127
3,639
graphiti
tests/llm_client/test_openai_client.py
.py
from types import SimpleNamespace import pytest from pydantic import BaseModel from graphiti_core.llm_client.config import LLMConfig from graphiti_core.llm_client.openai_base_client import DEFAULT_MODEL, DEFAULT_REASONING from graphiti_core.llm_client.openai_client import OpenAIClient class DummyResponses: def ...
222
6,849
graphiti
tests/llm_client/test_gemini_client.py
.py
""" Copyright 2024, Zep Software, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, sof...
483
20,920
graphiti
tests/llm_client/test_token_tracker.py
.py
""" Copyright 2024, Zep Software, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, sof...
215
7,553
graphiti
tests/llm_client/test_anthropic_client_int.py
.py
""" Copyright 2024, Zep Software, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, sof...
86
2,872
graphiti
tests/llm_client/test_cache.py
.py
""" Copyright 2024, Zep Software, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, sof...
113
4,036
graphiti
tests/utils/test_content_chunking.py
.py
""" Copyright 2024, Zep Software, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, sof...
781
30,429
graphiti
tests/utils/test_concatenate_episodes.py
.py
"""Tests for graphiti_core.utils.text_utils.""" from datetime import datetime, timezone from unittest.mock import MagicMock from graphiti_core.utils.text_utils import concatenate_episodes def _make_episode(content: str, valid_at: datetime | None = None) -> MagicMock: ep = MagicMock() ep.content = content ...
53
2,201
graphiti
tests/utils/maintenance/test_bulk_utils.py
.py
from collections import deque from unittest.mock import AsyncMock, MagicMock import pytest from graphiti_core.edges import EntityEdge from graphiti_core.graphiti_types import GraphitiClients from graphiti_core.nodes import EntityNode, EpisodeType, EpisodicNode from graphiti_core.utils import bulk_utils from graphiti_...
566
17,819
graphiti
tests/utils/maintenance/test_attribute_utils.py
.py
import logging import pytest from pydantic import BaseModel, Field from graphiti_core.utils.maintenance.attribute_utils import ( DEFAULT_ATTRIBUTE_MAX_LENGTH, LIST_TOTAL_LENGTH_MULTIPLIER, apply_capped_attributes, cap_string_attributes, ) class _Person(BaseModel): phones: str | None = Field( ...
257
9,927
graphiti
tests/utils/maintenance/test_node_operations.py
.py
import logging from collections import defaultdict from unittest.mock import AsyncMock, MagicMock import pytest from graphiti_core.graphiti_types import GraphitiClients from graphiti_core.nodes import EntityNode, EpisodeType, EpisodicNode from graphiti_core.utils.datetime_utils import utc_now from graphiti_core.utils...
921
30,945
graphiti
tests/utils/maintenance/test_edge_operations.py
.py
from datetime import datetime, timedelta, timezone from types import SimpleNamespace from unittest.mock import AsyncMock, MagicMock import pytest from pydantic import BaseModel from graphiti_core.edges import EntityEdge from graphiti_core.nodes import EntityNode, EpisodicNode from graphiti_core.search.search_config i...
774
24,523
graphiti
tests/utils/maintenance/test_entity_extraction.py
.py
""" Copyright 2024, Zep Software, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, sof...
662
21,832
graphiti
tests/utils/maintenance/test_remove_communities.py
.py
""" Copyright 2024, Zep Software, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, sof...
99
3,191
graphiti
tests/utils/search/test_edge_cross_encoder_rrf_shortlist.py
.py
from datetime import datetime, timezone from types import SimpleNamespace import pytest from graphiti_core.edges import EntityEdge from graphiti_core.search.search import edge_search from graphiti_core.search.search_config import EdgeReranker, EdgeSearchConfig, EdgeSearchMethod from graphiti_core.search.search_filter...
124
4,509
graphiti
tests/utils/search/test_search_tracing.py
.py
from collections.abc import Generator from contextlib import contextmanager from types import SimpleNamespace import pytest from graphiti_core.search.search import edge_search, search from graphiti_core.search.search_config import EdgeSearchConfig, EdgeSearchMethod, SearchConfig from graphiti_core.search.search_filte...
150
4,674
graphiti
tests/utils/search/search_utils_test.py
.py
from unittest.mock import AsyncMock, patch import pytest from graphiti_core.nodes import EntityNode from graphiti_core.search.search_filters import SearchFilters from graphiti_core.search.search_utils import hybrid_node_search @pytest.mark.asyncio async def test_hybrid_node_search_deduplication(): # Mock the da...
164
6,567
graphiti
tests/utils/search/test_search_security.py
.py
from types import SimpleNamespace from unittest.mock import MagicMock import pytest from pydantic import ValidationError from graphiti_core.driver.driver import GraphProvider from graphiti_core.driver.falkordb.operations.search_ops import _build_falkor_fulltext_query from graphiti_core.driver.neo4j.operations.search_...
161
6,459
graphiti
tests/utils/search/test_edge_bfs_query_shape.py
.py
"""Query-shape regression tests for edge_bfs_search (no live database). Completes #1500 on the generic path in ``graphiti_core/search/search_utils.py``, which is what executes today for FalkorDB and Neo4j (``driver.search_interface`` is never assigned, so the driver-level operations modules patched by #1500 are not re...
137
4,784
graphiti
tests/cross_encoder/test_bge_reranker_client_int.py
.py
""" Copyright 2024, Zep Software, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, sof...
79
2,403
graphiti
tests/cross_encoder/test_gemini_reranker_client.py
.py
""" Copyright 2024, Zep Software, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, sof...
354
14,027
graphiti
tests/evals/eval_e2e_graph_building.py
.py
""" Copyright 2024, Zep Software, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, sof...
181
6,813
graphiti
tests/evals/utils.py
.py
""" Copyright 2024, Zep Software, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, sof...
40
1,184
graphiti
tests/evals/eval_cli.py
.py
import argparse import asyncio from tests.evals.eval_e2e_graph_building import build_baseline_graph, eval_graph async def main(): parser = argparse.ArgumentParser( description='Run eval_graph and optionally build_baseline_graph from the command line.' ) parser.add_argument( '--multi-sess...
41
1,203
graphiti
examples/quickstart/quickstart_neo4j.py
.py
""" Copyright 2025, Zep Software, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, sof...
240
9,438
graphiti
examples/quickstart/quickstart_neptune.py
.py
""" Copyright 2025, Zep Software, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, sof...
253
9,774
graphiti
examples/quickstart/dense_vs_normal_ingestion.py
.py
""" Copyright 2025, Zep Software, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, sof...
343
14,626
graphiti
examples/quickstart/quickstart_falkordb.py
.py
""" Copyright 2025, Zep Software, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, sof...
257
10,328
graphiti
examples/wizard_of_oz/parser.py
.py
import os import re def parse_wizard_of_oz(file_path): with open(file_path, encoding='utf-8') as file: content = file.read() # Split the content into chapters chapters = re.split(r'\n\n+Chapter [IVX]+\n', content)[ 1: ] # Skip the first split which is before Chapter I episodes =...
37
1,120
graphiti
examples/wizard_of_oz/runner.py
.py
""" Copyright 2024, Zep Software, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, sof...
94
3,029
graphiti
examples/azure-openai/azure_openai_neo4j.py
.py
""" Copyright 2025, Zep Software, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, sof...
226
8,530
graphiti
examples/gliner2/gliner2_neo4j.py
.py
""" Copyright 2025, Zep Software, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, sof...
328
13,227
graphiti
examples/podcast/podcast_runner.py
.py
""" Copyright 2024, Zep Software, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, sof...
194
6,988
graphiti
examples/podcast/transcript_parser.py
.py
import os import re from datetime import datetime, timedelta, timezone from pydantic import BaseModel class Speaker(BaseModel): index: int name: str role: str class ParsedMessage(BaseModel): speaker_index: int speaker_name: str role: str relative_timestamp: str actual_timestamp: dat...
125
4,274
graphiti
examples/ecommerce/runner.py
.py
""" Copyright 2024, Zep Software, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, sof...
124
4,082
graphiti
examples/opentelemetry/otel_stdout_example.py
.py
""" Copyright 2025, Zep Software, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, sof...
126
4,358
EasyOCR
setup.py
.py
""" End-to-End Multi-Lingual Optical Character Recognition (OCR) Solution """ from io import open from setuptools import setup with open('requirements.txt', encoding="utf-8-sig") as f: requirements = f.readlines() def readme(): with open('README.md', encoding="utf-8-sig") as f: README = f.read() r...
36
1,100
EasyOCR
trainer/utils.py
.py
import torch import pickle import numpy as np device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') class AttrDict(dict): def __init__(self, *args, **kwargs): super(AttrDict, self).__init__(*args, **kwargs) self.__dict__ = self ##### https://github.com/githubharald/CTCDecoder/blob/...
366
14,518
EasyOCR
trainer/train.py
.py
import os import sys import time import random import torch import torch.backends.cudnn as cudnn import torch.nn as nn import torch.nn.init as init import torch.optim as optim import torch.utils.data from torch.cuda.amp import autocast, GradScaler import numpy as np from utils import CTCLabelConverter, AttnLabelConver...
283
12,198
EasyOCR
trainer/model.py
.py
import torch.nn as nn from modules.transformation import TPS_SpatialTransformerNetwork from modules.feature_extraction import VGG_FeatureExtractor, RCNN_FeatureExtractor, ResNet_FeatureExtractor from modules.sequence_modeling import BidirectionalLSTM from modules.prediction import Attention class Model(nn.Module): ...
75
3,573
EasyOCR
trainer/dataset.py
.py
import os import sys import re import six import math import torch import pandas as pd from natsort import natsorted from PIL import Image import numpy as np from torch.utils.data import Dataset, ConcatDataset, Subset from torch._utils import _accumulate import torchvision.transforms as transforms def contrast_grey(...
284
11,060
EasyOCR
trainer/test.py
.py
import os import time import string import argparse import torch import torch.backends.cudnn as cudnn import torch.utils.data import torch.nn.functional as F import numpy as np from nltk.metrics.distance import edit_distance from utils import CTCLabelConverter, AttnLabelConverter, Averager from dataset import hierarc...
113
4,722
EasyOCR
trainer/craft/train.py
.py
# -*- coding: utf-8 -*- import argparse import os import shutil import time import multiprocessing as mp import yaml import numpy as np import torch import torch.nn as nn import torch.optim as optim import wandb from config.load_config import load_yaml, DotDict from data.dataset import SynthTextDataSet, CustomDataset...
480
17,330
EasyOCR
trainer/craft/trainSynth.py
.py
# -*- coding: utf-8 -*- import argparse import os import shutil import time import yaml import multiprocessing as mp import numpy as np import torch import torch.nn as nn import torch.optim as optim import wandb from config.load_config import load_yaml, DotDict from data.dataset import SynthTextDataSet from loss.msel...
410
14,471
EasyOCR
trainer/craft/eval.py
.py
# -*- coding: utf-8 -*- import argparse import os import cv2 import numpy as np import torch import torch.backends.cudnn as cudnn from tqdm import tqdm import wandb from config.load_config import load_yaml, DotDict from model.craft import CRAFT from metrics.eval_det_iou import DetectionIoUEvaluator from utils.infere...
382
12,008
EasyOCR
trainer/craft/train_distributed.py
.py
# -*- coding: utf-8 -*- import argparse import os import shutil import time import multiprocessing as mp import yaml import numpy as np import torch import torch.nn as nn import torch.optim as optim import wandb from config.load_config import load_yaml, DotDict from data.dataset import SynthTextDataSet, CustomDataset...
524
19,294
EasyOCR
trainer/craft/loss/mseloss.py
.py
import torch import torch.nn as nn class Loss(nn.Module): def __init__(self): super(Loss, self).__init__() def forward(self, gt_region, gt_affinity, pred_region, pred_affinity, conf_map): loss = torch.mean( ((gt_region - pred_region).pow(2) + (gt_affinity - pred_affinity).pow(2)) ...
173
5,709
EasyOCR
trainer/craft/config/load_config.py
.py
import os import yaml from functools import reduce CONFIG_PATH = os.path.dirname(__file__) def load_yaml(config_name): with open(os.path.join(CONFIG_PATH, config_name)+ '.yaml') as file: config = yaml.safe_load(file) return config class DotDict(dict): def __getattr__(self, k): try: ...
37
987
EasyOCR
trainer/craft/model/vgg16_bn.py
.py
import torch import torch.nn as nn import torch.nn.init as init import torchvision from torchvision import models from packaging import version def init_weights(modules): for m in modules: if isinstance(m, nn.Conv2d): init.xavier_uniform_(m.weight.data) if m.bias is not None: ...
78
2,962
EasyOCR
trainer/craft/model/craft.py
.py
""" Copyright (c) 2019-present NAVER Corp. MIT License """ # -*- coding: utf-8 -*- import torch import torch.nn as nn import torch.nn.functional as F from model.vgg16_bn import vgg16_bn, init_weights class double_conv(nn.Module): def __init__(self, in_ch, mid_ch, out_ch): super(double_conv, self).__ini...
112
3,788
EasyOCR
trainer/craft/metrics/eval_det_iou.py
.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from collections import namedtuple import numpy as np from shapely.geometry import Polygon """ cite from: PaddleOCR, github: https://github.com/PaddlePaddle/PaddleOCR PaddleOCR reference from : https://github.com/MhLiao/DB/blob/3c32b808d4412680310d3d28eeb6a2d5bf1566c5/conce...
245
8,665
EasyOCR
trainer/craft/utils/craft_utils.py
.py
# -*- coding: utf-8 -*- import os import torch import cv2 import math import numpy as np from data import imgproc """ auxilary functions """ # unwarp corodinates def warpCoord(Minv, pt): out = np.matmul(Minv, (pt[0], pt[1], 1)) return np.array([out[0]/out[2], out[1]/out[2]]) """ end of auxilary functions ...
345
14,030
EasyOCR
trainer/craft/utils/util.py
.py
from collections import OrderedDict import os import cv2 import numpy as np from data import imgproc from utils import craft_utils def copyStateDict(state_dict): if list(state_dict.keys())[0].startswith("module"): start_idx = 1 else: start_idx = 0 new_state_dict = OrderedDict() for k...
143
4,759
EasyOCR
trainer/craft/utils/inference_boxes.py
.py
import os import re import itertools import cv2 import time import numpy as np import torch from torch.autograd import Variable from utils.craft_utils import getDetBoxes, adjustResultCoordinates from data import imgproc from data.dataset import SynthTextDataSet import math import xml.etree.ElementTree as elemTree #...
362
11,756
EasyOCR
trainer/craft/data/imgproc.py
.py
""" Copyright (c) 2019-present NAVER Corp. MIT License """ # -*- coding: utf-8 -*- import numpy as np import cv2 from skimage import io def loadImage(img_file): img = io.imread(img_file) # RGB order if img.shape[0] == 2: img = img[0] if len(img.shape) == 2: img = cv2.cvtColor(img, cv2...
92
2,340
EasyOCR
trainer/craft/data/gaussian.py
.py
import numpy as np import cv2 from data.boxEnlarge import enlargebox class GaussianBuilder(object): def __init__(self, init_size, sigma, enlarge_region, enlarge_affinity): self.init_size = init_size self.sigma = sigma self.enlarge_region = enlarge_region self.enlarge_affinity = en...
192
7,227
EasyOCR
trainer/craft/data/imgaug.py
.py
import random import cv2 import numpy as np from PIL import Image from torchvision.transforms.functional import resized_crop, crop from torchvision.transforms import RandomResizedCrop, RandomCrop from torchvision.transforms import InterpolationMode def rescale(img, bboxes, target_size=2240): h, w = img.shape[0:2...
176
5,316
EasyOCR
trainer/craft/data/boxEnlarge.py
.py
import math import numpy as np def pointAngle(Apoint, Bpoint): angle = (Bpoint[1] - Apoint[1]) / ((Bpoint[0] - Apoint[0]) + 10e-8) return angle def pointDistance(Apoint, Bpoint): return math.sqrt((Bpoint[1] - Apoint[1])**2 + (Bpoint[0] - Apoint[0])**2) def lineBiasAndK(Apoint, Bpoint): K = pointAng...
65
2,247
EasyOCR
trainer/craft/data/dataset.py
.py
import os import re import itertools import random import numpy as np import scipy.io as scio from PIL import Image import cv2 from torch.utils.data import Dataset import torchvision.transforms as transforms from data import imgproc from data.gaussian import GaussianBuilder from data.imgaug import ( rescale, ...
543
17,766
EasyOCR
trainer/craft/data/pseudo_label/watershed.py
.py
import cv2 import numpy as np from skimage.segmentation import watershed def segment_region_score(watershed_param, region_score, word_image, pseudo_vis_opt): region_score = np.float32(region_score) / 255 fore = np.uint8(region_score > 0.75) back = np.uint8(region_score < 0.05) unknown = 1 - (fore + ba...
46
1,353
EasyOCR
trainer/craft/data/pseudo_label/make_charbox.py
.py
import os import random import math import numpy as np import cv2 import torch from data import imgproc from data.pseudo_label.watershed import exec_watershed_by_version class PseudoCharBoxBuilder: def __init__(self, watershed_param, vis_test_dir, pseudo_vis_opt, gaussian_builder): self.watershed_param ...
264
9,045
EasyOCR
trainer/modules/prediction.py
.py
import torch import torch.nn as nn import torch.nn.functional as F device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') class Attention(nn.Module): def __init__(self, input_size, hidden_size, num_classes): super(Attention, self).__init__() self.attention_cell = AttentionCell(inpu...
82
4,026
EasyOCR
trainer/modules/feature_extraction.py
.py
import torch.nn as nn import torch.nn.functional as F class VGG_FeatureExtractor(nn.Module): """ FeatureExtractor of CRNN (https://arxiv.org/pdf/1507.05717.pdf) """ def __init__(self, input_channel, output_channel=512): super(VGG_FeatureExtractor, self).__init__() self.output_channel = [int(o...
247
10,366
EasyOCR
trainer/modules/transformation.py
.py
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') class TPS_SpatialTransformerNetwork(nn.Module): """ Rectification Network of RARE, namely TPS based STN """ def __init__(self, F, I_size, I_r_size, I_cha...
161
8,116
EasyOCR
trainer/modules/sequence_modeling.py
.py
import torch.nn as nn class BidirectionalLSTM(nn.Module): def __init__(self, input_size, hidden_size, output_size): super(BidirectionalLSTM, self).__init__() self.rnn = nn.LSTM(input_size, hidden_size, bidirectional=True, batch_first=True) self.linear = nn.Linear(hidden_size * 2, output_s...
23
796
EasyOCR
unit_test/make_test_solution.py
.py
import os import argparse import lzma import pickle from datetime import datetime import numpy as np import PIL.Image import torch import easyocr # %% def count_parameters(model): return sum([param.numel() for param in model.parameters()]) def get_weight_norm(model): with torch.no_grad(): return sum...
648
24,942
EasyOCR
unit_test/demo.py
.py
import os from unit_test import UnitTest # %% Set up paths easyocr_module = "../easyocr" verbose = 2 test_data = "./data/EasyOcrUnitTestPackage.pickle" image_data_dir = "../examples" # %% Initialize UnitTest unit_test = UnitTest(easyocr_module, test_data, image_data_dir ...
16
409
EasyOCR
unit_test/unit_test.py
.py
import os import sys import importlib import pickle import lzma import PIL.Image import numpy as np import torch # %% class Attributes: pass class UnitTest: def __init__(self, easyocr_module, test_data = "./data/EasyOcrUnitTestPackage.pickle", image_data_d...
262
10,576
EasyOCR
unit_test/run_unit_test.py
.py
import argparse from unit_test import UnitTest # %% def main(args): unit_test = UnitTest(args.easyocr, args.test_data, args.image_data_dir, args.verbose) unit_test.do_test(args.verbose) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Script to run EasyOCR unit tet.", ...
20
882
EasyOCR
easyocr/craft_utils.py
.py
""" Copyright (c) 2019-present NAVER Corp. MIT License """ # -*- coding: utf-8 -*- import numpy as np import cv2 import math from scipy.ndimage import label """ auxiliary functions """ # unwarp corodinates def warpCoord(Minv, pt): out = np.matmul(Minv, (pt[0], pt[1], 1)) return np.array([out[0]/out[2], out[...
252
9,583
EasyOCR
easyocr/imgproc.py
.py
""" Copyright (c) 2019-present NAVER Corp. MIT License """ # -*- coding: utf-8 -*- import numpy as np from skimage import io import cv2 def loadImage(img_file): img = io.imread(img_file) # RGB order if img.shape[0] == 2: img = img[0] if len(img.shape) == 2 : img = cv2.cvtColor(img, cv2.COLOR_G...
71
2,195
EasyOCR
easyocr/utils.py
.py
from __future__ import print_function import torch import pickle import numpy as np import math import cv2 from PIL import Image, JpegImagePlugin from scipy import ndimage import hashlib import sys, os from zipfile import ZipFile from .imgproc import loadImage if sys.version_info[0] == 2: from six.moves.urllib.re...
836
34,062
EasyOCR
easyocr/export.py
.py
import argparse import onnx import torch import easyocr import numpy as np def export_detector(detector_onnx_save_path, in_shape=[1, 3, 608, 800], lang_list=["en"], model_storage_directory=None, user_network_directory=None, ...
128
5,682
EasyOCR
easyocr/__init__.py
.py
from .easyocr import Reader __version__ = '1.7.2'
4
51
EasyOCR
easyocr/easyocr.py
.py
# -*- coding: utf-8 -*- from .recognition import get_recognizer, get_text from .utils import group_text_box, get_image_list, calculate_md5, get_paragraph,\ download_and_unzip, printProgressBar, diff, reformat_input,\ make_rotated_img_list, set_result_with_confidence,\ ...
580
31,891
EasyOCR
easyocr/detection_db.py
.py
''' Created by Jaided AI Released Date: 18/08/2022 Description: A wrapper for DBNet text detection module for EasyOCR ''' import os import numpy as np import torch import torch.backends.cudnn as cudnn from .DBNet.DBNet import DBNet def test_net(image, detector, threshold = 0.2, ...
221
8,772
EasyOCR
easyocr/recognition.py
.py
from PIL import Image import torch import torch.backends.cudnn as cudnn import torch.utils.data import torch.nn.functional as F import torchvision.transforms as transforms import numpy as np from collections import OrderedDict import importlib from .utils import CTCLabelConverter import math def custom_mean(x): re...
234
9,353
EasyOCR
easyocr/craft.py
.py
""" Copyright (c) 2019-present NAVER Corp. MIT License """ # -*- coding: utf-8 -*- import torch import torch.nn as nn import torch.nn.functional as F from .model.modules import vgg16_bn, init_weights class double_conv(nn.Module): def __init__(self, in_ch, mid_ch, out_ch): super(double_conv, self).__init_...
81
2,590
EasyOCR
easyocr/detection.py
.py
import torch import torch.backends.cudnn as cudnn from torch.autograd import Variable from PIL import Image from collections import OrderedDict import cv2 import numpy as np from .craft_utils import getDetBoxes, adjustResultCoordinates from .imgproc import resize_aspect_ratio, normalizeMeanVariance from .craft import ...
111
4,222
EasyOCR
easyocr/cli.py
.py
import argparse import easyocr def parse_args(): parser = argparse.ArgumentParser(description="Process EasyOCR.") parser.add_argument( "-l", "--lang", nargs='+', required=True, type=str, help="for languages", ) parser.add_argument( "--gpu", ...
284
8,659
EasyOCR
easyocr/config.py
.py
import os os.environ["LRU_CACHE_CAPACITY"] = "1" BASE_PATH = os.path.dirname(__file__) MODULE_PATH = os.environ.get("EASYOCR_MODULE_PATH") or \ os.environ.get("MODULE_PATH") or \ os.path.expanduser("~/.EasyOCR/") # detector parameters detection_models = { 'craft' : { 'filename...
212
91,824
EasyOCR
easyocr/DBNet/DBNet.py
.py
''' Created by Jaided AI Released Date: 18/08/2022 Description: DBNet text detection module. Many parts of the codes are adapted from https://github.com/MhLiao/DB ''' import os import math import yaml from shapely.geometry import Polygon import PIL.Image import numpy as np import cv2 import pyclipper import torch fro...
767
28,450
EasyOCR
easyocr/DBNet/backbones/resnet.py
.py
import torch.nn as nn import math import torch.utils.model_zoo as model_zoo BatchNorm2d = nn.BatchNorm2d __all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152'] model_urls = { 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth', 'resnet34': 'https://d...
341
12,428
EasyOCR
easyocr/DBNet/backbones/mobilenetv3.py
.py
# https://github.com/kuan-wang/pytorch-mobilenet-v3 import torch import torch.nn as nn import torch.nn.functional as F __all__ = ['MobileNetV3', 'mobilenetv3'] def conv_bn(inp, oup, stride, conv_layer=nn.Conv2d, norm_layer=nn.BatchNorm2d, nlin_layer=nn.ReLU): return nn.Sequential( conv_layer(inp, oup, 3...
253
8,930
EasyOCR
easyocr/DBNet/decoders/balance_cross_entropy_loss.py
.py
import torch import torch.nn as nn class BalanceCrossEntropyLoss(nn.Module): ''' Balanced cross entropy loss. Shape: - Input: :math:`(N, 1, H, W)` - GT: :math:`(N, 1, H, W)`, same shape as the input - Mask: :math:`(N, H, W)`, same spatial shape as the input - Output: scalar...
57
1,954
EasyOCR
easyocr/DBNet/decoders/seg_detector_asf.py
.py
from collections import OrderedDict import pdb import torch import torch.nn as nn from .feature_attention import ScaleFeatureSelection BatchNorm2d = nn.BatchNorm2d class SegSpatialScaleDetector(nn.Module): def __init__(self, in_channels=[64, 128, 256, 512], inner_channels=256, k=...
163
7,048
EasyOCR
easyocr/DBNet/decoders/feature_attention.py
.py
import torch import torch.nn as nn import torch.nn.functional as F class ScaleChannelAttention(nn.Module): def __init__(self, in_planes, out_planes, num_features, init_weight=True): super(ScaleChannelAttention, self).__init__() self.avgpool = nn.AdaptiveAvgPool2d(1) print(self.avgpool) ...
145
5,925
EasyOCR
easyocr/DBNet/decoders/l1_loss.py
.py
import torch import torch.nn as nn class MaskL1Loss(nn.Module): def __init__(self): super(MaskL1Loss, self).__init__() def forward(self, pred: torch.Tensor, gt, mask): mask_sum = mask.sum() if mask_sum.item() == 0: return mask_sum, dict(l1_loss=mask_sum) else: ...
42
1,363
EasyOCR
easyocr/DBNet/decoders/simple_detection.py
.py
import torch import torch.nn as nn import torch.nn.functional as F from backbones.upsample_head import SimpleUpsampleHead class SimpleDetectionDecoder(nn.Module): def __init__(self, feature_channel=256): nn.Module.__init__(self) self.feature_channel = feature_channel self.head_layer = s...
192
6,383
EasyOCR
easyocr/DBNet/decoders/pss_loss.py
.py
import torch import torch.nn as nn import torch.nn.functional as F class PSS_Loss(nn.Module): def __init__(self, cls_loss): super(PSS_Loss, self).__init__() self.eps = 1e-6 self.criterion = eval('self.' + cls_loss + '_loss') def dice_loss(self, pred, gt, m): intersection = tor...
116
4,582
EasyOCR
easyocr/DBNet/decoders/seg_detector.py
.py
from collections import OrderedDict import torch import torch.nn as nn BatchNorm2d = nn.BatchNorm2d class SegDetector(nn.Module): def __init__(self, in_channels=[64, 128, 256, 512], inner_channels=256, k=10, bias=False, adaptive=False, smooth=False, serial=False,...
153
6,112