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
PageIndex
pageindex/flash/phases/line_numbers.py
.py
"""Line-number column detection and stripping.""" from __future__ import annotations import math from typing import Optional from sortedcontainers import SortedKeyList from ..model import ( Span, left_aligned, right_aligned, center_aligned, x_centers_close, to_number, Rect, append_spa...
163
6,666
PageIndex
pageindex/flash/labels/__init__.py
.py
"""Keyword-labeled section and caption-region detection. This module finds blocks that look like figure/table/chart labels or named sections, then extends each label forward or backward to claim the associated body blocks. The resulting regions are used by classification and outline assembly to avoid treating captions ...
49
2,090
PageIndex
pageindex/flash/labels/caption_text.py
.py
"""Caption label text helpers and structural-number parsing.""" from __future__ import annotations import regex as regex_module # Unicode \p{...} property classes. from typing import Optional from ..model import ( Rect, rect_union, extend_top_to, extend_bottom_to, EMPTY_RECT, Bounded, _trim_unicode_ws, c...
172
7,031
PageIndex
pageindex/flash/labels/caption_regions.py
.py
"""Caption region growth, deduplication, and detection.""" from __future__ import annotations from typing import Optional from ..classification import FIGURE_KEYWORDS_TRIE, TABLE_KEYWORDS_TRIE, CHART_KEYWORDS_TRIE from ..model import ( Rect, rect_union, extend_top_to, extend_bottom_to, EMPTY_RECT, Bounded, _...
367
16,857
PageIndex
pageindex/integrations/openai_agents.py
.py
"""OpenAI Agents SDK adapter for the Agent(tools=...) slot. Cloud clients default to the live read tool set as plain FunctionTools via the MCP bridge; pass hosted=True to use a single HostedMCPTool instead (the model connects to the PageIndex cloud MCP server from OpenAI's side — the read-only ``?tools=read`` endpoint...
79
3,643
PageIndex
pageindex/integrations/__init__.py
.py
"""Framework adapters for the agent tools layer. These modules import their target frameworks lazily, at call time — the frameworks are never required to install or import pageindex. """
6
190
PageIndex
pageindex/integrations/claude_agent_sdk.py
.py
"""Claude Agent SDK adapter: one value for the mcp_servers slot. Cloud clients get the remote PageIndex MCP config — the framework connects directly, and include_management picks the endpoint (the read-only ``?tools=read`` URL by default); local clients get an in-process SDK MCP server over the same tool contract, gat...
68
2,643
PageIndex
pageindex/integrations/anthropic_sdk.py
.py
"""Anthropic SDK adapter for the tool runner's tools=... slot. Cloud clients get one runnable tool per live cloud MCP tool — the server's input schemas pass through verbatim (MCP inputSchema and Messages API input_schema are the same shape), calls proxied over MCP. Local clients get the in-process tools — the same set...
60
2,325
PageIndex
tests/test_client.py
.py
"""SDK surface tests: PageIndexClient in local and cloud mode.""" import asyncio import importlib import json import re import shutil import types import pytest import pageindex.flash import pageindex.utils from pageindex import PageIndexClient, PageIndexAPIError page_index_module = importlib.import_module("pageinde...
812
33,058
PageIndex
tests/test_agent_tools.py
.py
"""Agent tools layer: cloud-contract parity and behavior against a seeded local store (no LLM calls; one live parity test gated on PAGEINDEX_API_KEY).""" import asyncio import json import os import re import sys import time import types from pathlib import Path import pytest import pageindex.agent_tools as agent_tool...
2,213
93,320
PageIndex
tests/test_issue_163.py
.py
import pytest import sys import os from unittest.mock import patch, MagicMock sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..")) from pageindex.page_index_classic import ( check_if_toc_extraction_is_complete, check_if_toc_transformation_is_complete, toc_detector_single_page, detect_page...
136
6,066
PageIndex
tests/test_page_index.py
.py
import unittest from unittest.mock import Mock, patch from pageindex.page_index_classic import ( _secure_doc_text, process_no_toc, process_toc_no_page_numbers, ) class ProcessTocNoPageNumbersTest(unittest.TestCase): def test_rejects_same_length_reordered_llm_toc(self): toc = [ {"s...
70
2,776
PageIndex
tests/test_page_index_md.py
.py
import unittest from pageindex.page_index_md import extract_nodes_from_markdown class ExtractNodesFromMarkdownTest(unittest.TestCase): def test_skips_bold_heading_with_only_whitespace(self): nodes, _ = extract_nodes_from_markdown("** **\n**Valid heading**") self.assertEqual( nodes,...
24
563
PageIndex
tests/test_package_surface.py
.py
"""What `pip install pageindex` exposes: 0.2.8 helper compat and import cost.""" import subprocess import sys from pageindex.utils import create_node_mapping, print_tree, remove_fields TREE = [ {"title": "Root", "node_id": "0000", "page_index": 1, "text": "root text", "nodes": [ {"title": "Chil...
104
4,061
PageIndex
tests/test_local_chat.py
.py
"""Local chat surfaces: three protocols over fake backends — no network, no LLM keys. Tool execution runs for real against a seeded local store.""" import asyncio import json import sys import types import httpx # via the hard `openai` dependency import pytest import pageindex.local_chat as local_chat from pageindex...
1,395
60,212
PageIndex
tests/conftest.py
.py
import pytest @pytest.fixture(autouse=True) def _llm_key(monkeypatch): """Deterministic key presence for every test; missing-key tests delenv.""" monkeypatch.setenv("OPENAI_API_KEY", "test-key") def build_pdf(page_texts): """Build a minimal, uncompressed PDF (one Helvetica line per page) whose text ...
53
2,008
PageIndex
examples/agentic_vectorless_rag_demo.py
.py
""" Agentic Vectorless RAG with PageIndex - Demo A simple example of building a document QA agent with the PageIndex SDK in local mode and the OpenAI Agents SDK. Instead of vector similarity search and chunking, PageIndex builds a hierarchical tree index and uses agentic LLM reasoning for human-like, context-aware ret...
170
7,071
jieba
setup.py
.py
# -*- coding: utf-8 -*- from distutils.core import setup LONGDOC = """ jieba ===== “结巴”中文分词:做最好的 Python 中文分词组件 "Jieba" (Chinese for "to stutter") Chinese text segmentation: built to be the best Python Chinese word segmentation module. 完整文档见 ``README.md`` GitHub: https://github.com/fxsjy/jieba 特点 ==== - 支持三种分词模式:...
76
2,563
jieba
jieba/_compat.py
.py
# -*- coding: utf-8 -*- import logging import os import sys log_console = logging.StreamHandler(sys.stderr) default_logger = logging.getLogger(__name__) default_logger.setLevel(logging.DEBUG) def setLogLevel(log_level): default_logger.setLevel(log_level) check_paddle_install = {'is_paddle_installed': False} t...
90
2,785
jieba
jieba/__main__.py
.py
"""Jieba command line interface.""" import sys import jieba from argparse import ArgumentParser from ._compat import * parser = ArgumentParser(usage="%s -m jieba [options] filename" % sys.executable, description="Jieba command line interface.", epilog="If no filename specified, use STDIN instead.") parser.add_argument...
62
2,371
jieba
jieba/__init__.py
.py
from __future__ import absolute_import, unicode_literals __version__ = '0.42.1' __license__ = 'MIT' import marshal import re import tempfile import threading import time from hashlib import md5 from math import log from . import finalseg from ._compat import * if os.name == 'nt': from shutil import move as _rep...
620
19,809
jieba
jieba/posseg/__init__.py
.py
from __future__ import absolute_import, unicode_literals import pickle import re import jieba from .viterbi import viterbi from .._compat import * PROB_START_P = "prob_start.p" PROB_TRANS_P = "prob_trans.p" PROB_EMIT_P = "prob_emit.p" CHAR_STATE_TAB_P = "char_state_tab.p" re_han_detail = re.compile("([\u4E00-\u9FD5...
311
9,652
jieba
jieba/posseg/prob_trans.py
.py
P={('B', 'a'): {('E', 'a'): -0.0050648453069648755, ('M', 'a'): -5.287963037107507}, ('B', 'ad'): {('E', 'ad'): -0.0007479013978476627, ('M', 'ad'): -7.198613337130562}, ('B', 'ag'): {}, ('B', 'an'): {('E', 'an'): 0.0}, ('B', 'b'): {('E', 'b'): -0.06753917715798491, ('M', ...
5,308
247,312
jieba
jieba/posseg/prob_start.py
.py
P={('B', 'a'): -4.762305214596967, ('B', 'ad'): -6.680066036784177, ('B', 'ag'): -3.14e+100, ('B', 'an'): -8.697083223018778, ('B', 'b'): -5.018374362109218, ('B', 'bg'): -3.14e+100, ('B', 'c'): -3.423880184954888, ('B', 'd'): -3.9750475297585357, ('B', 'df'): -8.888974230828882, ('B', 'dg'): -3.14e+100, ('B'...
257
7,204
jieba
jieba/posseg/viterbi.py
.py
import sys import operator MIN_FLOAT = -3.14e100 MIN_INF = float("-inf") if sys.version_info[0] > 2: xrange = range def get_top_states(t_state_v, K=4): return sorted(t_state_v, key=t_state_v.__getitem__, reverse=True)[:K] def viterbi(obs, states, start_p, trans_p, emit_p): V = [{}] # tabular mem_p...
54
1,610
jieba
jieba/finalseg/__init__.py
.py
from __future__ import absolute_import, unicode_literals import re import os import sys import pickle from .._compat import * MIN_FLOAT = -3.14e100 PROB_START_P = "prob_start.p" PROB_TRANS_P = "prob_trans.p" PROB_EMIT_P = "prob_emit.p" PrevStatus = { 'B': 'ES', 'M': 'MB', 'S': 'SE', 'E': 'BM' } For...
101
2,659
jieba
jieba/finalseg/prob_trans.py
.py
P={'B': {'E': -0.510825623765990, 'M': -0.916290731874155}, 'E': {'B': -0.5897149736854513, 'S': -0.8085250474669937}, 'M': {'E': -0.33344856811948514, 'M': -1.2603623820268226}, 'S': {'B': -0.7211965654669841, 'S': -0.6658631448798212}}
5
241
jieba
jieba/finalseg/prob_start.py
.py
P={'B': -0.26268660809250016, 'E': -3.14e+100, 'M': -3.14e+100, 'S': -1.4652633398537678}
5
93
jieba
jieba/analyse/analyzer.py
.py
# encoding=utf-8 from __future__ import unicode_literals from whoosh.analysis import RegexAnalyzer, LowercaseFilter, StopFilter, StemFilter from whoosh.analysis import Tokenizer, Token from whoosh.lang.porter import stem import jieba import re STOP_WORDS = frozenset(('a', 'an', 'and', 'are', 'as', 'at', 'be', 'by', '...
38
1,403
jieba
jieba/analyse/textrank.py
.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import sys from operator import itemgetter from collections import defaultdict import jieba.posseg from .tfidf import KeywordExtractor from .._compat import * class UndirectWeightedGraph: d = 0.85 def __in...
111
3,772
jieba
jieba/analyse/__init__.py
.py
from __future__ import absolute_import from .tfidf import TFIDF from .textrank import TextRank try: from .analyzer import ChineseAnalyzer except ImportError: pass default_tfidf = TFIDF() default_textrank = TextRank() extract_tags = tfidf = default_tfidf.extract_tags set_idf_path = default_tfidf.set_idf_path t...
19
501
jieba
jieba/analyse/tfidf.py
.py
# encoding=utf-8 from __future__ import absolute_import import os import jieba import jieba.posseg from operator import itemgetter _get_module_path = lambda path: os.path.normpath(os.path.join(os.getcwd(), os.path.dirname(__file__), path)) _get_abs_path = jieba._get_abs...
117
4,310
jieba
jieba/lac_small/creator.py
.py
# -*- coding: UTF-8 -*- # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # 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 # ...
47
1,476
jieba
jieba/lac_small/utils.py
.py
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # 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 app...
143
4,319
jieba
jieba/lac_small/predict.py
.py
# -*- coding: UTF-8 -*- # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # 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 # ...
82
2,626
jieba
jieba/lac_small/reader_small.py
.py
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # 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 app...
101
3,123
jieba
jieba/lac_small/nets.py
.py
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # 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 app...
122
4,371
jieba
test/extract_tags.py
.py
import sys sys.path.append('../') import jieba import jieba.analyse from optparse import OptionParser USAGE = "usage: python extract_tags.py [file name] -k [top k]" parser = OptionParser(USAGE) parser.add_option("-k", dest="topK") opt, args = parser.parse_args() if len(args) < 1: print(USAGE) sys.exit(1...
31
528
jieba
test/test_pos.py
.py
#encoding=utf-8 from __future__ import print_function import sys sys.path.append("../") import jieba.posseg as pseg def cuttest(test_sent): result = pseg.cut(test_sent) for word, flag in result: print(word, "/", flag, ", ", end=' ') print("") if __name__ == "__main__": cuttest("这是一个伸手不见五指的黑夜。...
100
4,861
jieba
test/test_userdict.py
.py
#encoding=utf-8 from __future__ import print_function, unicode_literals import sys sys.path.append("../") import jieba jieba.load_userdict("userdict.txt") import jieba.posseg as pseg jieba.add_word('石墨烯') jieba.add_word('凱特琳') jieba.del_word('自定义词') test_sent = ( "李小福是创新办主任也是云计算方面的专家; 什么是八一双鹿\n" "例如我输入一个带“韩玉赏鉴”的标题,在自...
49
1,393
jieba
test/extract_tags_idfpath.py
.py
import sys sys.path.append('../') import jieba import jieba.analyse from optparse import OptionParser USAGE = "usage: python extract_tags_idfpath.py [file name] -k [top k]" parser = OptionParser(USAGE) parser.add_option("-k", dest="topK") opt, args = parser.parse_args() if len(args) < 1: print(USAGE) sy...
33
594
jieba
test/test_paddle.py
.py
#encoding=utf-8 import sys sys.path.append("../") import jieba jieba.enable_paddle() def cuttest(test_sent): result = jieba.cut(test_sent, use_paddle=True) print(" / ".join(result)) if __name__ == "__main__": cuttest("这是一个伸手不见五指的黑夜。我叫孙悟空,我爱北京,我爱Python和C++。") cuttest("我不喜欢日本和服。") cuttest("雷猴回归人间。"...
103
5,127
jieba
test/test_cutall.py
.py
#encoding=utf-8 from __future__ import print_function import sys sys.path.append("../") import jieba def cuttest(test_sent): result = jieba.cut(test_sent,cut_all=True) for word in result: print(word, "/", end=' ') print("") if __name__ == "__main__": cuttest("这是一个伸手不见五指的黑夜。我叫孙悟空,我爱北京,我爱Pytho...
102
4,990
jieba
test/test_cut_for_search.py
.py
#encoding=utf-8 from __future__ import print_function import sys sys.path.append("../") import jieba def cuttest(test_sent): result = jieba.cut_for_search(test_sent) for word in result: print(word, "/", end=' ') print("") if __name__ == "__main__": cuttest("这是一个伸手不见五指的黑夜。我叫孙悟空,我爱北京,我爱Python和...
99
4,804
jieba
test/extract_tags_with_weight.py
.py
import sys sys.path.append('../') import jieba import jieba.analyse from optparse import OptionParser USAGE = "usage: python extract_tags_with_weight.py [file name] -k [top k] -w [with weight=1 or 0]" parser = OptionParser(USAGE) parser.add_option("-k", dest="topK") parser.add_option("-w", dest="withWeight") opt,...
44
895
jieba
test/test_bug.py
.py
#encoding=utf-8 from __future__ import print_function import sys sys.path.append("../") import jieba import jieba.posseg as pseg words=pseg.cut("又跛又啞") for w in words: print(w.word,w.flag)
11
199
jieba
test/test_tokenize_no_hmm.py
.py
#encoding=utf-8 from __future__ import print_function,unicode_literals import sys sys.path.append("../") import jieba g_mode="default" def cuttest(test_sent): global g_mode result = jieba.tokenize(test_sent,mode=g_mode,HMM=False) for tk in result: print("word %s\t\t start: %d \t\t end:%d" % (tk[0]...
107
5,544
jieba
test/test_pos_no_hmm.py
.py
#encoding=utf-8 from __future__ import print_function import sys sys.path.append("../") import jieba.posseg as pseg def cuttest(test_sent): result = pseg.cut(test_sent, HMM=False) for word, flag in result: print(word, "/", flag, ", ", end=' ') print("") if __name__ == "__main__": cuttest("这是一...
100
4,872
jieba
test/test_tokenize.py
.py
#encoding=utf-8 from __future__ import print_function,unicode_literals import sys sys.path.append("../") import jieba g_mode="default" def cuttest(test_sent): global g_mode result = jieba.tokenize(test_sent,mode=g_mode) for tk in result: print("word %s\t\t start: %d \t\t end:%d" % (tk[0],tk[1],tk[...
107
5,534
jieba
test/test_file.py
.py
import time import sys sys.path.append("../") import jieba jieba.initialize() url = sys.argv[1] content = open(url,"rb").read() t1 = time.time() words = "/ ".join(jieba.cut(content)) t2 = time.time() tm_cost = t2-t1 log_f = open("1.log","wb") log_f.write(words.encode('utf-8')) log_f.close() print('cost ' + str(tm_c...
22
383
jieba
test/demo.py
.py
#encoding=utf-8 from __future__ import unicode_literals import sys sys.path.append("../") import jieba import jieba.posseg import jieba.analyse print('='*40) print('1. 分词') print('-'*40) seg_list = jieba.cut("我来到北京清华大学", cut_all=True) print("Full Mode: " + "/ ".join(seg_list)) # 全模式 seg_list = jieba.cut("我来到北京清华大学...
85
2,678
jieba
test/jieba_test.py
.py
#-*-coding: utf-8 -*- from __future__ import unicode_literals, print_function import sys sys.path.append("../") import unittest import types import jieba if sys.version_info[0] > 2: from imp import reload jieba.initialize() test_contents = [ "这是一个伸手不见五指的黑夜。我叫孙悟空,我爱北京,我爱Python和C++。", "我不喜欢日本和服。", "雷猴回...
206
9,085
jieba
test/extract_tags_stop_words.py
.py
import sys sys.path.append('../') import jieba import jieba.analyse from optparse import OptionParser USAGE = "usage: python extract_tags_stop_words.py [file name] -k [top k]" parser = OptionParser(USAGE) parser.add_option("-k", dest="topK") opt, args = parser.parse_args() if len(args) < 1: print(USAGE) ...
34
658
jieba
test/test_whoosh_file_read.py
.py
# -*- coding: UTF-8 -*- from __future__ import unicode_literals import sys import os sys.path.append("../") from whoosh.index import create_in,open_dir from whoosh.fields import * from whoosh.qparser import QueryParser from jieba.analyse import ChineseAnalyzer analyzer = ChineseAnalyzer() schema = Schema(title=TEXT...
29
826
jieba
test/test_pos_file.py
.py
from __future__ import print_function import sys import time sys.path.append("../") import jieba jieba.initialize() import jieba.posseg as pseg url = sys.argv[1] content = open(url,"rb").read() t1 = time.time() words = list(pseg.cut(content)) t2 = time.time() tm_cost = t2-t1 log_f = open("1.log","w") log_f.write(' /...
22
403
jieba
test/test_whoosh_file.py
.py
# -*- coding: UTF-8 -*- from __future__ import unicode_literals import sys import os sys.path.append("../") from whoosh.index import create_in from whoosh.fields import * from whoosh.qparser import QueryParser from jieba.analyse import ChineseAnalyzer analyzer = ChineseAnalyzer() schema = Schema(title=TEXT(stored=Tr...
43
1,089
jieba
test/test_lock.py
.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import jieba import threading def inittokenizer(tokenizer, group): print('===> Thread %s:%s started' % (group, threading.current_thread().ident)) tokenizer.initialize() print('<=== Thread %s:%s finished' % (group, threading.current_thread().ident)) tokrs1 = [jieba.Tok...
43
1,113
jieba
test/test_no_hmm.py
.py
#encoding=utf-8 import sys sys.path.append("../") import jieba def cuttest(test_sent): result = jieba.cut(test_sent,HMM=False) print(" / ".join(result)) if __name__ == "__main__": cuttest("这是一个伸手不见五指的黑夜。我叫孙悟空,我爱北京,我爱Python和C++。") cuttest("我不喜欢日本和服。") cuttest("雷猴回归人间。") cuttest("工信处女干事每月经过下属科...
101
4,983
jieba
test/test_whoosh.py
.py
# -*- coding: UTF-8 -*- from __future__ import unicode_literals import sys,os sys.path.append("../") from whoosh.index import create_in,open_dir from whoosh.fields import * from whoosh.qparser import QueryParser from jieba.analyse.analyzer import ChineseAnalyzer analyzer = ChineseAnalyzer() schema = Schema(title=TEX...
65
1,743
jieba
test/extract_topic.py
.py
import sys sys.path.append("../") from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn import decomposition import jieba import time import glob import sys import os import random if len(sys.argv)<2: print("usage: extract_topic.py di...
64
1,463
jieba
test/test.py
.py
#encoding=utf-8 import sys sys.path.append("../") import jieba def cuttest(test_sent): result = jieba.cut(test_sent) print(" / ".join(result)) if __name__ == "__main__": cuttest("这是一个伸手不见五指的黑夜。我叫孙悟空,我爱北京,我爱Python和C++。") cuttest("我不喜欢日本和服。") cuttest("雷猴回归人间。") cuttest("工信处女干事每月经过下属科室都要亲口交代24口...
103
5,089
jieba
test/test_paddle_postag.py
.py
#encoding=utf-8 import sys sys.path.append("../") import jieba.posseg as pseg import jieba jieba.enable_paddle() def cuttest(test_sent): result = pseg.cut(test_sent, use_paddle=True) for word, flag in result: print('%s %s' % (word, flag)) if __name__ == "__main__": cuttest("这是一个伸手不见五指的黑夜。我叫孙悟空,我爱...
103
5,076
jieba
test/test_change_dictpath.py
.py
#encoding=utf-8 from __future__ import print_function import sys sys.path.append("../") import jieba def cuttest(test_sent): result = jieba.cut(test_sent) print(" ".join(result)) def testcase(): cuttest("这是一个伸手不见五指的黑夜。我叫孙悟空,我爱北京,我爱Python和C++。") cuttest("我不喜欢日本和服。") cuttest("雷猴回归人间。") cuttest(...
29
873
jieba
test/jiebacmd.py
.py
''' usage example (find top 100 words in abc.txt): cat abc.txt | python jiebacmd.py | sort | uniq -c | sort -nr -k1 | head -100 ''' from __future__ import unicode_literals import sys sys.path.append("../") import jieba default_encoding='utf-8' if len(sys.argv)>1: default_encoding = sys.argv[1] while True: ...
29
461
jieba
test/test_multithread.py
.py
#encoding=utf-8 import sys import threading sys.path.append("../") import jieba class Worker(threading.Thread): def run(self): seg_list = jieba.cut("我来到北京清华大学",cut_all=True) print("Full Mode:" + "/ ".join(seg_list)) #全模式 seg_list = jieba.cut("我来到北京清华大学",cut_all=False) print("Defau...
30
830
jieba
test/parallel/extract_tags.py
.py
import sys sys.path.append('../../') import jieba jieba.enable_parallel(4) import jieba.analyse from optparse import OptionParser USAGE ="usage: python extract_tags.py [file name] -k [top k]" parser = OptionParser(USAGE) parser.add_option("-k",dest="topK") opt, args = parser.parse_args() if len(args) <1: pr...
35
550
jieba
test/parallel/test_pos.py
.py
#encoding=utf-8 from __future__ import print_function import sys sys.path.append("../../") import jieba jieba.enable_parallel(4) import jieba.posseg as pseg def cuttest(test_sent): result = pseg.cut(test_sent) for w in result: print(w.word, "/", w.flag, ", ", end=' ') print("") if __name__ == "...
101
4,862
jieba
test/parallel/test_disable_hmm.py
.py
#encoding=utf-8 from __future__ import print_function import sys sys.path.append("../../") import jieba jieba.enable_parallel(4) def cuttest(test_sent): result = jieba.cut(test_sent, HMM=False) for word in result: print(word, "/", end=' ') print("") if __name__ == "__main__": cuttest("这是一个伸手不...
96
4,524
jieba
test/parallel/test_cut_for_search.py
.py
#encoding=utf-8 from __future__ import print_function import sys sys.path.append("../../") import jieba jieba.enable_parallel(4) def cuttest(test_sent): result = jieba.cut_for_search(test_sent) for word in result: print(word, "/", end=' ') print("") if __name__ == "__main__": cuttest("这是一个伸手...
96
4,525
jieba
test/parallel/test2.py
.py
#encoding=utf-8 from __future__ import print_function import sys sys.path.append("../../") import jieba jieba.enable_parallel(4) def cuttest(test_sent): result = jieba.cut(test_sent,cut_all=True) for word in result: print(word, "/", end=' ') print("") if __name__ == "__main__": cuttest("这是一个...
96
4,527
jieba
test/parallel/test_file.py
.py
import sys import time sys.path.append("../../") import jieba jieba.enable_parallel() url = sys.argv[1] content = open(url,"rb").read() t1 = time.time() words = "/ ".join(jieba.cut(content)) t2 = time.time() tm_cost = t2-t1 log_f = open("1.log","wb") log_f.write(words.encode('utf-8')) print('speed %s bytes/second'...
21
348
jieba
test/parallel/test_pos_file.py
.py
from __future__ import print_function import sys,time import sys sys.path.append("../../") import jieba import jieba.posseg as pseg jieba.enable_parallel(4) url = sys.argv[1] content = open(url,"rb").read() t1 = time.time() words = list(pseg.cut(content)) t2 = time.time() tm_cost = t2-t1 log_f = open("1.log","w") l...
23
417
jieba
test/parallel/test.py
.py
#encoding=utf-8 from __future__ import print_function import sys sys.path.append("../../") import jieba jieba.enable_parallel(4) def cuttest(test_sent): result = jieba.cut(test_sent) for word in result: print(word, "/", end=' ') print("") if __name__ == "__main__": cuttest("这是一个伸手不见五指的黑夜。我叫孙...
100
4,821
detectron2
setup.py
.py
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. import glob import os import shutil from os import path from setuptools import find_packages, setup from typing import List import torch from torch.utils.cpp_extension import CUDA_HOME, CppExtension, CUDAExtension torch_ver = [int(x) for x in to...
220
8,278
detectron2
demo/predictor.py
.py
# Copyright (c) Facebook, Inc. and its affiliates. import atexit import bisect import multiprocessing as mp from collections import deque import cv2 import torch from detectron2.data import MetadataCatalog from detectron2.engine.defaults import DefaultPredictor from detectron2.utils.video_visualizer import VideoVisual...
221
7,836
detectron2
demo/demo.py
.py
# Copyright (c) Facebook, Inc. and its affiliates. import argparse import glob import multiprocessing as mp import numpy as np import os import tempfile import time import warnings import cv2 import tqdm from detectron2.config import get_cfg from detectron2.data.detection_utils import read_image from detectron2.utils....
195
7,215
detectron2
tools/plain_train_net.py
.py
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. """ Detectron2 training script with a plain training loop. This script reads a given config file and runs the training or evaluation. It is an entry point that is able to train standard models in detectron2. In order to let one script support tr...
222
7,961
detectron2
tools/benchmark.py
.py
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. """ A script to benchmark builtin models. Note: this script has an extra dependency of psutil. """ import itertools import logging import psutil import torch import tqdm from fvcore.common.timer import Timer from torch.nn.parallel import Distrib...
211
6,514
detectron2
tools/lightning_train_net.py
.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # Lightning Trainer should be considered beta at this point # We have confirmed that training and validation run correctly and produce correct results # Depending on how you launch the trainer, there are issues with processes terminating correctl...
246
8,840
detectron2
tools/analyze_model.py
.py
# -*- coding: utf-8 -*- # Copyright (c) Facebook, Inc. and its affiliates. import logging import numpy as np from collections import Counter import tqdm from fvcore.nn import flop_count_table # can also try flop_count_str from detectron2.checkpoint import DetectionCheckpointer from detectron2.config import CfgNode, ...
165
5,052
detectron2
tools/train_net.py
.py
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. """ A main training script. This scripts reads a given config file and runs the training or evaluation. It is an entry point that is made to train standard models in detectron2. In order to let one script support training of many models, this sc...
168
5,865
detectron2
tools/convert-torchvision-to-d2.py
.py
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. import pickle as pkl import sys import torch """ Usage: # download one of the ResNet{18,34,50,101,152} models from torchvision: wget https://download.pytorch.org/models/resnet50-19c8e357.pth -O r50.pth # run the conversion ./convert-torc...
57
1,608
detectron2
tools/visualize_data.py
.py
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. import argparse import os from itertools import chain import cv2 import tqdm from detectron2.config import get_cfg from detectron2.data import DatasetCatalog, MetadataCatalog, build_detection_train_loader from detectron2.data import detection_uti...
100
3,633
detectron2
tools/visualize_json_results.py
.py
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. import argparse import json import numpy as np import os from collections import defaultdict import cv2 import tqdm from detectron2.data import DatasetCatalog, MetadataCatalog from detectron2.structures import Boxes, BoxMode, Instances from dete...
96
3,265
detectron2
tools/lazyconfig_train_net.py
.py
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. """ Training script using the new "LazyConfig" python config files. This scripts reads a given python config file and runs the training or evaluation. It can be used to train any models or dataset as long as they can be instantiated by the recurs...
142
4,604
detectron2
tools/deploy/export_model.py
.py
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. import argparse import os from typing import Dict, List, Tuple import torch from torch import Tensor, nn import detectron2.data.transforms as T from detectron2.checkpoint import DetectionCheckpointer from detectron2.config import get_cfg from det...
246
9,454
detectron2
dev/packaging/gen_install_table.py
.py
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. # -*- coding: utf-8 -*- import argparse template = """<details><summary> install </summary><pre><code>\ python -m pip install detectron2{d2_version} -f \\ https://dl.fbaipublicfiles.com/detectron2/wheels/{cuda}/torch{torch}/index.html </code><...
64
2,014
detectron2
datasets/prepare_ade20k_sem_seg.py
.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (c) Facebook, Inc. and its affiliates. import numpy as np import os from pathlib import Path import tqdm from PIL import Image def convert(input, output): img = np.asarray(Image.open(input)) assert img.dtype == np.uint8 img = img - 1 # 0 (ignore)...
27
895
detectron2
datasets/prepare_cocofied_lvis.py
.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (c) Facebook, Inc. and its affiliates. import copy import json import os from collections import defaultdict # This mapping is extracted from the official LVIS mapping: # https://github.com/lvis-dataset/lvis-api/blob/master/data/coco_to_synset.json COCO_SYNSE...
177
7,617
detectron2
datasets/prepare_panoptic_fpn.py
.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (c) Facebook, Inc. and its affiliates. import functools import json import multiprocessing as mp import numpy as np import os import time from fvcore.common.download import download from panopticapi.utils import rgb2id from PIL import Image from detectron2.da...
117
4,351
detectron2
docs/conf.py
.py
# -*- coding: utf-8 -*- # Copyright (c) Facebook, Inc. and its affiliates. # flake8: noqa # Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path ...
396
13,268
detectron2
tests/test_scheduler.py
.py
# Copyright (c) Facebook, Inc. and its affiliates. import math import numpy as np from unittest import TestCase import torch from fvcore.common.param_scheduler import ( CosineParamScheduler, MultiStepParamScheduler, StepWithFixedGammaParamScheduler, ) from torch import nn from detectron2.solver import LRM...
159
5,017
detectron2
tests/test_engine.py
.py
# Copyright (c) Facebook, Inc. and its affiliates. import json import math import os import tempfile import time import unittest from unittest import mock import torch from fvcore.common.checkpoint import Checkpointer from torch import nn from detectron2 import model_zoo from detectron2.config import configurable, ge...
265
10,654
detectron2
tests/test_registry.py
.py
# Copyright (c) Facebook, Inc. and its affiliates. import unittest import torch from detectron2.modeling.meta_arch import GeneralizedRCNN from detectron2.utils.registry import _convert_target_to_string, locate class A: class B: pass class TestLocate(unittest.TestCase): def _test_obj(self, obj): ...
46
1,243
detectron2
tests/test_solver.py
.py
import unittest from detectron2.solver.build import _expand_param_groups, reduce_param_groups class TestOptimizer(unittest.TestCase): def testExpandParamsGroups(self): params = [ { "params": ["p1", "p2", "p3", "p4"], "lr": 1.0, "weight_decay": 3...
67
2,141
detectron2
tests/test_export_torchscript.py
.py
# Copyright (c) Facebook, Inc. and its affiliates. import copy import glob import json import os import random import tempfile import unittest import zipfile import torch from torch import Tensor, nn from detectron2 import model_zoo from detectron2.config import get_cfg from detectron2.config.instantiate import dump_...
339
13,423
detectron2
tests/test_export_onnx.py
.py
# Copyright (c) Facebook, Inc. and its affiliates. import io import unittest import warnings import onnx import torch from packaging import version from torch.hub import _check_module_exists from detectron2 import model_zoo from detectron2.config import get_cfg from detectron2.export import STABLE_ONNX_OPSET_VERSION ...
244
8,884
detectron2
tests/test_events.py
.py
# Copyright (c) Facebook, Inc. and its affiliates. import json import os import tempfile import unittest from detectron2.utils.events import ( CommonMetricPrinter, EventStorage, JSONWriter, get_event_storage, has_event_storage, ) class TestEventWriter(unittest.TestCase): def testScalar(self):...
123
4,668
detectron2
tests/test_model_analysis.py
.py
# Copyright (c) Facebook, Inc. and its affiliates. import unittest import torch from torch import nn from detectron2.utils.analysis import find_unused_parameters, flop_count_operators, parameter_count from detectron2.utils.testing import get_model_no_weights class RetinaNetTest(unittest.TestCase): def setUp(se...
81
2,890
detectron2
tests/test_export_caffe2.py
.py
# Copyright (c) Facebook, Inc. and its affiliates. # -*- coding: utf-8 -*- import copy import os import tempfile import unittest from torch.hub import _check_module_exists from detectron2 import model_zoo from detectron2.utils.logger import setup_logger from detectron2.utils.testing import get_sample_coco_image try:...
52
1,957