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
maigret
maigret/submit.py
.py
import asyncio import json import re import os import logging from typing import Any, Dict, List, Optional, Tuple from urllib.parse import urlparse from aiohttp import ClientSession, TCPConnector from colorama import Fore, Style from .activation import import_aiohttp_cookies from .result import MaigretCheckResult fro...
632
23,783
maigret
maigret/error_detection.py
.py
from typing import Dict, Optional from maigret import errors from maigret.errors import CheckError def detect_error_page( html_text: str, status_code: int, fail_flags: Optional[Dict[str, str]] = None, ignore_403: bool = False, ) -> Optional[CheckError]: """Classify a response as an error conditio...
37
1,186
maigret
maigret/errors.py
.py
from typing import Dict, List, Any, Tuple from .result import MaigretCheckResult, SiteResult # error got as a result of completed search query class CheckError: _type = 'Unknown' _desc = '' def __init__(self, typename, desc=''): self._type = typename self._desc = desc def __str__(se...
244
9,377
maigret
maigret/utils.py
.py
# coding: utf8 import ast import difflib import re import random import string from typing import Any from markupsafe import Markup, escape DEFAULT_USER_AGENTS = [ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36", ] class CaseConverter: @stat...
197
6,239
maigret
maigret/db_updater.py
.py
""" Database auto-update logic for maigret. Checks a lightweight meta file to determine if a newer site database is available, downloads it if compatible, and caches it locally in ~/.maigret/. """ import hashlib import json import logging import os import os.path as path import tempfile from datetime import datetime,...
336
10,671
maigret
maigret/sites.py
.py
# ****************************** -*- """Maigret Sites Information""" import copy import json import logging import sys from typing import Optional, List, Dict, Any, Tuple from .utils import CaseConverter, URLMatcher, is_country_tag logger = logging.getLogger(__name__) class MaigretEngine: site: Dict[str, Any] ...
733
25,892
maigret
maigret/executors.py
.py
import asyncio import time from typing import Any, Iterable, Callable class AsyncioQueueGeneratorExecutor: def __init__(self, *args, **kwargs): self.workers_count = kwargs.get('in_parallel', 10) self.queue: asyncio.Queue = asyncio.Queue() self.timeout = kwargs.get('timeout') self.l...
113
5,068
maigret
maigret/permutator.py
.py
# License MIT. by balestek https://github.com/balestek from itertools import permutations class Permute: def __init__(self, elements: dict): self.separators = ["", "_", "-", "."] self.elements = elements def gather(self, method: str = "strict" or "all") -> dict: permutations_dict = {}...
27
1,201
maigret
maigret/notify.py
.py
"""Console and query notification helpers. This module defines objects for notifying the caller about the results of queries. """ import sys from colorama import Fore, Style, init from .result import MaigretCheckStatus, KeywordMatchStatus from .utils import get_dict_ascii_tree class QueryNotifyPrint: """Query...
308
10,246
maigret
maigret/__main__.py
.py
#! /usr/bin/env python3 """ Maigret entrypoint """ import asyncio import sys from .maigret import main if __name__ == "__main__": # First Ctrl+C is caught inside main() (search loop → falls through to # report generation with partial results). A *second* Ctrl+C during # report generation, or any uncaugh...
23
640
maigret
maigret/__init__.py
.py
"""Maigret""" __title__ = 'Maigret' __package__ = 'maigret' __author__ = 'Soxoj' __author_email__ = 'soxoj@protonmail.com' from .__version__ import __version__ try: from .checking import maigret as search except ImportError as e: raise ImportError( "Missing required dependency while starting Maigret....
25
721
maigret
maigret/activation.py
.py
import json import os import os.path as path import re from http.cookiejar import MozillaCookieJar from http.cookies import Morsel from typing import Dict from aiohttp import ClientSession, CookieJar from .db_updater import MAIGRET_HOME class ParsingActivator: @staticmethod async def twitter(site, logger, c...
275
10,786
maigret
maigret/result.py
.py
"""Maigret Result Module This module defines various objects for recording the results of queries. """ import asyncio from enum import Enum from typing import TYPE_CHECKING, Any, Dict, List, Optional, TypedDict if TYPE_CHECKING: from aiohttp import CookieJar from .sites import MaigretSite class KeywordMatch...
191
6,085
maigret
maigret/__version__.py
.py
"""Maigret version file""" __version__ = '0.6.4'
4
50
maigret
maigret/ai.py
.py
"""Maigret AI Analysis Module Provides AI-powered analysis of search results using OpenAI-compatible APIs. """ import asyncio import json import os import sys import threading import aiohttp def load_ai_prompt() -> str: """Load the AI system prompt from the resources directory.""" maigret_path = os.path.di...
163
4,805
maigret
maigret/settings.py
.py
import os import os.path as path import json from typing import List SETTINGS_FILES_PATHS = [ path.join(path.dirname(path.realpath(__file__)), "resources/settings.json"), # System-wide policy. Lets an administrator or a distribution package # configure Maigret without editing inside the installed package, ...
97
2,530
maigret
maigret/checking.py
.py
# Standard library imports import ast import asyncio import logging import os import random import re import ssl import sys from typing import Any, Dict, List, Optional, Tuple from unittest.mock import Mock from urllib.parse import quote, urlparse # Third party imports import aiodns from alive_progress import alive_ba...
1,919
74,271
maigret
maigret/maigret.py
.py
""" Maigret main module """ import asyncio import logging import os import sys import platform import re from argparse import ArgumentParser, RawDescriptionHelpFormatter from typing import Any, Dict, List, Tuple import os.path as path from maigret.utils import extract_usernames try: from socid_extractor import ex...
1,156
39,966
maigret
maigret/report.py
.py
import ast import csv import io import ipaddress import json import logging import os import socket import tempfile import zipfile from datetime import datetime from typing import Dict, Any from urllib.parse import urlparse from xml.etree import ElementTree import xmind # type: ignore[import-untyped] from dateutil.tz...
995
35,375
maigret
maigret/web/app.py
.py
from flask import ( Flask, render_template, request, send_from_directory, Response, flash, redirect, url_for, ) from werkzeug.exceptions import NotFound import logging import os import asyncio import json import queue import uuid from datetime import datetime from threading import Thread...
715
24,317
500-AI-Agents-Projects
crewai_mcp_course/lesson_01/agent.py
.py
""" Lesson 01: Your First CrewAI Agent Demonstrates the fundamentals of CrewAI: - Creating agents with roles, goals, and backstories - Defining tasks - Running a simple crew Run: python agent.py """ from crewai import Agent, Crew, Process, Task from langchain_openai import ChatOpenAI llm = ChatOpenAI(model="gpt-4o-...
58
1,511
500-AI-Agents-Projects
crewai_mcp_course/lesson_03/mcp_server.py
.py
""" FastMCP Server for Lesson 03. Exposes tools that CrewAI agents can call via the MCP protocol. This is the server side — agents connect to this to use the tools. Run: python mcp_server.py (Keep this running while agent.py is running) """ import json from datetime import datetime try: from fastmcp import Fast...
96
2,812
500-AI-Agents-Projects
crewai_mcp_course/lesson_03/agent.py
.py
""" Lesson 03: CrewAI + FastMCP Integration Demonstrates: - Building a FastMCP server that exposes tools - Mirroring MCP server tools as CrewAI BaseTool wrappers - Production pattern: keep tool contracts stable between MCP server and CrewAI wrappers Architecture: MCP Server tool contracts → CrewAI tool wrappers →...
146
4,661
500-AI-Agents-Projects
crewai_mcp_course/lesson_02/agent.py
.py
""" Lesson 02: Multi-Agent Crew with Tool Use Demonstrates: - Multiple specialized agents with different roles - Custom tools (web search, calculator) - Sequential and hierarchical processes - Agent collaboration patterns Run: python agent.py --topic "quantum computing applications" """ import argparse import os fr...
146
4,403
500-AI-Agents-Projects
agents/14-social-media-agent/agent.py
.py
""" Social Media Content Agent using CrewAI. Generates platform-optimized content (Twitter/X, LinkedIn, Instagram) from a topic or article URL. Usage: python agent.py --topic "The rise of AI agents in 2025" python agent.py --topic "New product launch: CloudSync Pro v3" --brand "CloudSync" """ import argparse...
96
3,203
500-AI-Agents-Projects
agents/12-travel-planner-agent/agent.py
.py
""" Travel Planner Agent using CrewAI. Multi-agent crew that creates personalized travel itineraries: - Destination Researcher: gathers destination info - Activity Planner: creates day-by-day activities - Budget Analyst: estimates costs Usage: python agent.py --destination "Tokyo, Japan" --days 5 --budget 2000 ""...
107
3,889
500-AI-Agents-Projects
agents/08-data-analysis-agent/agent.py
.py
""" Data Analysis Agent using LangChain + pandas. Loads a CSV/Excel file and answers analytical questions about it using natural language. The agent generates Python/pandas code to answer questions. Usage: python agent.py --file data.csv python agent.py --file sales.xlsx --question "What is the monthly revenu...
107
3,689
500-AI-Agents-Projects
agents/19-competitive-analysis-agent/agent.py
.py
""" Competitive Analysis Agent using LangGraph. Multi-step agent that analyzes competitors: 1. Identifies key competitors 2. Analyzes each competitor's strengths/weaknesses 3. Generates competitive positioning recommendations Usage: python agent.py --company "Notion" --industry "productivity software" """ import...
119
4,181
500-AI-Agents-Projects
agents/10-meeting-notes-agent/agent.py
.py
""" Meeting Notes Agent. Converts meeting transcript text into structured meeting notes: summary, action items, decisions, and follow-ups. Usage: python agent.py --transcript meeting.txt python agent.py --text "John: Let's ship v2 next Friday..." """ import argparse import json import os import re from datet...
153
5,337
500-AI-Agents-Projects
agents/13-customer-support-agent/agent.py
.py
""" Customer Support Agent using LangGraph with RAG. Handles customer queries using a knowledge base (product docs). Routes complex issues to human escalation. Usage: python agent.py python agent.py --kb-dir docs/ # load custom knowledge base """ import argparse import os from pathlib import Path fr...
158
6,122
500-AI-Agents-Projects
agents/21-pii-sanitization-agent/agent.py
.py
""" PII Sanitization Agent — client for the TrustBoost API. Removes sensitive data (emails, phones, national IDs, bank accounts, API keys) from text before it reaches an LLM or external API. Built for autonomous agent pipelines where human review is not possible. This is a thin client: the sanitization logic, models,...
115
3,754
500-AI-Agents-Projects
agents/04-sql-query-agent/agent.py
.py
""" SQL Query Agent using LangChain. Connects to a SQLite database and answers natural language questions by generating and executing SQL queries. Usage: python agent.py # uses demo database python agent.py --db path/to/db.sqlite # your database python agent.py --db mydb.sqlite ...
131
4,781
500-AI-Agents-Projects
agents/20-multi-agent-debate/agent.py
.py
""" Multi-Agent Debate System using AutoGen-style orchestration. Two AI agents debate a topic from opposing sides, moderated by a judge who declares a winner and synthesizes the key arguments. Usage: python agent.py --topic "AI will eliminate more jobs than it creates" python agent.py --topic "Remote work is ...
131
4,292
500-AI-Agents-Projects
agents/03-pdf-qa-agent/agent.py
.py
""" PDF Q&A Agent using LlamaIndex. Loads a PDF, indexes it, and answers questions about its content. Maintains conversation history for follow-up questions. Usage: python agent.py --pdf path/to/document.pdf python agent.py --pdf report.pdf --question "What is the main finding?" """ import argparse import os...
80
2,341
500-AI-Agents-Projects
agents/16-documentation-writer/agent.py
.py
""" Documentation Writer Agent. Generates comprehensive documentation for Python modules: README, API reference, docstrings, and usage examples. Usage: python agent.py --file path/to/module.py python agent.py --file src/utils.py --format readme """ import argparse import ast import os from dotenv import loa...
196
6,464
500-AI-Agents-Projects
agents/02-code-review-agent/agent.py
.py
""" Code Review Agent using LangChain. Reviews Python code for bugs, security issues, style violations, and suggests improvements. Accepts a file path or inline code snippet. Usage: python agent.py --file path/to/code.py python agent.py --code "def add(a,b): return a+b" """ import argparse import os from do...
68
2,214
500-AI-Agents-Projects
agents/11-stock-research-agent/agent.py
.py
""" Stock Research Agent using Agno + Yahoo Finance. Provides comprehensive stock analysis: price data, financials, analyst ratings, and AI-powered investment summary. Usage: python agent.py --ticker AAPL python agent.py --ticker NVDA """ import argparse import os from dotenv import load_dotenv load_dotenv...
110
3,745
500-AI-Agents-Projects
agents/09-resume-parser-agent/agent.py
.py
""" Resume Parser Agent using LangChain. Extracts structured information from resume text or PDF: contact info, skills, experience, education, and provides a candidate summary and fit score for a job description. Usage: python agent.py --resume resume.txt python agent.py --resume resume.pdf --job-desc "Senior...
175
5,994
500-AI-Agents-Projects
agents/18-job-application-agent/agent.py
.py
""" Job Application Agent using CrewAI. Analyzes a job description and a candidate profile, then generates: - Tailored cover letter - Resume bullet points to highlight - Interview preparation questions Usage: python agent.py --job-desc "Senior Python Engineer at Stripe..." --candidate "7 years Python, FastAPI..."...
122
3,973
500-AI-Agents-Projects
agents/01-web-research-agent/agent.py
.py
""" Web Research Agent using LangGraph + Tavily Search. Searches the web for a given topic, synthesizes findings, and returns a structured research report. Usage: python agent.py python agent.py --query "latest advances in quantum computing" """ import argparse import os from typing import Annotated, TypedDi...
90
2,701
500-AI-Agents-Projects
agents/07-github-issue-triager/agent.py
.py
""" GitHub Issue Triager using LangGraph. Analyzes a GitHub issue and produces: severity label, category, reproduction steps summary, and suggested assignee type. Usage: python agent.py --title "Login fails on mobile Safari" --body "When I try..." python agent.py --issue-url https://github.com/owner/repo/issu...
122
4,244
500-AI-Agents-Projects
agents/15-unit-test-generator/agent.py
.py
""" Unit Test Generator Agent. Analyzes Python code and generates comprehensive pytest test suites covering happy paths, edge cases, and error conditions. Usage: python agent.py --file path/to/module.py python agent.py --code "def calculate_bmi(weight, height): return weight / height**2" """ import argparse ...
129
4,258
500-AI-Agents-Projects
agents/17-recipe-agent/agent.py
.py
""" Recipe Recommendation Agent using Agno-style single agent. Suggests recipes based on available ingredients, dietary restrictions, and time constraints. Usage: python agent.py --ingredients "chicken, garlic, lemon, rosemary" python agent.py --ingredients "tofu, broccoli, soy sauce" --diet vegan --time 20 "...
126
4,605
500-AI-Agents-Projects
agents/05-email-drafting-agent/agent.py
.py
""" Email Drafting Agent using CrewAI. A two-agent crew that drafts professional emails: - Analyst agent: understands context and tone requirements - Writer agent: drafts the final email Usage: python agent.py python agent.py --context "Follow up on the Q3 proposal sent last week" --tone "professional" """ i...
92
2,930
500-AI-Agents-Projects
agents/06-news-summarizer-agent/agent.py
.py
""" News Summarizer Agent using AutoGen. Fetches news articles and produces structured summaries with key insights. Usage: python agent.py --topic "artificial intelligence" python agent.py --topic "climate change" --count 5 """ import argparse import os import requests from dotenv import load_dotenv from la...
76
2,838
khoj
gunicorn-config.py
.py
import os bind = "0.0.0.0:42110" # Worker Configuration workers = int(os.environ.get("GUNICORN_WORKERS", 6)) worker_class = "uvicorn.workers.UvicornWorker" # Worker Timeout Configuration timeout = int(os.environ.get("GUNICORN_TIMEOUT", 180)) graceful_timeout = int(os.environ.get("GUNICORN_GRACEFUL_TIMEOUT", 90)) kee...
18
452
khoj
tests/test_online_chat_actors.py
.py
import os from datetime import datetime import freezegun import pytest from freezegun import freeze_time from khoj.database.models import ChatMessageModel from khoj.processor.conversation.openai.gpt import converse_openai from khoj.processor.conversation.utils import message_to_log from khoj.routers.helpers import ( ...
759
29,184
khoj
tests/test_date_filter.py
.py
import re from datetime import datetime import pytest from khoj.search_filter.date_filter import DateFilter @pytest.mark.filterwarnings("ignore:The localize method is no longer necessary.") def test_extract_date_range(): assert DateFilter().extract_date_range('head dt>"1984-01-04" dt<"1984-01-07" tail') == [ ...
217
9,666
khoj
tests/test_text_search.py
.py
# System Packages import asyncio import logging import os import pytest from khoj.database.adapters import EntryAdapters from khoj.database.models import Entry, GithubConfig, KhojUser from khoj.processor.content.github.github_to_entries import GithubToEntries from khoj.processor.content.org_mode.org_to_entries import...
409
16,314
khoj
tests/test_client.py
.py
# Standard Modules import os from urllib.parse import quote import pytest from fastapi import FastAPI from fastapi.testclient import TestClient from khoj.configure import configure_routes, configure_search_types from khoj.database.adapters import EntryAdapters from khoj.database.models import KhojApiUser, KhojUser fr...
511
18,912
khoj
tests/test_memory_settings.py
.py
""" Tests for memory enable/disable settings and memory scoping by user+agent. These tests verify: 1. The behavior of ConversationAdapters.is_memory_enabled() for different combinations of: - ServerChatSettings.memory_mode (DISABLED, ENABLED_DEFAULT_OFF, ENABLED_DEFAULT_ON) - UserConversationConfig.enable_memory...
480
18,608
khoj
tests/test_org_to_entries.py
.py
import os import re import time from khoj.processor.content.org_mode.org_to_entries import OrgToEntries from khoj.processor.content.text_to_entries import TextToEntries from khoj.utils.helpers import is_none_or_empty from khoj.utils.rawconfig import Entry def test_configure_indexing_heading_only_entries(tmp_path): ...
423
12,446
khoj
tests/test_markdown_to_entries.py
.py
import os import re from pathlib import Path from khoj.processor.content.markdown.markdown_to_entries import MarkdownToEntries def test_extract_markdown_with_no_headings(tmp_path): "Convert markdown file with no heading to entry format." # Arrange entry = """ - Bullet point 1 - Bullet point 2 ...
279
8,853
khoj
tests/test_pdf_to_entries.py
.py
import os import re import pytest from khoj.processor.content.pdf.pdf_to_entries import PdfToEntries def test_single_page_pdf_to_jsonl(): "Convert single page PDF file to jsonl." # Act # Extract Entries from specified Pdf files # Read singlepage.pdf into memory as bytes with open("tests/data/pdf...
69
2,015
khoj
tests/test_conversation_export.py
.py
import json import pytest from khoj.database.adapters import ConversationAdapters from khoj.database.models import Conversation EXPORT_BATCH_SIZE = 10 def export_all_conversations(user, limit=EXPORT_BATCH_SIZE): """Walk the export adapter the way the web client's export loop does. Pages until a page short...
100
4,559
khoj
tests/test_docx_to_entries.py
.py
from khoj.processor.content.docx.docx_to_entries import DocxToEntries def test_single_page_docx_to_jsonl(): "Convert single page DOCX file to jsonl." # Act # Extract Entries from specified Docx files # Read singlepage.docx into memory as bytes with open("tests/data/docx/iceland.docx", "rb") as f: ...
36
1,183
khoj
tests/test_online_chat_director.py
.py
import os import urllib.parse import pytest from freezegun import freeze_time from khoj.database.models import Agent, Entry, KhojUser from khoj.processor.conversation import prompts from tests.helpers import ConversationFactory, generate_chat_history, get_chat_api_key # Initialize variables for tests api_key = get_c...
696
28,572
khoj
tests/test_api_automation.py
.py
import pytest from apscheduler.schedulers.background import BackgroundScheduler from django_apscheduler.jobstores import DjangoJobStore from fastapi.testclient import TestClient from khoj.utils import state from tests.helpers import AiModelApiFactory, ChatModelFactory, get_chat_api_key @pytest.fixture(autouse=True) ...
136
4,687
khoj
tests/test_image_to_entries.py
.py
from khoj.processor.content.images.image_to_entries import ImageToEntries def test_png_to_jsonl(): with open("tests/data/images/testocr.png", "rb") as f: image_bytes = f.read() data = {"tests/data/images/testocr.png": image_bytes} entries = ImageToEntries.extract_image_entries(image_files=data) ...
20
712
khoj
tests/test_multiple_users.py
.py
# Standard Modules from urllib.parse import quote import pytest from khoj.database.models import KhojApiUser, KhojUser from khoj.processor.content.org_mode.org_to_entries import OrgToEntries from khoj.search_type import text_search # ----------------------------------------------------------------------------------...
99
4,534
khoj
tests/test_word_filter.py
.py
# Application Packages from khoj.search_filter.word_filter import WordFilter # Mock Entry class for testing class Entry: def __init__(self, compiled="", raw=""): self.compiled = compiled self.raw = raw # Test # -------------------------------------------------------------------------------------...
91
2,547
khoj
tests/test_file_filter.py
.py
# Application Packages from khoj.search_filter.file_filter import FileFilter # Mock Entry class for testing class Entry: def __init__(self, compiled="", raw="", file=""): self.compiled = compiled self.raw = raw self.file = file def test_can_filter_no_file_filter(): # Arrange file...
144
3,477
khoj
tests/test_grep_files.py
.py
# System Packages import pytest import logging from khoj.database.adapters import FileObjectAdapters from khoj.database.models import KhojUser from khoj.routers.helpers import grep_files logger = logging.getLogger(__name__) @pytest.fixture def default_user(): user, _ = KhojUser.objects.get_or_create( us...
274
8,575
khoj
tests/test_agents.py
.py
# tests/test_agents.py import asyncio from collections import Counter import pytest from asgiref.sync import sync_to_async from khoj.database.adapters import AgentAdapters from khoj.database.models import Agent, ChatModel, Entry, FileObject, KhojUser from khoj.routers.helpers import execute_search from khoj.utils.hel...
405
14,934
khoj
tests/test_db_lock.py
.py
import time import pytest from khoj.database.adapters import ProcessLockAdapters from khoj.database.models import ProcessLock from tests.helpers import ProcessLockFactory @pytest.mark.django_db(transaction=True) def test_process_lock(default_process_lock): # Arrange lock: ProcessLock = default_process_lock ...
59
1,503
khoj
tests/helpers.py
.py
import glob import logging import os from datetime import datetime import factory from asgiref.sync import sync_to_async from django.utils.timezone import make_aware from khoj.database.adapters import AgentAdapters from khoj.database.models import ( Agent, AiModelApi, ChatMessageModel, ChatModel, ...
327
9,704
khoj
tests/test_cli.py
.py
# Standard Modules from pathlib import Path from khoj.utils.cli import cli # Test # ---------------------------------------------------------------------------------------------------- def test_cli_minimal_default(): # Act actual_args = cli(["-vvv"]) # Assert assert actual_args.log_file == Path("~/....
16
372
khoj
tests/test_orgnode.py
.py
import datetime from khoj.processor.content.org_mode import orgnode # Test # ---------------------------------------------------------------------------------------------------- def test_parse_entry_with_no_headings(tmp_path): "Test parsing of entry with minimal fields" # Arrange entry = """Body Line 1""...
403
12,879
khoj
tests/test_plaintext_to_entries.py
.py
from pathlib import Path from textwrap import dedent from khoj.processor.content.plaintext.plaintext_to_entries import PlaintextToEntries def test_plaintext_file(): "Convert files with no heading to jsonl." # Arrange raw_entry = """ Hi, I am a plaintext file and I have some plaintext words. """ ...
100
3,040
khoj
tests/test_helpers.py
.py
import os import secrets import numpy as np import psutil import pytest from scipy.stats import linregress from khoj.processor.embeddings import EmbeddingsModel from khoj.processor.tools.online_search import ( read_webpage_at_url, read_webpage_with_olostep, ) from khoj.utils import helpers def test_get_from...
119
4,092
khoj
tests/test_conversation_utils.py
.py
from copy import deepcopy import tiktoken from langchain_core.messages.chat import ChatMessage from khoj.processor.conversation import utils class TestTruncateMessage: max_prompt_size = 40 model_name = "gpt-4o-mini" encoder = tiktoken.encoding_for_model(model_name) def test_truncate_message_all_sma...
228
11,494
khoj
tests/conftest.py
.py
import pytest from fastapi import FastAPI from fastapi.staticfiles import StaticFiles from fastapi.testclient import TestClient from khoj.configure import ( configure_middleware, configure_routes, configure_search_types, ) from khoj.database.adapters import get_default_search_model from khoj.database.model...
426
12,967
khoj
tests/evals/eval.py
.py
import argparse import base64 import concurrent.futures import json import logging import os import re import time from datetime import datetime from functools import partial from io import StringIO from textwrap import dedent from threading import Lock from typing import Any, Dict import pandas as pd import requests ...
727
28,582
khoj
src/khoj/manage.py
.py
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "khoj.app.settings") try: from django.core.management import execute_from_command_line except Im...
24
665
khoj
src/khoj/main.py
.py
"""Main module for Khoj isort:skip_file """ from contextlib import redirect_stdout import logging import io import os import atexit import sys import locale from rich.logging import RichHandler import threading import warnings from importlib.metadata import version from khoj.utils.helpers import in_debug_mode, is_en...
259
8,735
khoj
src/khoj/configure.py
.py
import json import logging import os from datetime import datetime from enum import Enum from functools import wraps from typing import Optional import openai import requests import schedule from asgiref.sync import sync_to_async from django.conf import settings from django.db import ( DatabaseError, Operation...
498
20,821
khoj
src/khoj/search_filter/word_filter.py
.py
import logging import re from collections import defaultdict from typing import List from khoj.search_filter.base_filter import BaseFilter from khoj.utils.helpers import LRU logger = logging.getLogger(__name__) class WordFilter(BaseFilter): # Filter Regex required_regex = r'\+"([a-zA-Z0-9_-]+)" ?' block...
30
1,005
khoj
src/khoj/search_filter/date_filter.py
.py
import calendar import logging import re from collections import defaultdict from datetime import datetime, timedelta from math import inf from typing import List, Tuple import dateparser as dtparse from dateutil.relativedelta import relativedelta from khoj.search_filter.base_filter import BaseFilter from khoj.utils....
216
10,019
khoj
src/khoj/search_filter/base_filter.py
.py
from abc import ABC, abstractmethod from typing import List class BaseFilter(ABC): @abstractmethod def get_filter_terms(self, query: str) -> List[str]: ... def can_filter(self, raw_query: str) -> bool: return len(self.get_filter_terms(raw_query)) > 0 @abstractmethod def defilter(self, qu...
14
342
khoj
src/khoj/search_filter/file_filter.py
.py
import logging import re from collections import defaultdict from typing import List from khoj.search_filter.base_filter import BaseFilter from khoj.utils.helpers import LRU logger = logging.getLogger(__name__) class FileFilter(BaseFilter): file_filter_regex = r'(?<!-)file:"(.+?)" ?' excluded_file_filter_re...
33
1,146
khoj
src/khoj/routers/twilio.py
.py
import logging import os from khoj.database.models import KhojUser logger = logging.getLogger(__name__) account_sid = os.getenv("TWILIO_ACCOUNT_SID") auth_token = os.getenv("TWILIO_AUTH_TOKEN") verification_service_sid = os.getenv("TWILIO_VERIFICATION_SID") twilio_enabled = account_sid is not None and auth_token is...
37
1,081
khoj
src/khoj/routers/web_client.py
.py
# System Packages import json from fastapi import APIRouter, HTTPException, Request from fastapi.responses import FileResponse, HTMLResponse, RedirectResponse from fastapi.templating import Jinja2Templates from starlette.authentication import requires from khoj.database.adapters import get_user_github_config from kho...
139
5,275
khoj
src/khoj/routers/api_subscription.py
.py
import logging import os from datetime import datetime, timezone from asgiref.sync import sync_to_async from fastapi import APIRouter, Request from starlette.authentication import requires from khoj.database import adapters from khoj.database.models import Subscription from khoj.routers.helpers import update_telemetr...
150
6,005
khoj
src/khoj/routers/email.py
.py
import logging import os from urllib.parse import quote import markdown_it import resend from django.conf import settings from jinja2 import Environment, FileSystemLoader from khoj.utils.helpers import is_none_or_empty logger = logging.getLogger(__name__) RESEND_API_KEY = os.getenv("RESEND_API_KEY") RESEND_AUDIENC...
137
3,917
khoj
src/khoj/routers/storage.py
.py
import logging import os import uuid logger = logging.getLogger(__name__) AWS_ACCESS_KEY = os.getenv("AWS_ACCESS_KEY") AWS_SECRET_KEY = os.getenv("AWS_SECRET_KEY") # S3 supports serving assets via your domain. Khoj expects this to be used in production. To enable it: # 1. Your bucket name for images should be of the ...
63
2,172
khoj
src/khoj/routers/api_automation.py
.py
import json import logging import threading from typing import Optional import cron_descriptor import pytz from apscheduler.job import Job from apscheduler.triggers.cron import CronTrigger from fastapi import APIRouter, Request from fastapi.responses import Response from starlette.authentication import requires from ...
244
9,398
khoj
src/khoj/routers/api_agents.py
.py
import json import logging import random from datetime import datetime, timedelta, timezone from typing import Dict, List, Optional from asgiref.sync import sync_to_async from django.core.exceptions import ValidationError from fastapi import APIRouter, Request from fastapi.responses import Response from pydantic impor...
511
17,784
khoj
src/khoj/routers/research.py
.py
import asyncio import logging import os from copy import deepcopy from datetime import datetime from typing import Callable, Dict, List, Optional import yaml from khoj.database.adapters import AgentAdapters, EntryAdapters, McpServerAdapters from khoj.database.models import Agent, ChatMessageModel, KhojUser, UserMemor...
707
32,983
khoj
src/khoj/routers/auth.py
.py
import asyncio import datetime import logging import os from typing import Optional from urllib.parse import urlencode, urlparse, urlunparse import requests from fastapi import APIRouter, Depends, HTTPException from starlette.authentication import requires from starlette.config import Config from starlette.requests im...
325
11,661
khoj
src/khoj/routers/api_content.py
.py
import asyncio import json import logging import math from concurrent.futures import ThreadPoolExecutor from typing import Dict, List, Optional, Union from asgiref.sync import sync_to_async from fastapi import ( APIRouter, BackgroundTasks, Depends, Header, HTTPException, Request, Response, ...
637
20,501
khoj
src/khoj/routers/notion.py
.py
import asyncio import base64 import json import logging import os from concurrent.futures import ThreadPoolExecutor import requests from fastapi import APIRouter, BackgroundTasks, Request, Response from starlette.authentication import requires from starlette.responses import RedirectResponse from khoj.database.models...
88
3,022
khoj
src/khoj/routers/api_model.py
.py
import json import logging from typing import Dict, Optional, Union from fastapi import APIRouter, Request from fastapi.responses import Response from starlette.authentication import has_required_scope, requires from khoj.database.adapters import ConversationAdapters from khoj.database.models import ( ChatModel, ...
164
5,236
khoj
src/khoj/routers/api_memories.py
.py
import json import logging from typing import Optional from asgiref.sync import sync_to_async from fastapi import APIRouter, Request from fastapi.responses import Response from pydantic import BaseModel from starlette.authentication import requires from khoj.database.adapters import UserMemoryAdapters from khoj.datab...
115
3,039
khoj
src/khoj/routers/api.py
.py
import json import logging import math import os import uuid from typing import List, Optional, Union import openai from fastapi import APIRouter, Depends, File, HTTPException, Request, UploadFile from fastapi.responses import Response from starlette.authentication import has_required_scope, requires from khoj.config...
269
8,470
khoj
src/khoj/routers/api_chat.py
.py
import asyncio import base64 import json import logging import time import uuid from dataclasses import dataclass from datetime import datetime from functools import partial from typing import Any, Dict, List, Optional from urllib.parse import unquote from fastapi import ( APIRouter, Depends, HTTPException...
1,762
70,509
khoj
src/khoj/routers/helpers.py
.py
import asyncio import base64 import fnmatch import hashlib import json import logging import math import os import re import time from datetime import datetime, timedelta, timezone from random import random from typing import ( Annotated, Any, AsyncGenerator, Callable, Dict, List, Optional, ...
3,459
132,047
khoj
src/khoj/routers/api_phone.py
.py
import logging from typing import Optional from fastapi import APIRouter, Depends, HTTPException, Request from starlette.authentication import requires from khoj.database import adapters from khoj.database.models import KhojUser from khoj.routers.helpers import ApiUserRateLimiter, update_telemetry_state from khoj.rou...
87
2,208
khoj
src/khoj/processor/embeddings.py
.py
import logging from typing import List import requests import tqdm from sentence_transformers import CrossEncoder, SentenceTransformer from tenacity import ( before_sleep_log, retry, retry_if_exception_type, stop_after_attempt, wait_random_exponential, ) from torch import nn from khoj.database.mod...
147
6,588
khoj
src/khoj/processor/image/generate.py
.py
import base64 import io import logging import os import time from typing import Any, Callable, Dict, List, Optional import openai import requests from google import genai from google.genai import types as gtypes from tenacity import ( retry, retry_if_exception, retry_if_exception_type, stop_after_attem...
444
18,003
khoj
src/khoj/processor/conversation/utils.py
.py
import base64 import json import logging import mimetypes import os import re import uuid from dataclasses import dataclass from datetime import datetime from enum import Enum from io import BytesIO from typing import Any, Callable, Dict, List, Literal, Optional, Tuple, Union import httpx import PIL.Image import pyjso...
1,282
48,872