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
khoj
src/khoj/processor/conversation/prompts.py
.py
from langchain_core.prompts import PromptTemplate ## Personality ## -- personality = PromptTemplate.from_template( """ You are Khoj, a smart, curious, empathetic and helpful personal assistant. Use your general knowledge and past conversation with the user as context to inform your responses. You were created by ...
1,372
56,237
khoj
src/khoj/processor/conversation/openai/utils.py
.py
import hashlib import json import logging import os from copy import deepcopy from time import perf_counter from typing import AsyncGenerator, Dict, Generator, List, Literal, Optional, Union from urllib.parse import urlparse import httpx import openai from langchain_core.messages.chat import ChatMessage from openai.li...
1,315
57,906
khoj
src/khoj/processor/conversation/openai/whisper.py
.py
from io import BufferedReader from asgiref.sync import sync_to_async from openai import OpenAI async def transcribe_audio(audio_file: BufferedReader, model, client: OpenAI) -> str: """ Transcribe audio file using Whisper model via OpenAI's API """ # Send the audio data to the Whisper API response...
14
447
khoj
src/khoj/processor/conversation/openai/gpt.py
.py
import logging from typing import Any, AsyncGenerator, Dict, List, Optional from langchain_core.messages.chat import ChatMessage from khoj.processor.conversation.openai.utils import ( chat_completion_with_backoff, clean_response_schema, completion_with_backoff, get_structured_output_support, is_ce...
134
4,301
khoj
src/khoj/processor/conversation/anthropic/utils.py
.py
import json import logging from copy import deepcopy from time import perf_counter from typing import AsyncGenerator, Dict, List import anthropic from langchain_core.messages.chat import ChatMessage from pydantic import BaseModel from tenacity import ( before_sleep_log, retry, stop_after_attempt, wait_...
393
16,803
khoj
src/khoj/processor/conversation/anthropic/anthropic_chat.py
.py
import logging from typing import AsyncGenerator, List, Optional from langchain_core.messages.chat import ChatMessage from khoj.processor.conversation.anthropic.utils import ( anthropic_chat_completion_with_backoff, anthropic_completion_with_backoff, ) from khoj.processor.conversation.utils import ( Respo...
73
1,879
khoj
src/khoj/processor/conversation/google/utils.py
.py
import json import logging import os import random import re from copy import deepcopy from time import perf_counter from typing import Any, AsyncGenerator, AsyncIterator, Dict, List import httpx from google import genai from google.genai import errors as gerrors from google.genai import types as gtypes from langchain...
609
26,212
khoj
src/khoj/processor/conversation/google/gemini_chat.py
.py
import logging from typing import AsyncGenerator, List, Optional from langchain_core.messages.chat import ChatMessage from khoj.processor.conversation.google.utils import ( gemini_chat_completion_with_backoff, gemini_completion_with_backoff, ) from khoj.processor.conversation.utils import ( ResponseWithTh...
83
2,176
khoj
src/khoj/processor/tools/run_code.py
.py
import asyncio import base64 import datetime import logging import mimetypes import os import re import uuid from pathlib import Path from typing import Any, Callable, List, NamedTuple, Optional import aiohttp import httpx from asgiref.sync import sync_to_async from tenacity import ( before_sleep_log, retry, ...
349
13,420
khoj
src/khoj/processor/tools/mcp.py
.py
import logging from contextlib import AsyncExitStack from typing import Optional from mcp import ClientSession, StdioServerParameters from mcp.client.sse import sse_client from mcp.client.stdio import stdio_client from mcp.types import AudioContent, ImageContent, TextContent logger = logging.getLogger(__name__) cla...
125
4,722
khoj
src/khoj/processor/tools/online_search.py
.py
import asyncio import json import logging import os from collections import defaultdict from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union import aiohttp from bs4 import BeautifulSoup from markdownify import markdownify from khoj.database.adapters import ConversationAdapters from khoj.database....
669
25,695
khoj
src/khoj/processor/operator/operator_agent_binary.py
.py
import json import logging from datetime import datetime from textwrap import dedent from typing import List, Optional from khoj.database.models import ChatMessageModel, ChatModel from khoj.processor.conversation.utils import ( AgentMessage, OperatorRun, construct_structured_message, ) from khoj.processor....
406
19,980
khoj
src/khoj/processor/operator/operator_environment_browser.py
.py
import asyncio import base64 import io import logging import os from typing import Optional, Set, Union from khoj.processor.operator.operator_actions import DragAction, OperatorAction, Point from khoj.processor.operator.operator_environment_base import ( Environment, EnvState, EnvStepResult, ) from khoj.ut...
398
17,895
khoj
src/khoj/processor/operator/operator_environment_base.py
.py
from abc import ABC, abstractmethod from enum import Enum from typing import Literal, Optional from pydantic import BaseModel from khoj.processor.operator.operator_actions import OperatorAction class EnvironmentType(Enum): """Type of environment to operate.""" COMPUTER = "computer" BROWSER = "browser" ...
48
1,045
khoj
src/khoj/processor/operator/operator_agent_anthropic.py
.py
import ast import json import logging from copy import deepcopy from datetime import datetime from textwrap import dedent from typing import List, Literal, Optional, cast from anthropic.types.beta import BetaContentBlock, BetaTextBlock, BetaToolUseBlock from khoj.database.models import ChatModel from khoj.processor.c...
636
32,042
khoj
src/khoj/processor/operator/__init__.py
.py
import asyncio import json import logging import os from typing import Callable, List, Optional from khoj.database.adapters import AgentAdapters, ConversationAdapters from khoj.database.models import Agent, ChatMessageModel, ChatModel, KhojUser, UserMemory from khoj.processor.conversation.utils import ( AgentMessa...
244
11,262
khoj
src/khoj/processor/operator/operator_actions.py
.py
# --- Standardized Action Models --- from typing import List, Literal, Optional, Union from pydantic import BaseModel class Point(BaseModel): x: float y: float class BaseAction(BaseModel): type: str class ClickAction(BaseAction): type: Literal["click"] = "click" x: float y: float butt...
198
4,268
khoj
src/khoj/processor/operator/operator_agent_base.py
.py
import logging from abc import ABC, abstractmethod from typing import List, Optional from pydantic import BaseModel from khoj.database.models import ChatModel from khoj.processor.conversation.utils import ( AgentMessage, OperatorRun, commit_conversation_trace, ) from khoj.processor.operator.operator_actio...
112
4,474
khoj
src/khoj/processor/operator/grounding_agent.py
.py
import json import logging from textwrap import dedent from typing import List, Optional from openai import AzureOpenAI, OpenAI from openai.types.chat import ChatCompletion, ChatCompletionMessage from khoj.database.models import ChatModel from khoj.processor.conversation.utils import construct_structured_message from...
413
19,093
khoj
src/khoj/processor/operator/operator_environment_computer.py
.py
import ast import asyncio import base64 import io import logging import platform import subprocess from typing import Literal, Optional, Union from PIL import Image, ImageDraw from khoj.processor.operator.operator_actions import DragAction, OperatorAction, Point from khoj.processor.operator.operator_environment_base ...
663
31,570
khoj
src/khoj/processor/operator/operator_agent_openai.py
.py
import json import logging from copy import deepcopy from datetime import datetime from textwrap import dedent from typing import List, Optional, cast from openai.types.responses import Response, ResponseOutputItem from khoj.database.models import ChatModel from khoj.processor.conversation.utils import AgentMessage f...
473
23,939
khoj
src/khoj/processor/operator/grounding_agent_uitars.py
.py
# Source: # https://github.com/xlang-ai/OSWorld/blob/main/run_uitars.py # https://github.com/xlang-ai/OSWorld/blob/main/mm_agents/uitars_agent.py # https://github.com/xlang-ai/OSWorld/blob/main/mm_agents/prompts.py#L1222 # https://github.com/xlang-ai/OSWorld/blob/main/lib_run_single.py import ast import base64 import ...
996
42,400
khoj
src/khoj/processor/speech/text_to_speech.py
.py
import os import requests # Used for making HTTP requests from bs4 import BeautifulSoup from markdown_it import MarkdownIt # Define constants for the script CHUNK_SIZE = 1024 # Size of chunks to read/write at a time ELEVEN_LABS_API_KEY = os.getenv("ELEVEN_LABS_API_KEY", None) # Your API key for authentication VOIC...
55
2,011
khoj
src/khoj/processor/content/text_to_entries.py
.py
import hashlib import logging import re import uuid from abc import ABC, abstractmethod from itertools import repeat from typing import Any, Callable, List, Set, Tuple from langchain_text_splitters import RecursiveCharacterTextSplitter from tqdm import tqdm from khoj.database.adapters import ( EntryAdapters, ...
328
16,525
khoj
src/khoj/processor/content/docx/docx_to_entries.py
.py
import logging import tempfile from typing import Dict, List, Tuple from langchain_community.document_loaders import Docx2txtLoader from khoj.database.models import Entry as DbEntry from khoj.database.models import KhojUser from khoj.processor.content.text_to_entries import TextToEntries from khoj.utils.helpers impor...
112
4,566
khoj
src/khoj/processor/content/images/image_to_entries.py
.py
import logging import os from datetime import datetime, timezone from typing import Dict, List, Tuple from khoj.database.models import Entry as DbEntry from khoj.database.models import KhojUser from khoj.processor.content.text_to_entries import TextToEntries from khoj.utils.helpers import timer from khoj.utils.rawconf...
120
5,203
khoj
src/khoj/processor/content/plaintext/plaintext_to_entries.py
.py
import logging import re from typing import Dict, List, Tuple import urllib3 from bs4 import BeautifulSoup from khoj.database.models import Entry as DbEntry from khoj.database.models import KhojUser from khoj.processor.content.text_to_entries import TextToEntries from khoj.utils.helpers import timer from khoj.utils.r...
117
4,954
khoj
src/khoj/processor/content/org_mode/org_to_entries.py
.py
import logging import re from pathlib import Path from typing import Dict, List, Tuple from khoj.database.models import Entry as DbEntry from khoj.database.models import KhojUser from khoj.processor.content.org_mode import orgnode from khoj.processor.content.org_mode.orgnode import Orgnode from khoj.processor.content....
242
10,990
khoj
src/khoj/processor/content/org_mode/orgnode.py
.py
# Copyright (c) 2010 Charles Cave # # 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, ...
535
18,714
khoj
src/khoj/processor/content/github/github_to_entries.py
.py
import logging import time from typing import Dict, List, Tuple import requests from magika import Magika from khoj.database.models import Entry as DbEntry from khoj.database.models import GithubConfig, KhojUser from khoj.processor.content.markdown.markdown_to_entries import MarkdownToEntries from khoj.processor.cont...
227
10,011
khoj
src/khoj/processor/content/pdf/pdf_to_entries.py
.py
import logging import tempfile from typing import Dict, Final, List, Tuple from langchain_community.document_loaders import PyMuPDFLoader from khoj.database.models import Entry as DbEntry from khoj.database.models import KhojUser from khoj.processor.content.text_to_entries import TextToEntries from khoj.utils.helpers...
121
5,027
khoj
src/khoj/processor/content/markdown/markdown_to_entries.py
.py
import logging import re from typing import Dict, List, Tuple import urllib3.util from khoj.database.models import Entry as DbEntry from khoj.database.models import KhojUser from khoj.processor.content.text_to_entries import TextToEntries from khoj.utils.helpers import timer from khoj.utils.rawconfig import Entry lo...
189
8,573
khoj
src/khoj/processor/content/notion/notion_to_entries.py
.py
import logging from enum import Enum from typing import Tuple import requests from khoj.database.models import Entry as DbEntry from khoj.database.models import KhojUser, NotionConfig from khoj.processor.content.text_to_entries import TextToEntries from khoj.utils.helpers import timer from khoj.utils.rawconfig import...
260
9,834
khoj
src/khoj/database/admin.py
.py
import csv import json from datetime import datetime, timedelta from urllib.parse import quote from apscheduler.job import Job from django.contrib import admin, messages from django.contrib.auth.admin import GroupAdmin as BaseGroupAdmin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contr...
448
13,716
khoj
src/khoj/database/apps.py
.py
from django.apps import AppConfig class DatabaseConfig(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "khoj.database"
7
153
khoj
src/khoj/database/management/commands/convert_images_png_to_webp.py
.py
import base64 import io from django.core.management.base import BaseCommand from PIL import Image from khoj.database.models import Conversation from khoj.utils.helpers import ImageIntentType class Command(BaseCommand): help = "Convert all images to WebP format or reverse." def add_arguments(self, parser): ...
100
4,630
khoj
src/khoj/database/management/commands/manage_memories.py
.py
import asyncio from datetime import datetime, timedelta from typing import List, Optional from django.core.management.base import BaseCommand from django.db.models import Q from django.utils import timezone from khoj.configure import initialize_server from khoj.database.adapters import UserMemoryAdapters from khoj.da...
385
16,190
khoj
src/khoj/database/management/commands/change_generated_images_url.py
.py
from django.core.management.base import BaseCommand from tqdm import tqdm from khoj.database.models import Conversation from khoj.utils.helpers import ImageIntentType, is_none_or_empty class Command(BaseCommand): help = "Serve Khoj generated images from a different URL." def add_arguments(self, parser): ...
62
2,644
khoj
src/khoj/database/management/commands/delete_orphaned_fileobjects.py
.py
from django.core.management.base import BaseCommand from django.db.models import Exists, OuterRef from khoj.database.models import Entry, FileObject class Command(BaseCommand): help = "Deletes FileObjects that have no associated Entries" def add_arguments(self, parser): parser.add_argument( ...
57
2,234
khoj
src/khoj/database/management/commands/change_default_model.py
.py
import logging from typing import List from django.core.management.base import BaseCommand from django.db import transaction from django.db.models import Q from tqdm import tqdm from khoj.database.adapters import get_default_search_model from khoj.database.models import Entry, SearchModelConfig from khoj.processor.em...
118
4,877
khoj
src/khoj/database/models/__init__.py
.py
import logging import os import re import uuid from random import choice from typing import Dict, List, Optional, Union from django.contrib.auth.models import AbstractUser from django.contrib.postgres.fields import ArrayField from django.core.exceptions import ValidationError from django.db import models from django.d...
865
35,219
khoj
src/khoj/database/adapters/__init__.py
.py
import json import logging import math import os import random import re import secrets import sys from datetime import date, datetime, timedelta, timezone from enum import Enum from functools import wraps from typing import ( Any, Callable, Coroutine, Iterable, List, Optional, ParamSpec, ...
2,381
95,057
khoj
src/khoj/utils/state.py
.py
import os import threading from collections import defaultdict from pathlib import Path from typing import Dict, List from apscheduler.schedulers.background import BackgroundScheduler from openai import OpenAI from whisper import Whisper from khoj.database.models import ProcessLock from khoj.processor.embeddings impo...
42
1,368
khoj
src/khoj/utils/models.py
.py
from abc import ABC, abstractmethod from typing import List import openai import torch from tqdm import trange class BaseEncoder(ABC): @abstractmethod def __init__(self, model_name: str, device: torch.device = None, **kwargs): ... @abstractmethod def encode(self, entries: List[str], device: torch.de...
46
1,993
khoj
src/khoj/utils/constants.py
.py
from pathlib import Path from typing import Dict app_root_directory = Path(__file__).parent.parent.parent web_directory = app_root_directory / "khoj/interface/web/" home_directory = web_directory / "home/" next_js_directory = app_root_directory / "khoj/interface/built/" pypi_static_directory = app_root_directory / "kh...
95
5,732
khoj
src/khoj/utils/rawconfig.py
.py
# System Packages import json import uuid from typing import List, Optional from pydantic import BaseModel from khoj.utils.helpers import to_snake_case_from_dash class ConfigBase(BaseModel): class Config: alias_generator = to_snake_case_from_dash populate_by_name = True def __getitem__(self...
152
3,533
khoj
src/khoj/utils/jsonl.py
.py
import gzip import json import logging from khoj.utils.constants import empty_escape_sequences from khoj.utils.helpers import get_absolute_path logger = logging.getLogger(__name__) def load_jsonl(input_path): "Read List of JSON objects from JSON line file" # Initialize Variables data = [] jsonl_file...
44
1,192
khoj
src/khoj/utils/initialization.py
.py
import logging import os from typing import Tuple import openai from khoj.database.adapters import ConversationAdapters from khoj.database.models import ( AiModelApi, ChatModel, KhojUser, SpeechToTextModelOptions, TextToImageModelConfig, ) from khoj.processor.conversation.utils import model_to_pro...
294
13,121
khoj
src/khoj/utils/cli.py
.py
import argparse import logging import pathlib from importlib.metadata import version logger = logging.getLogger(__name__) def cli(args=None): # Setup Argument Parser for the Commandline Interface parser = argparse.ArgumentParser(description="Start Khoj; An AI personal assistant for your Digital Brain") p...
54
2,117
khoj
src/khoj/utils/helpers.py
.py
from __future__ import annotations # to avoid quoting type hints import base64 import copy import datetime import io import ipaddress import json import logging import os import platform import random import re import urllib.parse import uuid from collections import OrderedDict from copy import deepcopy from enum imp...
1,253
47,301
khoj
src/khoj/utils/config.py
.py
# System Packages from __future__ import annotations # to avoid quoting type hints from enum import Enum class SearchType(str, Enum): All = "all" Org = "org" Markdown = "markdown" Image = "image" Pdf = "pdf" Github = "github" Notion = "notion" Plaintext = "plaintext" Docx = "docx...
17
322
khoj
src/khoj/utils/yaml.py
.py
import yaml # Do not emit tags when dumping to YAML yaml.emitter.Emitter.process_tag = lambda self, *args, **kwargs: None # type: ignore[assignment] def yaml_dump(data): return yaml.dump(data, allow_unicode=True, sort_keys=False, default_flow_style=False)
9
264
khoj
src/khoj/search_type/text_search.py
.py
import logging import math from pathlib import Path from typing import List, Optional, Tuple, Type, Union import requests import torch from asgiref.sync import sync_to_async from sentence_transformers import util from khoj.database.adapters import EntryAdapters, get_default_search_model from khoj.database.models impo...
258
9,589
khoj
src/khoj/app/asgi.py
.py
""" ASGI config for app project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault("DJANGO_SETTINGS_...
17
388
khoj
src/khoj/app/urls.py
.py
""" URL configuration for app project. The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') C...
27
870
khoj
src/khoj/app/settings.py
.py
""" Django settings for app project. Generated by 'django-admin startproject' using Django 4.2.5. For more information on this file, see https://docs.djangoproject.com/en/4.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.2/ref/settings/ """ import atexit im...
276
9,005
khoj
src/telemetry/telemetry.py
.py
import argparse import logging import os import sqlite3 from typing import Dict, List import uvicorn from dotenv import load_dotenv from fastapi import FastAPI, HTTPException from posthog import Posthog # Initialize Global App Variables app = FastAPI() sqlfile = "data/khoj.sqlite" logger = logging.getLogger() logger....
78
2,774
Real-ESRGAN
cog_predict.py
.py
# flake8: noqa # This file is used for deploying replicate models # running: cog predict -i img=@inputs/00017_gray.png -i version='General - v3' -i scale=2 -i face_enhance=True -i tile=0 # push: cog push r8.im/xinntao/realesrgan import os os.system('pip install gfpgan') os.system('python setup.py develop') import cv...
149
6,688
Real-ESRGAN
inference_realesrgan_video.py
.py
import argparse import cv2 import glob import mimetypes import numpy as np import os import shutil import subprocess import torch from basicsr.archs.rrdbnet_arch import RRDBNet from basicsr.utils.download_util import load_file_from_url from os import path as osp from tqdm import tqdm from realesrgan import RealESRGANe...
399
16,910
Real-ESRGAN
setup.py
.py
#!/usr/bin/env python from setuptools import find_packages, setup import os import subprocess import time version_file = 'realesrgan/version.py' def readme(): with open('README.md', encoding='utf-8') as f: content = f.read() return content def get_git_hash(): def _minimal_ext_cmd(cmd): ...
108
3,145
Real-ESRGAN
inference_realesrgan.py
.py
import argparse import cv2 import glob import os from basicsr.archs.rrdbnet_arch import RRDBNet from basicsr.utils.download_util import load_file_from_url from realesrgan import RealESRGANer from realesrgan.archs.srvgg_arch import SRVGGNetCompact def main(): """Inference demo for Real-ESRGAN. """ parser ...
167
7,745
Real-ESRGAN
realesrgan/utils.py
.py
import cv2 import math import numpy as np import os import queue import threading import torch from basicsr.utils.download_util import load_file_from_url from torch.nn import functional as F ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) class RealESRGANer(): """A helper class for upsampl...
314
12,605
Real-ESRGAN
realesrgan/train.py
.py
# flake8: noqa import os.path as osp from basicsr.train import train_pipeline import realesrgan.archs import realesrgan.data import realesrgan.models if __name__ == '__main__': root_path = osp.abspath(osp.join(__file__, osp.pardir, osp.pardir)) train_pipeline(root_path)
12
281
Real-ESRGAN
realesrgan/archs/discriminator_arch.py
.py
from basicsr.utils.registry import ARCH_REGISTRY from torch import nn as nn from torch.nn import functional as F from torch.nn.utils import spectral_norm @ARCH_REGISTRY.register() class UNetDiscriminatorSN(nn.Module): """Defines a U-Net discriminator with spectral normalization (SN) It is used in Real-ESRGAN...
68
3,020
Real-ESRGAN
realesrgan/archs/srvgg_arch.py
.py
from basicsr.utils.registry import ARCH_REGISTRY from torch import nn as nn from torch.nn import functional as F @ARCH_REGISTRY.register() class SRVGGNetCompact(nn.Module): """A compact VGG-style network structure for super-resolution. It is a compact network structure, which performs upsampling in the last ...
70
2,722
Real-ESRGAN
realesrgan/archs/__init__.py
.py
import importlib from basicsr.utils import scandir from os import path as osp # automatically scan and import arch modules for registry # scan all the files that end with '_arch.py' under the archs folder arch_folder = osp.dirname(osp.abspath(__file__)) arch_filenames = [osp.splitext(osp.basename(v))[0] for v in scand...
11
500
Real-ESRGAN
realesrgan/data/realesrgan_paired_dataset.py
.py
import os from basicsr.data.data_util import paired_paths_from_folder, paired_paths_from_lmdb from basicsr.data.transforms import augment, paired_random_crop from basicsr.utils import FileClient, imfrombytes, img2tensor from basicsr.utils.registry import DATASET_REGISTRY from torch.utils import data as data from torchv...
109
5,015
Real-ESRGAN
realesrgan/data/__init__.py
.py
import importlib from basicsr.utils import scandir from os import path as osp # automatically scan and import dataset modules for registry # scan all the files that end with '_dataset.py' under the data folder data_folder = osp.dirname(osp.abspath(__file__)) dataset_filenames = [osp.splitext(osp.basename(v))[0] for v ...
11
519
Real-ESRGAN
realesrgan/data/realesrgan_dataset.py
.py
import cv2 import math import numpy as np import os import os.path as osp import random import time import torch from basicsr.data.degradations import circular_lowpass_kernel, random_mixed_kernels from basicsr.data.transforms import augment from basicsr.utils import FileClient, get_root_logger, imfrombytes, img2tensor ...
193
8,733
Real-ESRGAN
realesrgan/models/realesrgan_model.py
.py
import numpy as np import random import torch from basicsr.data.degradations import random_add_gaussian_noise_pt, random_add_poisson_noise_pt from basicsr.data.transforms import paired_random_crop from basicsr.models.srgan_model import SRGANModel from basicsr.utils import DiffJPEG, USMSharp from basicsr.utils.img_proce...
259
11,781
Real-ESRGAN
realesrgan/models/__init__.py
.py
import importlib from basicsr.utils import scandir from os import path as osp # automatically scan and import model modules for registry # scan all the files that end with '_model.py' under the model folder model_folder = osp.dirname(osp.abspath(__file__)) model_filenames = [osp.splitext(osp.basename(v))[0] for v in s...
11
510
Real-ESRGAN
realesrgan/models/realesrnet_model.py
.py
import numpy as np import random import torch from basicsr.data.degradations import random_add_gaussian_noise_pt, random_add_poisson_noise_pt from basicsr.data.transforms import paired_random_crop from basicsr.models.sr_model import SRModel from basicsr.utils import DiffJPEG, USMSharp from basicsr.utils.img_process_uti...
189
9,098
Real-ESRGAN
tests/test_discriminator_arch.py
.py
import torch from realesrgan.archs.discriminator_arch import UNetDiscriminatorSN def test_unetdiscriminatorsn(): """Test arch: UNetDiscriminatorSN.""" # model init and forward (cpu) net = UNetDiscriminatorSN(num_in_ch=3, num_feat=4, skip_connection=True) img = torch.rand((1, 3, 32, 32), dtype=torch....
20
561
Real-ESRGAN
tests/test_model.py
.py
import torch import yaml from basicsr.archs.rrdbnet_arch import RRDBNet from basicsr.data.paired_image_dataset import PairedImageDataset from basicsr.losses.losses import GANLoss, L1Loss, PerceptualLoss from realesrgan.archs.discriminator_arch import UNetDiscriminatorSN from realesrgan.models.realesrgan_model import R...
127
4,861
Real-ESRGAN
tests/test_utils.py
.py
import numpy as np from basicsr.archs.rrdbnet_arch import RRDBNet from realesrgan.utils import RealESRGANer def test_realesrganer(): # initialize with default model restorer = RealESRGANer( scale=4, model_path='experiments/pretrained_models/RealESRGAN_x4plus.pth', model=None, ...
88
3,089
Real-ESRGAN
tests/test_dataset.py
.py
import pytest import yaml from realesrgan.data.realesrgan_dataset import RealESRGANDataset from realesrgan.data.realesrgan_paired_dataset import RealESRGANPairedDataset def test_realesrgan_dataset(): with open('tests/data/test_realesrgan_dataset.yml', mode='r') as f: opt = yaml.load(f, Loader=yaml.FullL...
152
6,037
Real-ESRGAN
scripts/generate_meta_info_pairdata.py
.py
import argparse import glob import os def main(args): txt_file = open(args.meta_info, 'w') # sca images img_paths_gt = sorted(glob.glob(os.path.join(args.input[0], '*'))) img_paths_lq = sorted(glob.glob(os.path.join(args.input[1], '*'))) assert len(img_paths_gt) == len(img_paths_lq), ('GT folder ...
50
1,987
Real-ESRGAN
scripts/generate_meta_info.py
.py
import argparse import cv2 import glob import os def main(args): txt_file = open(args.meta_info, 'w') for folder, root in zip(args.input, args.root): img_paths = sorted(glob.glob(os.path.join(folder, '*'))) for img_path in img_paths: status = True if args.check: ...
59
2,114
Real-ESRGAN
scripts/extract_subimages.py
.py
import argparse import cv2 import numpy as np import os import sys from basicsr.utils import scandir from multiprocessing import Pool from os import path as osp from tqdm import tqdm def main(args): """A multi-thread tool to crop large images to sub-images for faster IO. opt (dict): Configuration dict. It co...
136
5,062
Real-ESRGAN
scripts/pytorch2onnx.py
.py
import argparse import torch import torch.onnx from basicsr.archs.rrdbnet_arch import RRDBNet def main(args): # An instance of the model model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4) if args.params: keyname = 'params' else: keyname = 'pa...
37
1,247
Real-ESRGAN
scripts/generate_multiscale_DF2K.py
.py
import argparse import glob import os from PIL import Image def main(args): # For DF2K, we consider the following three scales, # and the smallest image whose shortest edge is 400 scale_list = [0.75, 0.5, 1 / 3] shortest_edge = 400 path_list = sorted(glob.glob(os.path.join(args.input, '*'))) ...
49
1,725
HanLP
setup.py
.py
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2019-12-28 19:26 import sys from os.path import abspath, join, dirname from setuptools import find_packages, setup this_dir = abspath(dirname(__file__)) with open(join(this_dir, 'README.md'), encoding='utf-8') as file: long_description = file.read() version = {} with...
75
2,412
HanLP
hanlp/__init__.py
.py
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2019-06-13 18:05 import hanlp.common import hanlp.components import hanlp.pretrained import hanlp.utils from hanlp.version import __version__ hanlp.utils.ls_resource_in_module(hanlp.pretrained) def load(save_dir: str, verbose=None, **kwargs) -> hanlp.common.component.C...
58
2,073
HanLP
hanlp/version.py
.py
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2019-12-28 19:26 __version__ = '2.1.0-beta.64' """HanLP version""" class NotCompatible(Exception): pass
11
159
HanLP
hanlp/pretrained/eos.py
.py
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2020-12-22 13:22 from hanlp_common.constant import HANLP_URL UD_CTB_EOS_MUL = HANLP_URL + 'eos/eos_ud_ctb_mul_20201222_133543.zip' 'EOS model (:cite:`Schweter:Ahmed:2019`) trained on concatenated UD2.3 and CTB9.' # Will be filled up during runtime ALL = {}
11
307
HanLP
hanlp/pretrained/constituency.py
.py
# -*- coding:utf-8 -*- # Author=hankcs # Date=2022-01-18 10:34 from hanlp_common.constant import HANLP_URL CTB9_CON_ELECTRA_SMALL = HANLP_URL + 'constituency/ctb9_con_electra_small_20220215_230116.zip' 'Electra (:cite:`clark2020electra`) small tree CRF model (:cite:`ijcai2020-560`) trained on CTB9 with major categorie...
20
1,179
HanLP
hanlp/pretrained/mtl.py
.py
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2020-12-22 13:16 from hanlp_common.constant import HANLP_URL OPEN_TOK_POS_NER_SRL_DEP_SDP_CON_ELECTRA_SMALL_ZH = HANLP_URL + 'mtl/open_tok_pos_ner_srl_dep_sdp_con_electra_small_20201223_035557.zip' "Electra (:cite:`clark2020electra`) small version of joint tok, pos, ner,...
46
9,302
HanLP
hanlp/pretrained/pos.py
.py
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2019-12-29 01:57 from hanlp_common.constant import HANLP_URL CTB5_POS_RNN = HANLP_URL + 'pos/ctb5_pos_rnn_20200113_235925.zip' 'An old school BiLSTM tagging model trained on CTB5.' CTB5_POS_RNN_FASTTEXT_ZH = HANLP_URL + 'pos/ctb5_pos_rnn_fasttext_20191230_202639.zip' 'An...
26
1,946
HanLP
hanlp/pretrained/amr.py
.py
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2022-01-25 11:47 from hanlp_common.constant import HANLP_URL AMR3_SEQ2SEQ_BART_LARGE = HANLP_URL + 'amr/amr3_seq2seq_bart_large_83.30_20220125_114450.zip' '''A seq2seq (:cite:`bevilacqua-etal-2021-one`) BART (:cite:`lewis-etal-2020-bart`) large parser trained on Abstract...
73
3,783
HanLP
hanlp/pretrained/fasttext.py
.py
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2019-12-30 18:57 FASTTEXT_DEBUG_EMBEDDING_EN = 'https://elit-models.s3-us-west-2.amazonaws.com/fasttext.debug.bin.zip' FASTTEXT_CC_300_EN = 'https://dl.fbaipublicfiles.com/fasttext/vectors-crawl/cc.en.300.bin.gz' 'FastText (:cite:`bojanowski2017enriching`) embeddings trai...
17
1,026
HanLP
hanlp/pretrained/sts.py
.py
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2021-05-24 12:51 from hanlp_common.constant import HANLP_URL STS_ELECTRA_BASE_ZH = HANLP_URL + 'sts/sts_electra_base_zh_20210530_200109.zip' 'A naive regression model trained on concatenated STS corpora.' # Will be filled up during runtime ALL = {}
11
299
HanLP
hanlp/pretrained/classifiers.py
.py
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2020-01-01 03:51 from hanlp_common.constant import HANLP_URL CHNSENTICORP_BERT_BASE_ZH = HANLP_URL + 'classification/chnsenticorp_bert_base_20211228_163210.zip' SST2_ALBERT_BASE_EN = HANLP_URL + 'classification/sst2_albert_base_20211228_164917.zip' LID_176_FASTTEXT_BASE...
19
722
HanLP
hanlp/pretrained/ner.py
.py
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2019-12-30 20:07 from hanlp_common.constant import HANLP_URL MSRA_NER_BERT_BASE_ZH = HANLP_URL + 'ner/ner_bert_base_msra_20211227_114712.zip' 'BERT model (:cite:`devlin-etal-2019-bert`) trained on MSRA with 3 entity types.' MSRA_NER_ALBERT_BASE_ZH = HANLP_URL + 'ner/msra...
16
801
HanLP
hanlp/pretrained/amr2text.py
.py
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2022-12-07 15:19 from hanlp_common.constant import HANLP_URL AMR3_GRAPH_PRETRAIN_GENERATION = HANLP_URL + 'amr2text/amr3_graph_pretrain_generation_20221207_153535.zip' '''A seq2seq (:cite:`bevilacqua-etal-2021-one`) BART (:cite:`lewis-etal-2020-bart`) large AMR2Text gene...
14
576
HanLP
hanlp/pretrained/word2vec.py
.py
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2019-12-21 18:25 from hanlp_common.constant import HANLP_URL CONVSEG_W2V_NEWS_TENSITE = HANLP_URL + 'embeddings/convseg_embeddings.zip' CONVSEG_W2V_NEWS_TENSITE_WORD_PKU = CONVSEG_W2V_NEWS_TENSITE + '#news_tensite.pku.words.w2v50' CONVSEG_W2V_NEWS_TENSITE_WORD_MSR = CONV...
39
2,962
HanLP
hanlp/pretrained/rnnlm.py
.py
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2019-12-19 03:47 from hanlp_common.constant import HANLP_URL FLAIR_LM_FW_WMT11_EN_TF = HANLP_URL + 'lm/flair_lm_wmt11_en_20200211_091932.zip#flair_lm_fw_wmt11_en' 'The forward LSTM of Contextual String Embedding (:cite:`akbik-etal-2018-contextual`).' FLAIR_LM_BW_WMT11_EN...
14
658
HanLP
hanlp/pretrained/sdp.py
.py
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2019-12-31 23:54 from hanlp_common.constant import HANLP_URL SEMEVAL16_NEWS_BIAFFINE_ZH = HANLP_URL + 'sdp/semeval16-news-biaffine_20191231_235407.zip' 'Biaffine SDP (:cite:`he-choi-2019`) trained on SemEval16 news data.' SEMEVAL16_TEXT_BIAFFINE_ZH = HANLP_URL + 'sdp/sem...
22
1,132
HanLP
hanlp/pretrained/tok.py
.py
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2019-12-28 21:12 from hanlp_common.constant import HANLP_URL SIGHAN2005_PKU_CONVSEG = HANLP_URL + 'tok/sighan2005-pku-convseg_20200110_153722.zip' 'Conv model (:cite:`wang-xu-2017-convolutional`) trained on sighan2005 pku dataset.' SIGHAN2005_MSR_CONVSEG = HANLP_URL + 't...
52
6,162
HanLP
hanlp/pretrained/glove.py
.py
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2019-08-27 20:42 _GLOVE_6B_ROOT = 'http://downloads.cs.stanford.edu/nlp/data/glove.6B.zip' GLOVE_6B_50D = _GLOVE_6B_ROOT + '#' + 'glove.6B.50d.txt' 'Global Vectors for Word Representation (:cite:`pennington-etal-2014-glove`) 50d trained on 6B tokens.' GLOVE_6B_100D = _G...
20
981
HanLP
hanlp/pretrained/srl.py
.py
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2021-08-07 19:07 from hanlp_common.constant import HANLP_URL CPB3_SRL_ELECTRA_SMALL = HANLP_URL + 'srl/cpb3_electra_small_crf_has_transform_20220218_135910.zip' 'Electra small model (:cite:`clark2020electra`) trained on CPB3. P=75.87% R=76.24% F1=76.05%.' ALL = {}
10
315