repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
jreese/aiosqlite
aiosqlite/core.py
Connection.cursor
python
async def cursor(self) -> Cursor: return Cursor(self, await self._execute(self._conn.cursor))
Create an aiosqlite cursor wrapping a sqlite3 cursor object.
train
https://github.com/jreese/aiosqlite/blob/3f548b568b8db9a57022b6e2c9627f5cdefb983f/aiosqlite/core.py#L186-L188
[ "async def _execute(self, fn, *args, **kwargs):\n \"\"\"Queue a function with the given arguments for execution.\"\"\"\n function = partial(fn, *args, **kwargs)\n future = self._loop.create_future()\n\n self._tx.put_nowait((future, function))\n\n return await future\n" ]
class Connection(Thread): def __init__( self, connector: Callable[[], sqlite3.Connection], loop: asyncio.AbstractEventLoop, ) -> None: super().__init__() self._running = True self._connection = None # type: Optional[sqlite3.Connection] self._connector = connector self._loop = loop self._tx = Queue() # type: Queue @property def _conn(self) -> sqlite3.Connection: if self._connection is None: raise ValueError("no active connection") return self._connection def _execute_insert( self, sql: str, parameters: Iterable[Any] ) -> Optional[sqlite3.Row]: cursor = self._conn.execute(sql, parameters) cursor.execute("SELECT last_insert_rowid()") return cursor.fetchone() def _execute_fetchall( self, sql: str, parameters: Iterable[Any] ) -> Iterable[sqlite3.Row]: cursor = self._conn.execute(sql, parameters) return cursor.fetchall() def run(self) -> None: """Execute function calls on a separate thread.""" while self._running: try: future, function = self._tx.get(timeout=0.1) except Empty: continue try: LOG.debug("executing %s", function) result = function() LOG.debug("returning %s", result) self._loop.call_soon_threadsafe(future.set_result, result) except BaseException as e: LOG.exception("returning exception %s", e) self._loop.call_soon_threadsafe(future.set_exception, e) async def _execute(self, fn, *args, **kwargs): """Queue a function with the given arguments for execution.""" function = partial(fn, *args, **kwargs) future = self._loop.create_future() self._tx.put_nowait((future, function)) return await future async def _connect(self) -> "Connection": """Connect to the actual sqlite database.""" if self._connection is None: self._connection = await self._execute(self._connector) return self def __await__(self) -> Generator[Any, None, "Connection"]: self.start() return self._connect().__await__() async def __aenter__(self) -> "Connection": return await self async def __aexit__(self, exc_type, exc_val, exc_tb) -> None: await self.close() @contextmanager async def commit(self) -> None: """Commit the current transaction.""" await self._execute(self._conn.commit) async def rollback(self) -> None: """Roll back the current transaction.""" await self._execute(self._conn.rollback) async def close(self) -> None: """Complete queued queries/cursors and close the connection.""" await self._execute(self._conn.close) self._running = False self._connection = None @contextmanager async def execute(self, sql: str, parameters: Iterable[Any] = None) -> Cursor: """Helper to create a cursor and execute the given query.""" if parameters is None: parameters = [] cursor = await self._execute(self._conn.execute, sql, parameters) return Cursor(self, cursor) @contextmanager async def execute_insert( self, sql: str, parameters: Iterable[Any] = None ) -> Optional[sqlite3.Row]: """Helper to insert and get the last_insert_rowid.""" if parameters is None: parameters = [] return await self._execute(self._execute_insert, sql, parameters) @contextmanager async def execute_fetchall( self, sql: str, parameters: Iterable[Any] = None ) -> Iterable[sqlite3.Row]: """Helper to execute a query and return all the data.""" if parameters is None: parameters = [] return await self._execute(self._execute_fetchall, sql, parameters) @contextmanager async def executemany( self, sql: str, parameters: Iterable[Iterable[Any]] ) -> Cursor: """Helper to create a cursor and execute the given multiquery.""" cursor = await self._execute(self._conn.executemany, sql, parameters) return Cursor(self, cursor) @contextmanager async def executescript(self, sql_script: str) -> Cursor: """Helper to create a cursor and execute a user script.""" cursor = await self._execute(self._conn.executescript, sql_script) return Cursor(self, cursor) async def interrupt(self) -> None: """Interrupt pending queries.""" return self._conn.interrupt() @property def in_transaction(self) -> bool: return self._conn.in_transaction @property def isolation_level(self) -> str: return self._conn.isolation_level @isolation_level.setter def isolation_level(self, value: str) -> None: self._conn.isolation_level = value @property def row_factory(self) -> "Optional[Type]": # py3.5.2 compat (#24) return self._conn.row_factory @row_factory.setter def row_factory(self, factory: "Optional[Type]") -> None: # py3.5.2 compat (#24) self._conn.row_factory = factory @property def text_factory(self) -> Type: return self._conn.text_factory @text_factory.setter def text_factory(self, factory: Type) -> None: self._conn.text_factory = factory @property def total_changes(self) -> int: return self._conn.total_changes async def enable_load_extension(self, value: bool) -> None: await self._execute(self._conn.enable_load_extension, value) # type: ignore async def load_extension(self, path: str): await self._execute(self._conn.load_extension, path) # type: ignore
jreese/aiosqlite
aiosqlite/core.py
Connection.close
python
async def close(self) -> None: await self._execute(self._conn.close) self._running = False self._connection = None
Complete queued queries/cursors and close the connection.
train
https://github.com/jreese/aiosqlite/blob/3f548b568b8db9a57022b6e2c9627f5cdefb983f/aiosqlite/core.py#L198-L202
[ "async def _execute(self, fn, *args, **kwargs):\n \"\"\"Queue a function with the given arguments for execution.\"\"\"\n function = partial(fn, *args, **kwargs)\n future = self._loop.create_future()\n\n self._tx.put_nowait((future, function))\n\n return await future\n" ]
class Connection(Thread): def __init__( self, connector: Callable[[], sqlite3.Connection], loop: asyncio.AbstractEventLoop, ) -> None: super().__init__() self._running = True self._connection = None # type: Optional[sqlite3.Connection] self._connector = connector self._loop = loop self._tx = Queue() # type: Queue @property def _conn(self) -> sqlite3.Connection: if self._connection is None: raise ValueError("no active connection") return self._connection def _execute_insert( self, sql: str, parameters: Iterable[Any] ) -> Optional[sqlite3.Row]: cursor = self._conn.execute(sql, parameters) cursor.execute("SELECT last_insert_rowid()") return cursor.fetchone() def _execute_fetchall( self, sql: str, parameters: Iterable[Any] ) -> Iterable[sqlite3.Row]: cursor = self._conn.execute(sql, parameters) return cursor.fetchall() def run(self) -> None: """Execute function calls on a separate thread.""" while self._running: try: future, function = self._tx.get(timeout=0.1) except Empty: continue try: LOG.debug("executing %s", function) result = function() LOG.debug("returning %s", result) self._loop.call_soon_threadsafe(future.set_result, result) except BaseException as e: LOG.exception("returning exception %s", e) self._loop.call_soon_threadsafe(future.set_exception, e) async def _execute(self, fn, *args, **kwargs): """Queue a function with the given arguments for execution.""" function = partial(fn, *args, **kwargs) future = self._loop.create_future() self._tx.put_nowait((future, function)) return await future async def _connect(self) -> "Connection": """Connect to the actual sqlite database.""" if self._connection is None: self._connection = await self._execute(self._connector) return self def __await__(self) -> Generator[Any, None, "Connection"]: self.start() return self._connect().__await__() async def __aenter__(self) -> "Connection": return await self async def __aexit__(self, exc_type, exc_val, exc_tb) -> None: await self.close() @contextmanager async def cursor(self) -> Cursor: """Create an aiosqlite cursor wrapping a sqlite3 cursor object.""" return Cursor(self, await self._execute(self._conn.cursor)) async def commit(self) -> None: """Commit the current transaction.""" await self._execute(self._conn.commit) async def rollback(self) -> None: """Roll back the current transaction.""" await self._execute(self._conn.rollback) @contextmanager async def execute(self, sql: str, parameters: Iterable[Any] = None) -> Cursor: """Helper to create a cursor and execute the given query.""" if parameters is None: parameters = [] cursor = await self._execute(self._conn.execute, sql, parameters) return Cursor(self, cursor) @contextmanager async def execute_insert( self, sql: str, parameters: Iterable[Any] = None ) -> Optional[sqlite3.Row]: """Helper to insert and get the last_insert_rowid.""" if parameters is None: parameters = [] return await self._execute(self._execute_insert, sql, parameters) @contextmanager async def execute_fetchall( self, sql: str, parameters: Iterable[Any] = None ) -> Iterable[sqlite3.Row]: """Helper to execute a query and return all the data.""" if parameters is None: parameters = [] return await self._execute(self._execute_fetchall, sql, parameters) @contextmanager async def executemany( self, sql: str, parameters: Iterable[Iterable[Any]] ) -> Cursor: """Helper to create a cursor and execute the given multiquery.""" cursor = await self._execute(self._conn.executemany, sql, parameters) return Cursor(self, cursor) @contextmanager async def executescript(self, sql_script: str) -> Cursor: """Helper to create a cursor and execute a user script.""" cursor = await self._execute(self._conn.executescript, sql_script) return Cursor(self, cursor) async def interrupt(self) -> None: """Interrupt pending queries.""" return self._conn.interrupt() @property def in_transaction(self) -> bool: return self._conn.in_transaction @property def isolation_level(self) -> str: return self._conn.isolation_level @isolation_level.setter def isolation_level(self, value: str) -> None: self._conn.isolation_level = value @property def row_factory(self) -> "Optional[Type]": # py3.5.2 compat (#24) return self._conn.row_factory @row_factory.setter def row_factory(self, factory: "Optional[Type]") -> None: # py3.5.2 compat (#24) self._conn.row_factory = factory @property def text_factory(self) -> Type: return self._conn.text_factory @text_factory.setter def text_factory(self, factory: Type) -> None: self._conn.text_factory = factory @property def total_changes(self) -> int: return self._conn.total_changes async def enable_load_extension(self, value: bool) -> None: await self._execute(self._conn.enable_load_extension, value) # type: ignore async def load_extension(self, path: str): await self._execute(self._conn.load_extension, path) # type: ignore
jreese/aiosqlite
aiosqlite/core.py
Connection.execute_insert
python
async def execute_insert( self, sql: str, parameters: Iterable[Any] = None ) -> Optional[sqlite3.Row]: if parameters is None: parameters = [] return await self._execute(self._execute_insert, sql, parameters)
Helper to insert and get the last_insert_rowid.
train
https://github.com/jreese/aiosqlite/blob/3f548b568b8db9a57022b6e2c9627f5cdefb983f/aiosqlite/core.py#L213-L219
[ "async def _execute(self, fn, *args, **kwargs):\n \"\"\"Queue a function with the given arguments for execution.\"\"\"\n function = partial(fn, *args, **kwargs)\n future = self._loop.create_future()\n\n self._tx.put_nowait((future, function))\n\n return await future\n" ]
class Connection(Thread): def __init__( self, connector: Callable[[], sqlite3.Connection], loop: asyncio.AbstractEventLoop, ) -> None: super().__init__() self._running = True self._connection = None # type: Optional[sqlite3.Connection] self._connector = connector self._loop = loop self._tx = Queue() # type: Queue @property def _conn(self) -> sqlite3.Connection: if self._connection is None: raise ValueError("no active connection") return self._connection def _execute_insert( self, sql: str, parameters: Iterable[Any] ) -> Optional[sqlite3.Row]: cursor = self._conn.execute(sql, parameters) cursor.execute("SELECT last_insert_rowid()") return cursor.fetchone() def _execute_fetchall( self, sql: str, parameters: Iterable[Any] ) -> Iterable[sqlite3.Row]: cursor = self._conn.execute(sql, parameters) return cursor.fetchall() def run(self) -> None: """Execute function calls on a separate thread.""" while self._running: try: future, function = self._tx.get(timeout=0.1) except Empty: continue try: LOG.debug("executing %s", function) result = function() LOG.debug("returning %s", result) self._loop.call_soon_threadsafe(future.set_result, result) except BaseException as e: LOG.exception("returning exception %s", e) self._loop.call_soon_threadsafe(future.set_exception, e) async def _execute(self, fn, *args, **kwargs): """Queue a function with the given arguments for execution.""" function = partial(fn, *args, **kwargs) future = self._loop.create_future() self._tx.put_nowait((future, function)) return await future async def _connect(self) -> "Connection": """Connect to the actual sqlite database.""" if self._connection is None: self._connection = await self._execute(self._connector) return self def __await__(self) -> Generator[Any, None, "Connection"]: self.start() return self._connect().__await__() async def __aenter__(self) -> "Connection": return await self async def __aexit__(self, exc_type, exc_val, exc_tb) -> None: await self.close() @contextmanager async def cursor(self) -> Cursor: """Create an aiosqlite cursor wrapping a sqlite3 cursor object.""" return Cursor(self, await self._execute(self._conn.cursor)) async def commit(self) -> None: """Commit the current transaction.""" await self._execute(self._conn.commit) async def rollback(self) -> None: """Roll back the current transaction.""" await self._execute(self._conn.rollback) async def close(self) -> None: """Complete queued queries/cursors and close the connection.""" await self._execute(self._conn.close) self._running = False self._connection = None @contextmanager async def execute(self, sql: str, parameters: Iterable[Any] = None) -> Cursor: """Helper to create a cursor and execute the given query.""" if parameters is None: parameters = [] cursor = await self._execute(self._conn.execute, sql, parameters) return Cursor(self, cursor) @contextmanager @contextmanager async def execute_fetchall( self, sql: str, parameters: Iterable[Any] = None ) -> Iterable[sqlite3.Row]: """Helper to execute a query and return all the data.""" if parameters is None: parameters = [] return await self._execute(self._execute_fetchall, sql, parameters) @contextmanager async def executemany( self, sql: str, parameters: Iterable[Iterable[Any]] ) -> Cursor: """Helper to create a cursor and execute the given multiquery.""" cursor = await self._execute(self._conn.executemany, sql, parameters) return Cursor(self, cursor) @contextmanager async def executescript(self, sql_script: str) -> Cursor: """Helper to create a cursor and execute a user script.""" cursor = await self._execute(self._conn.executescript, sql_script) return Cursor(self, cursor) async def interrupt(self) -> None: """Interrupt pending queries.""" return self._conn.interrupt() @property def in_transaction(self) -> bool: return self._conn.in_transaction @property def isolation_level(self) -> str: return self._conn.isolation_level @isolation_level.setter def isolation_level(self, value: str) -> None: self._conn.isolation_level = value @property def row_factory(self) -> "Optional[Type]": # py3.5.2 compat (#24) return self._conn.row_factory @row_factory.setter def row_factory(self, factory: "Optional[Type]") -> None: # py3.5.2 compat (#24) self._conn.row_factory = factory @property def text_factory(self) -> Type: return self._conn.text_factory @text_factory.setter def text_factory(self, factory: Type) -> None: self._conn.text_factory = factory @property def total_changes(self) -> int: return self._conn.total_changes async def enable_load_extension(self, value: bool) -> None: await self._execute(self._conn.enable_load_extension, value) # type: ignore async def load_extension(self, path: str): await self._execute(self._conn.load_extension, path) # type: ignore
jreese/aiosqlite
aiosqlite/core.py
Connection.execute_fetchall
python
async def execute_fetchall( self, sql: str, parameters: Iterable[Any] = None ) -> Iterable[sqlite3.Row]: if parameters is None: parameters = [] return await self._execute(self._execute_fetchall, sql, parameters)
Helper to execute a query and return all the data.
train
https://github.com/jreese/aiosqlite/blob/3f548b568b8db9a57022b6e2c9627f5cdefb983f/aiosqlite/core.py#L222-L228
[ "async def _execute(self, fn, *args, **kwargs):\n \"\"\"Queue a function with the given arguments for execution.\"\"\"\n function = partial(fn, *args, **kwargs)\n future = self._loop.create_future()\n\n self._tx.put_nowait((future, function))\n\n return await future\n" ]
class Connection(Thread): def __init__( self, connector: Callable[[], sqlite3.Connection], loop: asyncio.AbstractEventLoop, ) -> None: super().__init__() self._running = True self._connection = None # type: Optional[sqlite3.Connection] self._connector = connector self._loop = loop self._tx = Queue() # type: Queue @property def _conn(self) -> sqlite3.Connection: if self._connection is None: raise ValueError("no active connection") return self._connection def _execute_insert( self, sql: str, parameters: Iterable[Any] ) -> Optional[sqlite3.Row]: cursor = self._conn.execute(sql, parameters) cursor.execute("SELECT last_insert_rowid()") return cursor.fetchone() def _execute_fetchall( self, sql: str, parameters: Iterable[Any] ) -> Iterable[sqlite3.Row]: cursor = self._conn.execute(sql, parameters) return cursor.fetchall() def run(self) -> None: """Execute function calls on a separate thread.""" while self._running: try: future, function = self._tx.get(timeout=0.1) except Empty: continue try: LOG.debug("executing %s", function) result = function() LOG.debug("returning %s", result) self._loop.call_soon_threadsafe(future.set_result, result) except BaseException as e: LOG.exception("returning exception %s", e) self._loop.call_soon_threadsafe(future.set_exception, e) async def _execute(self, fn, *args, **kwargs): """Queue a function with the given arguments for execution.""" function = partial(fn, *args, **kwargs) future = self._loop.create_future() self._tx.put_nowait((future, function)) return await future async def _connect(self) -> "Connection": """Connect to the actual sqlite database.""" if self._connection is None: self._connection = await self._execute(self._connector) return self def __await__(self) -> Generator[Any, None, "Connection"]: self.start() return self._connect().__await__() async def __aenter__(self) -> "Connection": return await self async def __aexit__(self, exc_type, exc_val, exc_tb) -> None: await self.close() @contextmanager async def cursor(self) -> Cursor: """Create an aiosqlite cursor wrapping a sqlite3 cursor object.""" return Cursor(self, await self._execute(self._conn.cursor)) async def commit(self) -> None: """Commit the current transaction.""" await self._execute(self._conn.commit) async def rollback(self) -> None: """Roll back the current transaction.""" await self._execute(self._conn.rollback) async def close(self) -> None: """Complete queued queries/cursors and close the connection.""" await self._execute(self._conn.close) self._running = False self._connection = None @contextmanager async def execute(self, sql: str, parameters: Iterable[Any] = None) -> Cursor: """Helper to create a cursor and execute the given query.""" if parameters is None: parameters = [] cursor = await self._execute(self._conn.execute, sql, parameters) return Cursor(self, cursor) @contextmanager async def execute_insert( self, sql: str, parameters: Iterable[Any] = None ) -> Optional[sqlite3.Row]: """Helper to insert and get the last_insert_rowid.""" if parameters is None: parameters = [] return await self._execute(self._execute_insert, sql, parameters) @contextmanager @contextmanager async def executemany( self, sql: str, parameters: Iterable[Iterable[Any]] ) -> Cursor: """Helper to create a cursor and execute the given multiquery.""" cursor = await self._execute(self._conn.executemany, sql, parameters) return Cursor(self, cursor) @contextmanager async def executescript(self, sql_script: str) -> Cursor: """Helper to create a cursor and execute a user script.""" cursor = await self._execute(self._conn.executescript, sql_script) return Cursor(self, cursor) async def interrupt(self) -> None: """Interrupt pending queries.""" return self._conn.interrupt() @property def in_transaction(self) -> bool: return self._conn.in_transaction @property def isolation_level(self) -> str: return self._conn.isolation_level @isolation_level.setter def isolation_level(self, value: str) -> None: self._conn.isolation_level = value @property def row_factory(self) -> "Optional[Type]": # py3.5.2 compat (#24) return self._conn.row_factory @row_factory.setter def row_factory(self, factory: "Optional[Type]") -> None: # py3.5.2 compat (#24) self._conn.row_factory = factory @property def text_factory(self) -> Type: return self._conn.text_factory @text_factory.setter def text_factory(self, factory: Type) -> None: self._conn.text_factory = factory @property def total_changes(self) -> int: return self._conn.total_changes async def enable_load_extension(self, value: bool) -> None: await self._execute(self._conn.enable_load_extension, value) # type: ignore async def load_extension(self, path: str): await self._execute(self._conn.load_extension, path) # type: ignore
jreese/aiosqlite
aiosqlite/core.py
Connection.executemany
python
async def executemany( self, sql: str, parameters: Iterable[Iterable[Any]] ) -> Cursor: cursor = await self._execute(self._conn.executemany, sql, parameters) return Cursor(self, cursor)
Helper to create a cursor and execute the given multiquery.
train
https://github.com/jreese/aiosqlite/blob/3f548b568b8db9a57022b6e2c9627f5cdefb983f/aiosqlite/core.py#L231-L236
[ "async def _execute(self, fn, *args, **kwargs):\n \"\"\"Queue a function with the given arguments for execution.\"\"\"\n function = partial(fn, *args, **kwargs)\n future = self._loop.create_future()\n\n self._tx.put_nowait((future, function))\n\n return await future\n" ]
class Connection(Thread): def __init__( self, connector: Callable[[], sqlite3.Connection], loop: asyncio.AbstractEventLoop, ) -> None: super().__init__() self._running = True self._connection = None # type: Optional[sqlite3.Connection] self._connector = connector self._loop = loop self._tx = Queue() # type: Queue @property def _conn(self) -> sqlite3.Connection: if self._connection is None: raise ValueError("no active connection") return self._connection def _execute_insert( self, sql: str, parameters: Iterable[Any] ) -> Optional[sqlite3.Row]: cursor = self._conn.execute(sql, parameters) cursor.execute("SELECT last_insert_rowid()") return cursor.fetchone() def _execute_fetchall( self, sql: str, parameters: Iterable[Any] ) -> Iterable[sqlite3.Row]: cursor = self._conn.execute(sql, parameters) return cursor.fetchall() def run(self) -> None: """Execute function calls on a separate thread.""" while self._running: try: future, function = self._tx.get(timeout=0.1) except Empty: continue try: LOG.debug("executing %s", function) result = function() LOG.debug("returning %s", result) self._loop.call_soon_threadsafe(future.set_result, result) except BaseException as e: LOG.exception("returning exception %s", e) self._loop.call_soon_threadsafe(future.set_exception, e) async def _execute(self, fn, *args, **kwargs): """Queue a function with the given arguments for execution.""" function = partial(fn, *args, **kwargs) future = self._loop.create_future() self._tx.put_nowait((future, function)) return await future async def _connect(self) -> "Connection": """Connect to the actual sqlite database.""" if self._connection is None: self._connection = await self._execute(self._connector) return self def __await__(self) -> Generator[Any, None, "Connection"]: self.start() return self._connect().__await__() async def __aenter__(self) -> "Connection": return await self async def __aexit__(self, exc_type, exc_val, exc_tb) -> None: await self.close() @contextmanager async def cursor(self) -> Cursor: """Create an aiosqlite cursor wrapping a sqlite3 cursor object.""" return Cursor(self, await self._execute(self._conn.cursor)) async def commit(self) -> None: """Commit the current transaction.""" await self._execute(self._conn.commit) async def rollback(self) -> None: """Roll back the current transaction.""" await self._execute(self._conn.rollback) async def close(self) -> None: """Complete queued queries/cursors and close the connection.""" await self._execute(self._conn.close) self._running = False self._connection = None @contextmanager async def execute(self, sql: str, parameters: Iterable[Any] = None) -> Cursor: """Helper to create a cursor and execute the given query.""" if parameters is None: parameters = [] cursor = await self._execute(self._conn.execute, sql, parameters) return Cursor(self, cursor) @contextmanager async def execute_insert( self, sql: str, parameters: Iterable[Any] = None ) -> Optional[sqlite3.Row]: """Helper to insert and get the last_insert_rowid.""" if parameters is None: parameters = [] return await self._execute(self._execute_insert, sql, parameters) @contextmanager async def execute_fetchall( self, sql: str, parameters: Iterable[Any] = None ) -> Iterable[sqlite3.Row]: """Helper to execute a query and return all the data.""" if parameters is None: parameters = [] return await self._execute(self._execute_fetchall, sql, parameters) @contextmanager @contextmanager async def executescript(self, sql_script: str) -> Cursor: """Helper to create a cursor and execute a user script.""" cursor = await self._execute(self._conn.executescript, sql_script) return Cursor(self, cursor) async def interrupt(self) -> None: """Interrupt pending queries.""" return self._conn.interrupt() @property def in_transaction(self) -> bool: return self._conn.in_transaction @property def isolation_level(self) -> str: return self._conn.isolation_level @isolation_level.setter def isolation_level(self, value: str) -> None: self._conn.isolation_level = value @property def row_factory(self) -> "Optional[Type]": # py3.5.2 compat (#24) return self._conn.row_factory @row_factory.setter def row_factory(self, factory: "Optional[Type]") -> None: # py3.5.2 compat (#24) self._conn.row_factory = factory @property def text_factory(self) -> Type: return self._conn.text_factory @text_factory.setter def text_factory(self, factory: Type) -> None: self._conn.text_factory = factory @property def total_changes(self) -> int: return self._conn.total_changes async def enable_load_extension(self, value: bool) -> None: await self._execute(self._conn.enable_load_extension, value) # type: ignore async def load_extension(self, path: str): await self._execute(self._conn.load_extension, path) # type: ignore
jreese/aiosqlite
aiosqlite/core.py
Connection.executescript
python
async def executescript(self, sql_script: str) -> Cursor: cursor = await self._execute(self._conn.executescript, sql_script) return Cursor(self, cursor)
Helper to create a cursor and execute a user script.
train
https://github.com/jreese/aiosqlite/blob/3f548b568b8db9a57022b6e2c9627f5cdefb983f/aiosqlite/core.py#L239-L242
[ "async def _execute(self, fn, *args, **kwargs):\n \"\"\"Queue a function with the given arguments for execution.\"\"\"\n function = partial(fn, *args, **kwargs)\n future = self._loop.create_future()\n\n self._tx.put_nowait((future, function))\n\n return await future\n" ]
class Connection(Thread): def __init__( self, connector: Callable[[], sqlite3.Connection], loop: asyncio.AbstractEventLoop, ) -> None: super().__init__() self._running = True self._connection = None # type: Optional[sqlite3.Connection] self._connector = connector self._loop = loop self._tx = Queue() # type: Queue @property def _conn(self) -> sqlite3.Connection: if self._connection is None: raise ValueError("no active connection") return self._connection def _execute_insert( self, sql: str, parameters: Iterable[Any] ) -> Optional[sqlite3.Row]: cursor = self._conn.execute(sql, parameters) cursor.execute("SELECT last_insert_rowid()") return cursor.fetchone() def _execute_fetchall( self, sql: str, parameters: Iterable[Any] ) -> Iterable[sqlite3.Row]: cursor = self._conn.execute(sql, parameters) return cursor.fetchall() def run(self) -> None: """Execute function calls on a separate thread.""" while self._running: try: future, function = self._tx.get(timeout=0.1) except Empty: continue try: LOG.debug("executing %s", function) result = function() LOG.debug("returning %s", result) self._loop.call_soon_threadsafe(future.set_result, result) except BaseException as e: LOG.exception("returning exception %s", e) self._loop.call_soon_threadsafe(future.set_exception, e) async def _execute(self, fn, *args, **kwargs): """Queue a function with the given arguments for execution.""" function = partial(fn, *args, **kwargs) future = self._loop.create_future() self._tx.put_nowait((future, function)) return await future async def _connect(self) -> "Connection": """Connect to the actual sqlite database.""" if self._connection is None: self._connection = await self._execute(self._connector) return self def __await__(self) -> Generator[Any, None, "Connection"]: self.start() return self._connect().__await__() async def __aenter__(self) -> "Connection": return await self async def __aexit__(self, exc_type, exc_val, exc_tb) -> None: await self.close() @contextmanager async def cursor(self) -> Cursor: """Create an aiosqlite cursor wrapping a sqlite3 cursor object.""" return Cursor(self, await self._execute(self._conn.cursor)) async def commit(self) -> None: """Commit the current transaction.""" await self._execute(self._conn.commit) async def rollback(self) -> None: """Roll back the current transaction.""" await self._execute(self._conn.rollback) async def close(self) -> None: """Complete queued queries/cursors and close the connection.""" await self._execute(self._conn.close) self._running = False self._connection = None @contextmanager async def execute(self, sql: str, parameters: Iterable[Any] = None) -> Cursor: """Helper to create a cursor and execute the given query.""" if parameters is None: parameters = [] cursor = await self._execute(self._conn.execute, sql, parameters) return Cursor(self, cursor) @contextmanager async def execute_insert( self, sql: str, parameters: Iterable[Any] = None ) -> Optional[sqlite3.Row]: """Helper to insert and get the last_insert_rowid.""" if parameters is None: parameters = [] return await self._execute(self._execute_insert, sql, parameters) @contextmanager async def execute_fetchall( self, sql: str, parameters: Iterable[Any] = None ) -> Iterable[sqlite3.Row]: """Helper to execute a query and return all the data.""" if parameters is None: parameters = [] return await self._execute(self._execute_fetchall, sql, parameters) @contextmanager async def executemany( self, sql: str, parameters: Iterable[Iterable[Any]] ) -> Cursor: """Helper to create a cursor and execute the given multiquery.""" cursor = await self._execute(self._conn.executemany, sql, parameters) return Cursor(self, cursor) @contextmanager async def interrupt(self) -> None: """Interrupt pending queries.""" return self._conn.interrupt() @property def in_transaction(self) -> bool: return self._conn.in_transaction @property def isolation_level(self) -> str: return self._conn.isolation_level @isolation_level.setter def isolation_level(self, value: str) -> None: self._conn.isolation_level = value @property def row_factory(self) -> "Optional[Type]": # py3.5.2 compat (#24) return self._conn.row_factory @row_factory.setter def row_factory(self, factory: "Optional[Type]") -> None: # py3.5.2 compat (#24) self._conn.row_factory = factory @property def text_factory(self) -> Type: return self._conn.text_factory @text_factory.setter def text_factory(self, factory: Type) -> None: self._conn.text_factory = factory @property def total_changes(self) -> int: return self._conn.total_changes async def enable_load_extension(self, value: bool) -> None: await self._execute(self._conn.enable_load_extension, value) # type: ignore async def load_extension(self, path: str): await self._execute(self._conn.load_extension, path) # type: ignore
mzucker/noteshrink
noteshrink.py
quantize
python
def quantize(image, bits_per_channel=None): '''Reduces the number of bits per channel in the given image.''' if bits_per_channel is None: bits_per_channel = 6 assert image.dtype == np.uint8 shift = 8-bits_per_channel halfbin = (1 << shift) >> 1 return ((image.astype(int) >> shift) << shift) + halfbin
Reduces the number of bits per channel in the given image.
train
https://github.com/mzucker/noteshrink/blob/7d876e5b43923c6bf8d64b7ef18f6855bfb30ce3/noteshrink.py#L27-L39
null
#!/usr/bin/env python '''Converts sequence of images to compact PDF while removing speckles, bleedthrough, etc. ''' # for some reason pylint complains about members being undefined :( # pylint: disable=E1101 from __future__ import print_function import sys import os import re import subprocess import shlex from argparse import ArgumentParser import numpy as np from PIL import Image from scipy.cluster.vq import kmeans, vq ###################################################################### ###################################################################### def pack_rgb(rgb): '''Packs a 24-bit RGB triples into a single integer, works on both arrays and tuples.''' orig_shape = None if isinstance(rgb, np.ndarray): assert rgb.shape[-1] == 3 orig_shape = rgb.shape[:-1] else: assert len(rgb) == 3 rgb = np.array(rgb) rgb = rgb.astype(int).reshape((-1, 3)) packed = (rgb[:, 0] << 16 | rgb[:, 1] << 8 | rgb[:, 2]) if orig_shape is None: return packed else: return packed.reshape(orig_shape) ###################################################################### def unpack_rgb(packed): '''Unpacks a single integer or array of integers into one or more 24-bit RGB values. ''' orig_shape = None if isinstance(packed, np.ndarray): assert packed.dtype == int orig_shape = packed.shape packed = packed.reshape((-1, 1)) rgb = ((packed >> 16) & 0xff, (packed >> 8) & 0xff, (packed) & 0xff) if orig_shape is None: return rgb else: return np.hstack(rgb).reshape(orig_shape + (3,)) ###################################################################### def get_bg_color(image, bits_per_channel=None): '''Obtains the background color from an image or array of RGB colors by grouping similar colors into bins and finding the most frequent one. ''' assert image.shape[-1] == 3 quantized = quantize(image, bits_per_channel).astype(int) packed = pack_rgb(quantized) unique, counts = np.unique(packed, return_counts=True) packed_mode = unique[counts.argmax()] return unpack_rgb(packed_mode) ###################################################################### def rgb_to_sv(rgb): '''Convert an RGB image or array of RGB colors to saturation and value, returning each one as a separate 32-bit floating point array or value. ''' if not isinstance(rgb, np.ndarray): rgb = np.array(rgb) axis = len(rgb.shape)-1 cmax = rgb.max(axis=axis).astype(np.float32) cmin = rgb.min(axis=axis).astype(np.float32) delta = cmax - cmin saturation = delta.astype(np.float32) / cmax.astype(np.float32) saturation = np.where(cmax == 0, 0, saturation) value = cmax/255.0 return saturation, value ###################################################################### def postprocess(output_filename, options): '''Runs the postprocessing command on the file provided.''' assert options.postprocess_cmd base, _ = os.path.splitext(output_filename) post_filename = base + options.postprocess_ext cmd = options.postprocess_cmd cmd = cmd.replace('%i', output_filename) cmd = cmd.replace('%o', post_filename) cmd = cmd.replace('%e', options.postprocess_ext) subprocess_args = shlex.split(cmd) if os.path.exists(post_filename): os.unlink(post_filename) if not options.quiet: print(' running "{}"...'.format(cmd), end=' ') sys.stdout.flush() try: result = subprocess.call(subprocess_args) before = os.stat(output_filename).st_size after = os.stat(post_filename).st_size except OSError: result = -1 if result == 0: if not options.quiet: print('{:.1f}% reduction'.format( 100*(1.0-float(after)/before))) return post_filename else: sys.stderr.write('warning: postprocessing failed!\n') return None ###################################################################### def percent(string): '''Convert a string (i.e. 85) to a fraction (i.e. .85).''' return float(string)/100.0 ###################################################################### def get_argument_parser(): '''Parse the command-line arguments for this program.''' parser = ArgumentParser( description='convert scanned, hand-written notes to PDF') show_default = ' (default %(default)s)' parser.add_argument('filenames', metavar='IMAGE', nargs='+', help='files to convert') parser.add_argument('-q', dest='quiet', action='store_true', default=False, help='reduce program output') parser.add_argument('-b', dest='basename', metavar='BASENAME', default='page', help='output PNG filename base' + show_default) parser.add_argument('-o', dest='pdfname', metavar='PDF', default='output.pdf', help='output PDF filename' + show_default) parser.add_argument('-v', dest='value_threshold', metavar='PERCENT', type=percent, default='25', help='background value threshold %%'+show_default) parser.add_argument('-s', dest='sat_threshold', metavar='PERCENT', type=percent, default='20', help='background saturation ' 'threshold %%'+show_default) parser.add_argument('-n', dest='num_colors', type=int, default='8', help='number of output colors '+show_default) parser.add_argument('-p', dest='sample_fraction', metavar='PERCENT', type=percent, default='5', help='%% of pixels to sample' + show_default) parser.add_argument('-w', dest='white_bg', action='store_true', default=False, help='make background white') parser.add_argument('-g', dest='global_palette', action='store_true', default=False, help='use one global palette for all pages') parser.add_argument('-S', dest='saturate', action='store_false', default=True, help='do not saturate colors') parser.add_argument('-K', dest='sort_numerically', action='store_false', default=True, help='keep filenames ordered as specified; ' 'use if you *really* want IMG_10.png to ' 'precede IMG_2.png') parser.add_argument('-P', dest='postprocess_cmd', default=None, help='set postprocessing command (see -O, -C, -Q)') parser.add_argument('-e', dest='postprocess_ext', default='_post.png', help='filename suffix/extension for ' 'postprocessing command') parser.add_argument('-O', dest='postprocess_cmd', action='store_const', const='optipng -silent %i -out %o', help='same as -P "%(const)s"') parser.add_argument('-C', dest='postprocess_cmd', action='store_const', const='pngcrush -q %i %o', help='same as -P "%(const)s"') parser.add_argument('-Q', dest='postprocess_cmd', action='store_const', const='pngquant --ext %e %i', help='same as -P "%(const)s"') parser.add_argument('-c', dest='pdf_cmd', metavar="COMMAND", default='convert %i %o', help='PDF command (default "%(default)s")') return parser ###################################################################### def get_filenames(options): '''Get the filenames from the command line, optionally sorted by number, so that IMG_10.png is re-arranged to come after IMG_9.png. This is a nice feature because some scanner programs (like Image Capture on Mac OS X) automatically number files without leading zeros, and this way you can supply files using a wildcard and still have the pages ordered correctly. ''' if not options.sort_numerically: return options.filenames filenames = [] for filename in options.filenames: basename = os.path.basename(filename) root, _ = os.path.splitext(basename) matches = re.findall(r'[0-9]+', root) if matches: num = int(matches[-1]) else: num = -1 filenames.append((num, filename)) return [fn for (_, fn) in sorted(filenames)] ###################################################################### def load(input_filename): '''Load an image with Pillow and convert it to numpy array. Also returns the image DPI in x and y as a tuple.''' try: pil_img = Image.open(input_filename) except IOError: sys.stderr.write('warning: error opening {}\n'.format( input_filename)) return None, None if pil_img.mode != 'RGB': pil_img = pil_img.convert('RGB') if 'dpi' in pil_img.info: dpi = pil_img.info['dpi'] else: dpi = (300, 300) img = np.array(pil_img) return img, dpi ###################################################################### def sample_pixels(img, options): '''Pick a fixed percentage of pixels in the image, returned in random order.''' pixels = img.reshape((-1, 3)) num_pixels = pixels.shape[0] num_samples = int(num_pixels*options.sample_fraction) idx = np.arange(num_pixels) np.random.shuffle(idx) return pixels[idx[:num_samples]] ###################################################################### def get_fg_mask(bg_color, samples, options): '''Determine whether each pixel in a set of samples is foreground by comparing it to the background color. A pixel is classified as a foreground pixel if either its value or saturation differs from the background by a threshold.''' s_bg, v_bg = rgb_to_sv(bg_color) s_samples, v_samples = rgb_to_sv(samples) s_diff = np.abs(s_bg - s_samples) v_diff = np.abs(v_bg - v_samples) return ((v_diff >= options.value_threshold) | (s_diff >= options.sat_threshold)) ###################################################################### def get_palette(samples, options, return_mask=False, kmeans_iter=40): '''Extract the palette for the set of sampled RGB values. The first palette entry is always the background color; the rest are determined from foreground pixels by running K-means clustering. Returns the palette, as well as a mask corresponding to the foreground pixels. ''' if not options.quiet: print(' getting palette...') bg_color = get_bg_color(samples, 6) fg_mask = get_fg_mask(bg_color, samples, options) centers, _ = kmeans(samples[fg_mask].astype(np.float32), options.num_colors-1, iter=kmeans_iter) palette = np.vstack((bg_color, centers)).astype(np.uint8) if not return_mask: return palette else: return palette, fg_mask ###################################################################### def apply_palette(img, palette, options): '''Apply the pallete to the given image. The first step is to set all background pixels to the background color; then, nearest-neighbor matching is used to map each foreground color to the closest one in the palette. ''' if not options.quiet: print(' applying palette...') bg_color = palette[0] fg_mask = get_fg_mask(bg_color, img, options) orig_shape = img.shape pixels = img.reshape((-1, 3)) fg_mask = fg_mask.flatten() num_pixels = pixels.shape[0] labels = np.zeros(num_pixels, dtype=np.uint8) labels[fg_mask], _ = vq(pixels[fg_mask], palette) return labels.reshape(orig_shape[:-1]) ###################################################################### def save(output_filename, labels, palette, dpi, options): '''Save the label/palette pair out as an indexed PNG image. This optionally saturates the pallete by mapping the smallest color component to zero and the largest one to 255, and also optionally sets the background color to pure white. ''' if not options.quiet: print(' saving {}...'.format(output_filename)) if options.saturate: palette = palette.astype(np.float32) pmin = palette.min() pmax = palette.max() palette = 255 * (palette - pmin)/(pmax-pmin) palette = palette.astype(np.uint8) if options.white_bg: palette = palette.copy() palette[0] = (255, 255, 255) output_img = Image.fromarray(labels, 'P') output_img.putpalette(palette.flatten()) output_img.save(output_filename, dpi=dpi) ###################################################################### def get_global_palette(filenames, options): '''Fetch the global palette for a series of input files by merging their samples together into one large array. ''' input_filenames = [] all_samples = [] if not options.quiet: print('building global palette...') for input_filename in filenames: img, _ = load(input_filename) if img is None: continue if not options.quiet: print(' processing {}...'.format(input_filename)) samples = sample_pixels(img, options) input_filenames.append(input_filename) all_samples.append(samples) num_inputs = len(input_filenames) all_samples = [s[:int(round(float(s.shape[0])/num_inputs))] for s in all_samples] all_samples = np.vstack(tuple(all_samples)) global_palette = get_palette(all_samples, options) if not options.quiet: print(' done\n') return input_filenames, global_palette ###################################################################### def emit_pdf(outputs, options): '''Runs the PDF conversion command to generate the PDF.''' cmd = options.pdf_cmd cmd = cmd.replace('%o', options.pdfname) if len(outputs) > 2: cmd_print = cmd.replace('%i', ' '.join(outputs[:2] + ['...'])) else: cmd_print = cmd.replace('%i', ' '.join(outputs)) cmd = cmd.replace('%i', ' '.join(outputs)) if not options.quiet: print('running PDF command "{}"...'.format(cmd_print)) try: result = subprocess.call(shlex.split(cmd)) except OSError: result = -1 if result == 0: if not options.quiet: print(' wrote', options.pdfname) else: sys.stderr.write('warning: PDF command failed\n') ###################################################################### def notescan_main(options): '''Main function for this program when run as script.''' filenames = get_filenames(options) outputs = [] do_global = options.global_palette and len(filenames) > 1 if do_global: filenames, palette = get_global_palette(filenames, options) do_postprocess = bool(options.postprocess_cmd) for input_filename in filenames: img, dpi = load(input_filename) if img is None: continue output_filename = '{}{:04d}.png'.format( options.basename, len(outputs)) if not options.quiet: print('opened', input_filename) if not do_global: samples = sample_pixels(img, options) palette = get_palette(samples, options) labels = apply_palette(img, palette, options) save(output_filename, labels, palette, dpi, options) if do_postprocess: post_filename = postprocess(output_filename, options) if post_filename: output_filename = post_filename else: do_postprocess = False outputs.append(output_filename) if not options.quiet: print(' done\n') emit_pdf(outputs, options) ###################################################################### def main(): '''Parse args and call notescan_main().''' notescan_main(options=get_argument_parser().parse_args()) if __name__ == '__main__': main()
mzucker/noteshrink
noteshrink.py
pack_rgb
python
def pack_rgb(rgb): '''Packs a 24-bit RGB triples into a single integer, works on both arrays and tuples.''' orig_shape = None if isinstance(rgb, np.ndarray): assert rgb.shape[-1] == 3 orig_shape = rgb.shape[:-1] else: assert len(rgb) == 3 rgb = np.array(rgb) rgb = rgb.astype(int).reshape((-1, 3)) packed = (rgb[:, 0] << 16 | rgb[:, 1] << 8 | rgb[:, 2]) if orig_shape is None: return packed else: return packed.reshape(orig_shape)
Packs a 24-bit RGB triples into a single integer, works on both arrays and tuples.
train
https://github.com/mzucker/noteshrink/blob/7d876e5b43923c6bf8d64b7ef18f6855bfb30ce3/noteshrink.py#L43-L66
null
#!/usr/bin/env python '''Converts sequence of images to compact PDF while removing speckles, bleedthrough, etc. ''' # for some reason pylint complains about members being undefined :( # pylint: disable=E1101 from __future__ import print_function import sys import os import re import subprocess import shlex from argparse import ArgumentParser import numpy as np from PIL import Image from scipy.cluster.vq import kmeans, vq ###################################################################### def quantize(image, bits_per_channel=None): '''Reduces the number of bits per channel in the given image.''' if bits_per_channel is None: bits_per_channel = 6 assert image.dtype == np.uint8 shift = 8-bits_per_channel halfbin = (1 << shift) >> 1 return ((image.astype(int) >> shift) << shift) + halfbin ###################################################################### ###################################################################### def unpack_rgb(packed): '''Unpacks a single integer or array of integers into one or more 24-bit RGB values. ''' orig_shape = None if isinstance(packed, np.ndarray): assert packed.dtype == int orig_shape = packed.shape packed = packed.reshape((-1, 1)) rgb = ((packed >> 16) & 0xff, (packed >> 8) & 0xff, (packed) & 0xff) if orig_shape is None: return rgb else: return np.hstack(rgb).reshape(orig_shape + (3,)) ###################################################################### def get_bg_color(image, bits_per_channel=None): '''Obtains the background color from an image or array of RGB colors by grouping similar colors into bins and finding the most frequent one. ''' assert image.shape[-1] == 3 quantized = quantize(image, bits_per_channel).astype(int) packed = pack_rgb(quantized) unique, counts = np.unique(packed, return_counts=True) packed_mode = unique[counts.argmax()] return unpack_rgb(packed_mode) ###################################################################### def rgb_to_sv(rgb): '''Convert an RGB image or array of RGB colors to saturation and value, returning each one as a separate 32-bit floating point array or value. ''' if not isinstance(rgb, np.ndarray): rgb = np.array(rgb) axis = len(rgb.shape)-1 cmax = rgb.max(axis=axis).astype(np.float32) cmin = rgb.min(axis=axis).astype(np.float32) delta = cmax - cmin saturation = delta.astype(np.float32) / cmax.astype(np.float32) saturation = np.where(cmax == 0, 0, saturation) value = cmax/255.0 return saturation, value ###################################################################### def postprocess(output_filename, options): '''Runs the postprocessing command on the file provided.''' assert options.postprocess_cmd base, _ = os.path.splitext(output_filename) post_filename = base + options.postprocess_ext cmd = options.postprocess_cmd cmd = cmd.replace('%i', output_filename) cmd = cmd.replace('%o', post_filename) cmd = cmd.replace('%e', options.postprocess_ext) subprocess_args = shlex.split(cmd) if os.path.exists(post_filename): os.unlink(post_filename) if not options.quiet: print(' running "{}"...'.format(cmd), end=' ') sys.stdout.flush() try: result = subprocess.call(subprocess_args) before = os.stat(output_filename).st_size after = os.stat(post_filename).st_size except OSError: result = -1 if result == 0: if not options.quiet: print('{:.1f}% reduction'.format( 100*(1.0-float(after)/before))) return post_filename else: sys.stderr.write('warning: postprocessing failed!\n') return None ###################################################################### def percent(string): '''Convert a string (i.e. 85) to a fraction (i.e. .85).''' return float(string)/100.0 ###################################################################### def get_argument_parser(): '''Parse the command-line arguments for this program.''' parser = ArgumentParser( description='convert scanned, hand-written notes to PDF') show_default = ' (default %(default)s)' parser.add_argument('filenames', metavar='IMAGE', nargs='+', help='files to convert') parser.add_argument('-q', dest='quiet', action='store_true', default=False, help='reduce program output') parser.add_argument('-b', dest='basename', metavar='BASENAME', default='page', help='output PNG filename base' + show_default) parser.add_argument('-o', dest='pdfname', metavar='PDF', default='output.pdf', help='output PDF filename' + show_default) parser.add_argument('-v', dest='value_threshold', metavar='PERCENT', type=percent, default='25', help='background value threshold %%'+show_default) parser.add_argument('-s', dest='sat_threshold', metavar='PERCENT', type=percent, default='20', help='background saturation ' 'threshold %%'+show_default) parser.add_argument('-n', dest='num_colors', type=int, default='8', help='number of output colors '+show_default) parser.add_argument('-p', dest='sample_fraction', metavar='PERCENT', type=percent, default='5', help='%% of pixels to sample' + show_default) parser.add_argument('-w', dest='white_bg', action='store_true', default=False, help='make background white') parser.add_argument('-g', dest='global_palette', action='store_true', default=False, help='use one global palette for all pages') parser.add_argument('-S', dest='saturate', action='store_false', default=True, help='do not saturate colors') parser.add_argument('-K', dest='sort_numerically', action='store_false', default=True, help='keep filenames ordered as specified; ' 'use if you *really* want IMG_10.png to ' 'precede IMG_2.png') parser.add_argument('-P', dest='postprocess_cmd', default=None, help='set postprocessing command (see -O, -C, -Q)') parser.add_argument('-e', dest='postprocess_ext', default='_post.png', help='filename suffix/extension for ' 'postprocessing command') parser.add_argument('-O', dest='postprocess_cmd', action='store_const', const='optipng -silent %i -out %o', help='same as -P "%(const)s"') parser.add_argument('-C', dest='postprocess_cmd', action='store_const', const='pngcrush -q %i %o', help='same as -P "%(const)s"') parser.add_argument('-Q', dest='postprocess_cmd', action='store_const', const='pngquant --ext %e %i', help='same as -P "%(const)s"') parser.add_argument('-c', dest='pdf_cmd', metavar="COMMAND", default='convert %i %o', help='PDF command (default "%(default)s")') return parser ###################################################################### def get_filenames(options): '''Get the filenames from the command line, optionally sorted by number, so that IMG_10.png is re-arranged to come after IMG_9.png. This is a nice feature because some scanner programs (like Image Capture on Mac OS X) automatically number files without leading zeros, and this way you can supply files using a wildcard and still have the pages ordered correctly. ''' if not options.sort_numerically: return options.filenames filenames = [] for filename in options.filenames: basename = os.path.basename(filename) root, _ = os.path.splitext(basename) matches = re.findall(r'[0-9]+', root) if matches: num = int(matches[-1]) else: num = -1 filenames.append((num, filename)) return [fn for (_, fn) in sorted(filenames)] ###################################################################### def load(input_filename): '''Load an image with Pillow and convert it to numpy array. Also returns the image DPI in x and y as a tuple.''' try: pil_img = Image.open(input_filename) except IOError: sys.stderr.write('warning: error opening {}\n'.format( input_filename)) return None, None if pil_img.mode != 'RGB': pil_img = pil_img.convert('RGB') if 'dpi' in pil_img.info: dpi = pil_img.info['dpi'] else: dpi = (300, 300) img = np.array(pil_img) return img, dpi ###################################################################### def sample_pixels(img, options): '''Pick a fixed percentage of pixels in the image, returned in random order.''' pixels = img.reshape((-1, 3)) num_pixels = pixels.shape[0] num_samples = int(num_pixels*options.sample_fraction) idx = np.arange(num_pixels) np.random.shuffle(idx) return pixels[idx[:num_samples]] ###################################################################### def get_fg_mask(bg_color, samples, options): '''Determine whether each pixel in a set of samples is foreground by comparing it to the background color. A pixel is classified as a foreground pixel if either its value or saturation differs from the background by a threshold.''' s_bg, v_bg = rgb_to_sv(bg_color) s_samples, v_samples = rgb_to_sv(samples) s_diff = np.abs(s_bg - s_samples) v_diff = np.abs(v_bg - v_samples) return ((v_diff >= options.value_threshold) | (s_diff >= options.sat_threshold)) ###################################################################### def get_palette(samples, options, return_mask=False, kmeans_iter=40): '''Extract the palette for the set of sampled RGB values. The first palette entry is always the background color; the rest are determined from foreground pixels by running K-means clustering. Returns the palette, as well as a mask corresponding to the foreground pixels. ''' if not options.quiet: print(' getting palette...') bg_color = get_bg_color(samples, 6) fg_mask = get_fg_mask(bg_color, samples, options) centers, _ = kmeans(samples[fg_mask].astype(np.float32), options.num_colors-1, iter=kmeans_iter) palette = np.vstack((bg_color, centers)).astype(np.uint8) if not return_mask: return palette else: return palette, fg_mask ###################################################################### def apply_palette(img, palette, options): '''Apply the pallete to the given image. The first step is to set all background pixels to the background color; then, nearest-neighbor matching is used to map each foreground color to the closest one in the palette. ''' if not options.quiet: print(' applying palette...') bg_color = palette[0] fg_mask = get_fg_mask(bg_color, img, options) orig_shape = img.shape pixels = img.reshape((-1, 3)) fg_mask = fg_mask.flatten() num_pixels = pixels.shape[0] labels = np.zeros(num_pixels, dtype=np.uint8) labels[fg_mask], _ = vq(pixels[fg_mask], palette) return labels.reshape(orig_shape[:-1]) ###################################################################### def save(output_filename, labels, palette, dpi, options): '''Save the label/palette pair out as an indexed PNG image. This optionally saturates the pallete by mapping the smallest color component to zero and the largest one to 255, and also optionally sets the background color to pure white. ''' if not options.quiet: print(' saving {}...'.format(output_filename)) if options.saturate: palette = palette.astype(np.float32) pmin = palette.min() pmax = palette.max() palette = 255 * (palette - pmin)/(pmax-pmin) palette = palette.astype(np.uint8) if options.white_bg: palette = palette.copy() palette[0] = (255, 255, 255) output_img = Image.fromarray(labels, 'P') output_img.putpalette(palette.flatten()) output_img.save(output_filename, dpi=dpi) ###################################################################### def get_global_palette(filenames, options): '''Fetch the global palette for a series of input files by merging their samples together into one large array. ''' input_filenames = [] all_samples = [] if not options.quiet: print('building global palette...') for input_filename in filenames: img, _ = load(input_filename) if img is None: continue if not options.quiet: print(' processing {}...'.format(input_filename)) samples = sample_pixels(img, options) input_filenames.append(input_filename) all_samples.append(samples) num_inputs = len(input_filenames) all_samples = [s[:int(round(float(s.shape[0])/num_inputs))] for s in all_samples] all_samples = np.vstack(tuple(all_samples)) global_palette = get_palette(all_samples, options) if not options.quiet: print(' done\n') return input_filenames, global_palette ###################################################################### def emit_pdf(outputs, options): '''Runs the PDF conversion command to generate the PDF.''' cmd = options.pdf_cmd cmd = cmd.replace('%o', options.pdfname) if len(outputs) > 2: cmd_print = cmd.replace('%i', ' '.join(outputs[:2] + ['...'])) else: cmd_print = cmd.replace('%i', ' '.join(outputs)) cmd = cmd.replace('%i', ' '.join(outputs)) if not options.quiet: print('running PDF command "{}"...'.format(cmd_print)) try: result = subprocess.call(shlex.split(cmd)) except OSError: result = -1 if result == 0: if not options.quiet: print(' wrote', options.pdfname) else: sys.stderr.write('warning: PDF command failed\n') ###################################################################### def notescan_main(options): '''Main function for this program when run as script.''' filenames = get_filenames(options) outputs = [] do_global = options.global_palette and len(filenames) > 1 if do_global: filenames, palette = get_global_palette(filenames, options) do_postprocess = bool(options.postprocess_cmd) for input_filename in filenames: img, dpi = load(input_filename) if img is None: continue output_filename = '{}{:04d}.png'.format( options.basename, len(outputs)) if not options.quiet: print('opened', input_filename) if not do_global: samples = sample_pixels(img, options) palette = get_palette(samples, options) labels = apply_palette(img, palette, options) save(output_filename, labels, palette, dpi, options) if do_postprocess: post_filename = postprocess(output_filename, options) if post_filename: output_filename = post_filename else: do_postprocess = False outputs.append(output_filename) if not options.quiet: print(' done\n') emit_pdf(outputs, options) ###################################################################### def main(): '''Parse args and call notescan_main().''' notescan_main(options=get_argument_parser().parse_args()) if __name__ == '__main__': main()
mzucker/noteshrink
noteshrink.py
unpack_rgb
python
def unpack_rgb(packed): '''Unpacks a single integer or array of integers into one or more 24-bit RGB values. ''' orig_shape = None if isinstance(packed, np.ndarray): assert packed.dtype == int orig_shape = packed.shape packed = packed.reshape((-1, 1)) rgb = ((packed >> 16) & 0xff, (packed >> 8) & 0xff, (packed) & 0xff) if orig_shape is None: return rgb else: return np.hstack(rgb).reshape(orig_shape + (3,))
Unpacks a single integer or array of integers into one or more 24-bit RGB values.
train
https://github.com/mzucker/noteshrink/blob/7d876e5b43923c6bf8d64b7ef18f6855bfb30ce3/noteshrink.py#L70-L91
null
#!/usr/bin/env python '''Converts sequence of images to compact PDF while removing speckles, bleedthrough, etc. ''' # for some reason pylint complains about members being undefined :( # pylint: disable=E1101 from __future__ import print_function import sys import os import re import subprocess import shlex from argparse import ArgumentParser import numpy as np from PIL import Image from scipy.cluster.vq import kmeans, vq ###################################################################### def quantize(image, bits_per_channel=None): '''Reduces the number of bits per channel in the given image.''' if bits_per_channel is None: bits_per_channel = 6 assert image.dtype == np.uint8 shift = 8-bits_per_channel halfbin = (1 << shift) >> 1 return ((image.astype(int) >> shift) << shift) + halfbin ###################################################################### def pack_rgb(rgb): '''Packs a 24-bit RGB triples into a single integer, works on both arrays and tuples.''' orig_shape = None if isinstance(rgb, np.ndarray): assert rgb.shape[-1] == 3 orig_shape = rgb.shape[:-1] else: assert len(rgb) == 3 rgb = np.array(rgb) rgb = rgb.astype(int).reshape((-1, 3)) packed = (rgb[:, 0] << 16 | rgb[:, 1] << 8 | rgb[:, 2]) if orig_shape is None: return packed else: return packed.reshape(orig_shape) ###################################################################### ###################################################################### def get_bg_color(image, bits_per_channel=None): '''Obtains the background color from an image or array of RGB colors by grouping similar colors into bins and finding the most frequent one. ''' assert image.shape[-1] == 3 quantized = quantize(image, bits_per_channel).astype(int) packed = pack_rgb(quantized) unique, counts = np.unique(packed, return_counts=True) packed_mode = unique[counts.argmax()] return unpack_rgb(packed_mode) ###################################################################### def rgb_to_sv(rgb): '''Convert an RGB image or array of RGB colors to saturation and value, returning each one as a separate 32-bit floating point array or value. ''' if not isinstance(rgb, np.ndarray): rgb = np.array(rgb) axis = len(rgb.shape)-1 cmax = rgb.max(axis=axis).astype(np.float32) cmin = rgb.min(axis=axis).astype(np.float32) delta = cmax - cmin saturation = delta.astype(np.float32) / cmax.astype(np.float32) saturation = np.where(cmax == 0, 0, saturation) value = cmax/255.0 return saturation, value ###################################################################### def postprocess(output_filename, options): '''Runs the postprocessing command on the file provided.''' assert options.postprocess_cmd base, _ = os.path.splitext(output_filename) post_filename = base + options.postprocess_ext cmd = options.postprocess_cmd cmd = cmd.replace('%i', output_filename) cmd = cmd.replace('%o', post_filename) cmd = cmd.replace('%e', options.postprocess_ext) subprocess_args = shlex.split(cmd) if os.path.exists(post_filename): os.unlink(post_filename) if not options.quiet: print(' running "{}"...'.format(cmd), end=' ') sys.stdout.flush() try: result = subprocess.call(subprocess_args) before = os.stat(output_filename).st_size after = os.stat(post_filename).st_size except OSError: result = -1 if result == 0: if not options.quiet: print('{:.1f}% reduction'.format( 100*(1.0-float(after)/before))) return post_filename else: sys.stderr.write('warning: postprocessing failed!\n') return None ###################################################################### def percent(string): '''Convert a string (i.e. 85) to a fraction (i.e. .85).''' return float(string)/100.0 ###################################################################### def get_argument_parser(): '''Parse the command-line arguments for this program.''' parser = ArgumentParser( description='convert scanned, hand-written notes to PDF') show_default = ' (default %(default)s)' parser.add_argument('filenames', metavar='IMAGE', nargs='+', help='files to convert') parser.add_argument('-q', dest='quiet', action='store_true', default=False, help='reduce program output') parser.add_argument('-b', dest='basename', metavar='BASENAME', default='page', help='output PNG filename base' + show_default) parser.add_argument('-o', dest='pdfname', metavar='PDF', default='output.pdf', help='output PDF filename' + show_default) parser.add_argument('-v', dest='value_threshold', metavar='PERCENT', type=percent, default='25', help='background value threshold %%'+show_default) parser.add_argument('-s', dest='sat_threshold', metavar='PERCENT', type=percent, default='20', help='background saturation ' 'threshold %%'+show_default) parser.add_argument('-n', dest='num_colors', type=int, default='8', help='number of output colors '+show_default) parser.add_argument('-p', dest='sample_fraction', metavar='PERCENT', type=percent, default='5', help='%% of pixels to sample' + show_default) parser.add_argument('-w', dest='white_bg', action='store_true', default=False, help='make background white') parser.add_argument('-g', dest='global_palette', action='store_true', default=False, help='use one global palette for all pages') parser.add_argument('-S', dest='saturate', action='store_false', default=True, help='do not saturate colors') parser.add_argument('-K', dest='sort_numerically', action='store_false', default=True, help='keep filenames ordered as specified; ' 'use if you *really* want IMG_10.png to ' 'precede IMG_2.png') parser.add_argument('-P', dest='postprocess_cmd', default=None, help='set postprocessing command (see -O, -C, -Q)') parser.add_argument('-e', dest='postprocess_ext', default='_post.png', help='filename suffix/extension for ' 'postprocessing command') parser.add_argument('-O', dest='postprocess_cmd', action='store_const', const='optipng -silent %i -out %o', help='same as -P "%(const)s"') parser.add_argument('-C', dest='postprocess_cmd', action='store_const', const='pngcrush -q %i %o', help='same as -P "%(const)s"') parser.add_argument('-Q', dest='postprocess_cmd', action='store_const', const='pngquant --ext %e %i', help='same as -P "%(const)s"') parser.add_argument('-c', dest='pdf_cmd', metavar="COMMAND", default='convert %i %o', help='PDF command (default "%(default)s")') return parser ###################################################################### def get_filenames(options): '''Get the filenames from the command line, optionally sorted by number, so that IMG_10.png is re-arranged to come after IMG_9.png. This is a nice feature because some scanner programs (like Image Capture on Mac OS X) automatically number files without leading zeros, and this way you can supply files using a wildcard and still have the pages ordered correctly. ''' if not options.sort_numerically: return options.filenames filenames = [] for filename in options.filenames: basename = os.path.basename(filename) root, _ = os.path.splitext(basename) matches = re.findall(r'[0-9]+', root) if matches: num = int(matches[-1]) else: num = -1 filenames.append((num, filename)) return [fn for (_, fn) in sorted(filenames)] ###################################################################### def load(input_filename): '''Load an image with Pillow and convert it to numpy array. Also returns the image DPI in x and y as a tuple.''' try: pil_img = Image.open(input_filename) except IOError: sys.stderr.write('warning: error opening {}\n'.format( input_filename)) return None, None if pil_img.mode != 'RGB': pil_img = pil_img.convert('RGB') if 'dpi' in pil_img.info: dpi = pil_img.info['dpi'] else: dpi = (300, 300) img = np.array(pil_img) return img, dpi ###################################################################### def sample_pixels(img, options): '''Pick a fixed percentage of pixels in the image, returned in random order.''' pixels = img.reshape((-1, 3)) num_pixels = pixels.shape[0] num_samples = int(num_pixels*options.sample_fraction) idx = np.arange(num_pixels) np.random.shuffle(idx) return pixels[idx[:num_samples]] ###################################################################### def get_fg_mask(bg_color, samples, options): '''Determine whether each pixel in a set of samples is foreground by comparing it to the background color. A pixel is classified as a foreground pixel if either its value or saturation differs from the background by a threshold.''' s_bg, v_bg = rgb_to_sv(bg_color) s_samples, v_samples = rgb_to_sv(samples) s_diff = np.abs(s_bg - s_samples) v_diff = np.abs(v_bg - v_samples) return ((v_diff >= options.value_threshold) | (s_diff >= options.sat_threshold)) ###################################################################### def get_palette(samples, options, return_mask=False, kmeans_iter=40): '''Extract the palette for the set of sampled RGB values. The first palette entry is always the background color; the rest are determined from foreground pixels by running K-means clustering. Returns the palette, as well as a mask corresponding to the foreground pixels. ''' if not options.quiet: print(' getting palette...') bg_color = get_bg_color(samples, 6) fg_mask = get_fg_mask(bg_color, samples, options) centers, _ = kmeans(samples[fg_mask].astype(np.float32), options.num_colors-1, iter=kmeans_iter) palette = np.vstack((bg_color, centers)).astype(np.uint8) if not return_mask: return palette else: return palette, fg_mask ###################################################################### def apply_palette(img, palette, options): '''Apply the pallete to the given image. The first step is to set all background pixels to the background color; then, nearest-neighbor matching is used to map each foreground color to the closest one in the palette. ''' if not options.quiet: print(' applying palette...') bg_color = palette[0] fg_mask = get_fg_mask(bg_color, img, options) orig_shape = img.shape pixels = img.reshape((-1, 3)) fg_mask = fg_mask.flatten() num_pixels = pixels.shape[0] labels = np.zeros(num_pixels, dtype=np.uint8) labels[fg_mask], _ = vq(pixels[fg_mask], palette) return labels.reshape(orig_shape[:-1]) ###################################################################### def save(output_filename, labels, palette, dpi, options): '''Save the label/palette pair out as an indexed PNG image. This optionally saturates the pallete by mapping the smallest color component to zero and the largest one to 255, and also optionally sets the background color to pure white. ''' if not options.quiet: print(' saving {}...'.format(output_filename)) if options.saturate: palette = palette.astype(np.float32) pmin = palette.min() pmax = palette.max() palette = 255 * (palette - pmin)/(pmax-pmin) palette = palette.astype(np.uint8) if options.white_bg: palette = palette.copy() palette[0] = (255, 255, 255) output_img = Image.fromarray(labels, 'P') output_img.putpalette(palette.flatten()) output_img.save(output_filename, dpi=dpi) ###################################################################### def get_global_palette(filenames, options): '''Fetch the global palette for a series of input files by merging their samples together into one large array. ''' input_filenames = [] all_samples = [] if not options.quiet: print('building global palette...') for input_filename in filenames: img, _ = load(input_filename) if img is None: continue if not options.quiet: print(' processing {}...'.format(input_filename)) samples = sample_pixels(img, options) input_filenames.append(input_filename) all_samples.append(samples) num_inputs = len(input_filenames) all_samples = [s[:int(round(float(s.shape[0])/num_inputs))] for s in all_samples] all_samples = np.vstack(tuple(all_samples)) global_palette = get_palette(all_samples, options) if not options.quiet: print(' done\n') return input_filenames, global_palette ###################################################################### def emit_pdf(outputs, options): '''Runs the PDF conversion command to generate the PDF.''' cmd = options.pdf_cmd cmd = cmd.replace('%o', options.pdfname) if len(outputs) > 2: cmd_print = cmd.replace('%i', ' '.join(outputs[:2] + ['...'])) else: cmd_print = cmd.replace('%i', ' '.join(outputs)) cmd = cmd.replace('%i', ' '.join(outputs)) if not options.quiet: print('running PDF command "{}"...'.format(cmd_print)) try: result = subprocess.call(shlex.split(cmd)) except OSError: result = -1 if result == 0: if not options.quiet: print(' wrote', options.pdfname) else: sys.stderr.write('warning: PDF command failed\n') ###################################################################### def notescan_main(options): '''Main function for this program when run as script.''' filenames = get_filenames(options) outputs = [] do_global = options.global_palette and len(filenames) > 1 if do_global: filenames, palette = get_global_palette(filenames, options) do_postprocess = bool(options.postprocess_cmd) for input_filename in filenames: img, dpi = load(input_filename) if img is None: continue output_filename = '{}{:04d}.png'.format( options.basename, len(outputs)) if not options.quiet: print('opened', input_filename) if not do_global: samples = sample_pixels(img, options) palette = get_palette(samples, options) labels = apply_palette(img, palette, options) save(output_filename, labels, palette, dpi, options) if do_postprocess: post_filename = postprocess(output_filename, options) if post_filename: output_filename = post_filename else: do_postprocess = False outputs.append(output_filename) if not options.quiet: print(' done\n') emit_pdf(outputs, options) ###################################################################### def main(): '''Parse args and call notescan_main().''' notescan_main(options=get_argument_parser().parse_args()) if __name__ == '__main__': main()
mzucker/noteshrink
noteshrink.py
get_bg_color
python
def get_bg_color(image, bits_per_channel=None): '''Obtains the background color from an image or array of RGB colors by grouping similar colors into bins and finding the most frequent one. ''' assert image.shape[-1] == 3 quantized = quantize(image, bits_per_channel).astype(int) packed = pack_rgb(quantized) unique, counts = np.unique(packed, return_counts=True) packed_mode = unique[counts.argmax()] return unpack_rgb(packed_mode)
Obtains the background color from an image or array of RGB colors by grouping similar colors into bins and finding the most frequent one.
train
https://github.com/mzucker/noteshrink/blob/7d876e5b43923c6bf8d64b7ef18f6855bfb30ce3/noteshrink.py#L95-L112
[ "def quantize(image, bits_per_channel=None):\n\n '''Reduces the number of bits per channel in the given image.'''\n\n if bits_per_channel is None:\n bits_per_channel = 6\n\n assert image.dtype == np.uint8\n\n shift = 8-bits_per_channel\n halfbin = (1 << shift) >> 1\n\n return ((image.astype(int) >> shift) << shift) + halfbin\n", "def pack_rgb(rgb):\n\n '''Packs a 24-bit RGB triples into a single integer,\nworks on both arrays and tuples.'''\n\n orig_shape = None\n\n if isinstance(rgb, np.ndarray):\n assert rgb.shape[-1] == 3\n orig_shape = rgb.shape[:-1]\n else:\n assert len(rgb) == 3\n rgb = np.array(rgb)\n\n rgb = rgb.astype(int).reshape((-1, 3))\n\n packed = (rgb[:, 0] << 16 |\n rgb[:, 1] << 8 |\n rgb[:, 2])\n\n if orig_shape is None:\n return packed\n else:\n return packed.reshape(orig_shape)\n", "def unpack_rgb(packed):\n\n '''Unpacks a single integer or array of integers into one or more\n24-bit RGB values.\n\n '''\n\n orig_shape = None\n\n if isinstance(packed, np.ndarray):\n assert packed.dtype == int\n orig_shape = packed.shape\n packed = packed.reshape((-1, 1))\n\n rgb = ((packed >> 16) & 0xff,\n (packed >> 8) & 0xff,\n (packed) & 0xff)\n\n if orig_shape is None:\n return rgb\n else:\n return np.hstack(rgb).reshape(orig_shape + (3,))\n" ]
#!/usr/bin/env python '''Converts sequence of images to compact PDF while removing speckles, bleedthrough, etc. ''' # for some reason pylint complains about members being undefined :( # pylint: disable=E1101 from __future__ import print_function import sys import os import re import subprocess import shlex from argparse import ArgumentParser import numpy as np from PIL import Image from scipy.cluster.vq import kmeans, vq ###################################################################### def quantize(image, bits_per_channel=None): '''Reduces the number of bits per channel in the given image.''' if bits_per_channel is None: bits_per_channel = 6 assert image.dtype == np.uint8 shift = 8-bits_per_channel halfbin = (1 << shift) >> 1 return ((image.astype(int) >> shift) << shift) + halfbin ###################################################################### def pack_rgb(rgb): '''Packs a 24-bit RGB triples into a single integer, works on both arrays and tuples.''' orig_shape = None if isinstance(rgb, np.ndarray): assert rgb.shape[-1] == 3 orig_shape = rgb.shape[:-1] else: assert len(rgb) == 3 rgb = np.array(rgb) rgb = rgb.astype(int).reshape((-1, 3)) packed = (rgb[:, 0] << 16 | rgb[:, 1] << 8 | rgb[:, 2]) if orig_shape is None: return packed else: return packed.reshape(orig_shape) ###################################################################### def unpack_rgb(packed): '''Unpacks a single integer or array of integers into one or more 24-bit RGB values. ''' orig_shape = None if isinstance(packed, np.ndarray): assert packed.dtype == int orig_shape = packed.shape packed = packed.reshape((-1, 1)) rgb = ((packed >> 16) & 0xff, (packed >> 8) & 0xff, (packed) & 0xff) if orig_shape is None: return rgb else: return np.hstack(rgb).reshape(orig_shape + (3,)) ###################################################################### ###################################################################### def rgb_to_sv(rgb): '''Convert an RGB image or array of RGB colors to saturation and value, returning each one as a separate 32-bit floating point array or value. ''' if not isinstance(rgb, np.ndarray): rgb = np.array(rgb) axis = len(rgb.shape)-1 cmax = rgb.max(axis=axis).astype(np.float32) cmin = rgb.min(axis=axis).astype(np.float32) delta = cmax - cmin saturation = delta.astype(np.float32) / cmax.astype(np.float32) saturation = np.where(cmax == 0, 0, saturation) value = cmax/255.0 return saturation, value ###################################################################### def postprocess(output_filename, options): '''Runs the postprocessing command on the file provided.''' assert options.postprocess_cmd base, _ = os.path.splitext(output_filename) post_filename = base + options.postprocess_ext cmd = options.postprocess_cmd cmd = cmd.replace('%i', output_filename) cmd = cmd.replace('%o', post_filename) cmd = cmd.replace('%e', options.postprocess_ext) subprocess_args = shlex.split(cmd) if os.path.exists(post_filename): os.unlink(post_filename) if not options.quiet: print(' running "{}"...'.format(cmd), end=' ') sys.stdout.flush() try: result = subprocess.call(subprocess_args) before = os.stat(output_filename).st_size after = os.stat(post_filename).st_size except OSError: result = -1 if result == 0: if not options.quiet: print('{:.1f}% reduction'.format( 100*(1.0-float(after)/before))) return post_filename else: sys.stderr.write('warning: postprocessing failed!\n') return None ###################################################################### def percent(string): '''Convert a string (i.e. 85) to a fraction (i.e. .85).''' return float(string)/100.0 ###################################################################### def get_argument_parser(): '''Parse the command-line arguments for this program.''' parser = ArgumentParser( description='convert scanned, hand-written notes to PDF') show_default = ' (default %(default)s)' parser.add_argument('filenames', metavar='IMAGE', nargs='+', help='files to convert') parser.add_argument('-q', dest='quiet', action='store_true', default=False, help='reduce program output') parser.add_argument('-b', dest='basename', metavar='BASENAME', default='page', help='output PNG filename base' + show_default) parser.add_argument('-o', dest='pdfname', metavar='PDF', default='output.pdf', help='output PDF filename' + show_default) parser.add_argument('-v', dest='value_threshold', metavar='PERCENT', type=percent, default='25', help='background value threshold %%'+show_default) parser.add_argument('-s', dest='sat_threshold', metavar='PERCENT', type=percent, default='20', help='background saturation ' 'threshold %%'+show_default) parser.add_argument('-n', dest='num_colors', type=int, default='8', help='number of output colors '+show_default) parser.add_argument('-p', dest='sample_fraction', metavar='PERCENT', type=percent, default='5', help='%% of pixels to sample' + show_default) parser.add_argument('-w', dest='white_bg', action='store_true', default=False, help='make background white') parser.add_argument('-g', dest='global_palette', action='store_true', default=False, help='use one global palette for all pages') parser.add_argument('-S', dest='saturate', action='store_false', default=True, help='do not saturate colors') parser.add_argument('-K', dest='sort_numerically', action='store_false', default=True, help='keep filenames ordered as specified; ' 'use if you *really* want IMG_10.png to ' 'precede IMG_2.png') parser.add_argument('-P', dest='postprocess_cmd', default=None, help='set postprocessing command (see -O, -C, -Q)') parser.add_argument('-e', dest='postprocess_ext', default='_post.png', help='filename suffix/extension for ' 'postprocessing command') parser.add_argument('-O', dest='postprocess_cmd', action='store_const', const='optipng -silent %i -out %o', help='same as -P "%(const)s"') parser.add_argument('-C', dest='postprocess_cmd', action='store_const', const='pngcrush -q %i %o', help='same as -P "%(const)s"') parser.add_argument('-Q', dest='postprocess_cmd', action='store_const', const='pngquant --ext %e %i', help='same as -P "%(const)s"') parser.add_argument('-c', dest='pdf_cmd', metavar="COMMAND", default='convert %i %o', help='PDF command (default "%(default)s")') return parser ###################################################################### def get_filenames(options): '''Get the filenames from the command line, optionally sorted by number, so that IMG_10.png is re-arranged to come after IMG_9.png. This is a nice feature because some scanner programs (like Image Capture on Mac OS X) automatically number files without leading zeros, and this way you can supply files using a wildcard and still have the pages ordered correctly. ''' if not options.sort_numerically: return options.filenames filenames = [] for filename in options.filenames: basename = os.path.basename(filename) root, _ = os.path.splitext(basename) matches = re.findall(r'[0-9]+', root) if matches: num = int(matches[-1]) else: num = -1 filenames.append((num, filename)) return [fn for (_, fn) in sorted(filenames)] ###################################################################### def load(input_filename): '''Load an image with Pillow and convert it to numpy array. Also returns the image DPI in x and y as a tuple.''' try: pil_img = Image.open(input_filename) except IOError: sys.stderr.write('warning: error opening {}\n'.format( input_filename)) return None, None if pil_img.mode != 'RGB': pil_img = pil_img.convert('RGB') if 'dpi' in pil_img.info: dpi = pil_img.info['dpi'] else: dpi = (300, 300) img = np.array(pil_img) return img, dpi ###################################################################### def sample_pixels(img, options): '''Pick a fixed percentage of pixels in the image, returned in random order.''' pixels = img.reshape((-1, 3)) num_pixels = pixels.shape[0] num_samples = int(num_pixels*options.sample_fraction) idx = np.arange(num_pixels) np.random.shuffle(idx) return pixels[idx[:num_samples]] ###################################################################### def get_fg_mask(bg_color, samples, options): '''Determine whether each pixel in a set of samples is foreground by comparing it to the background color. A pixel is classified as a foreground pixel if either its value or saturation differs from the background by a threshold.''' s_bg, v_bg = rgb_to_sv(bg_color) s_samples, v_samples = rgb_to_sv(samples) s_diff = np.abs(s_bg - s_samples) v_diff = np.abs(v_bg - v_samples) return ((v_diff >= options.value_threshold) | (s_diff >= options.sat_threshold)) ###################################################################### def get_palette(samples, options, return_mask=False, kmeans_iter=40): '''Extract the palette for the set of sampled RGB values. The first palette entry is always the background color; the rest are determined from foreground pixels by running K-means clustering. Returns the palette, as well as a mask corresponding to the foreground pixels. ''' if not options.quiet: print(' getting palette...') bg_color = get_bg_color(samples, 6) fg_mask = get_fg_mask(bg_color, samples, options) centers, _ = kmeans(samples[fg_mask].astype(np.float32), options.num_colors-1, iter=kmeans_iter) palette = np.vstack((bg_color, centers)).astype(np.uint8) if not return_mask: return palette else: return palette, fg_mask ###################################################################### def apply_palette(img, palette, options): '''Apply the pallete to the given image. The first step is to set all background pixels to the background color; then, nearest-neighbor matching is used to map each foreground color to the closest one in the palette. ''' if not options.quiet: print(' applying palette...') bg_color = palette[0] fg_mask = get_fg_mask(bg_color, img, options) orig_shape = img.shape pixels = img.reshape((-1, 3)) fg_mask = fg_mask.flatten() num_pixels = pixels.shape[0] labels = np.zeros(num_pixels, dtype=np.uint8) labels[fg_mask], _ = vq(pixels[fg_mask], palette) return labels.reshape(orig_shape[:-1]) ###################################################################### def save(output_filename, labels, palette, dpi, options): '''Save the label/palette pair out as an indexed PNG image. This optionally saturates the pallete by mapping the smallest color component to zero and the largest one to 255, and also optionally sets the background color to pure white. ''' if not options.quiet: print(' saving {}...'.format(output_filename)) if options.saturate: palette = palette.astype(np.float32) pmin = palette.min() pmax = palette.max() palette = 255 * (palette - pmin)/(pmax-pmin) palette = palette.astype(np.uint8) if options.white_bg: palette = palette.copy() palette[0] = (255, 255, 255) output_img = Image.fromarray(labels, 'P') output_img.putpalette(palette.flatten()) output_img.save(output_filename, dpi=dpi) ###################################################################### def get_global_palette(filenames, options): '''Fetch the global palette for a series of input files by merging their samples together into one large array. ''' input_filenames = [] all_samples = [] if not options.quiet: print('building global palette...') for input_filename in filenames: img, _ = load(input_filename) if img is None: continue if not options.quiet: print(' processing {}...'.format(input_filename)) samples = sample_pixels(img, options) input_filenames.append(input_filename) all_samples.append(samples) num_inputs = len(input_filenames) all_samples = [s[:int(round(float(s.shape[0])/num_inputs))] for s in all_samples] all_samples = np.vstack(tuple(all_samples)) global_palette = get_palette(all_samples, options) if not options.quiet: print(' done\n') return input_filenames, global_palette ###################################################################### def emit_pdf(outputs, options): '''Runs the PDF conversion command to generate the PDF.''' cmd = options.pdf_cmd cmd = cmd.replace('%o', options.pdfname) if len(outputs) > 2: cmd_print = cmd.replace('%i', ' '.join(outputs[:2] + ['...'])) else: cmd_print = cmd.replace('%i', ' '.join(outputs)) cmd = cmd.replace('%i', ' '.join(outputs)) if not options.quiet: print('running PDF command "{}"...'.format(cmd_print)) try: result = subprocess.call(shlex.split(cmd)) except OSError: result = -1 if result == 0: if not options.quiet: print(' wrote', options.pdfname) else: sys.stderr.write('warning: PDF command failed\n') ###################################################################### def notescan_main(options): '''Main function for this program when run as script.''' filenames = get_filenames(options) outputs = [] do_global = options.global_palette and len(filenames) > 1 if do_global: filenames, palette = get_global_palette(filenames, options) do_postprocess = bool(options.postprocess_cmd) for input_filename in filenames: img, dpi = load(input_filename) if img is None: continue output_filename = '{}{:04d}.png'.format( options.basename, len(outputs)) if not options.quiet: print('opened', input_filename) if not do_global: samples = sample_pixels(img, options) palette = get_palette(samples, options) labels = apply_palette(img, palette, options) save(output_filename, labels, palette, dpi, options) if do_postprocess: post_filename = postprocess(output_filename, options) if post_filename: output_filename = post_filename else: do_postprocess = False outputs.append(output_filename) if not options.quiet: print(' done\n') emit_pdf(outputs, options) ###################################################################### def main(): '''Parse args and call notescan_main().''' notescan_main(options=get_argument_parser().parse_args()) if __name__ == '__main__': main()
mzucker/noteshrink
noteshrink.py
rgb_to_sv
python
def rgb_to_sv(rgb): '''Convert an RGB image or array of RGB colors to saturation and value, returning each one as a separate 32-bit floating point array or value. ''' if not isinstance(rgb, np.ndarray): rgb = np.array(rgb) axis = len(rgb.shape)-1 cmax = rgb.max(axis=axis).astype(np.float32) cmin = rgb.min(axis=axis).astype(np.float32) delta = cmax - cmin saturation = delta.astype(np.float32) / cmax.astype(np.float32) saturation = np.where(cmax == 0, 0, saturation) value = cmax/255.0 return saturation, value
Convert an RGB image or array of RGB colors to saturation and value, returning each one as a separate 32-bit floating point array or value.
train
https://github.com/mzucker/noteshrink/blob/7d876e5b43923c6bf8d64b7ef18f6855bfb30ce3/noteshrink.py#L116-L137
null
#!/usr/bin/env python '''Converts sequence of images to compact PDF while removing speckles, bleedthrough, etc. ''' # for some reason pylint complains about members being undefined :( # pylint: disable=E1101 from __future__ import print_function import sys import os import re import subprocess import shlex from argparse import ArgumentParser import numpy as np from PIL import Image from scipy.cluster.vq import kmeans, vq ###################################################################### def quantize(image, bits_per_channel=None): '''Reduces the number of bits per channel in the given image.''' if bits_per_channel is None: bits_per_channel = 6 assert image.dtype == np.uint8 shift = 8-bits_per_channel halfbin = (1 << shift) >> 1 return ((image.astype(int) >> shift) << shift) + halfbin ###################################################################### def pack_rgb(rgb): '''Packs a 24-bit RGB triples into a single integer, works on both arrays and tuples.''' orig_shape = None if isinstance(rgb, np.ndarray): assert rgb.shape[-1] == 3 orig_shape = rgb.shape[:-1] else: assert len(rgb) == 3 rgb = np.array(rgb) rgb = rgb.astype(int).reshape((-1, 3)) packed = (rgb[:, 0] << 16 | rgb[:, 1] << 8 | rgb[:, 2]) if orig_shape is None: return packed else: return packed.reshape(orig_shape) ###################################################################### def unpack_rgb(packed): '''Unpacks a single integer or array of integers into one or more 24-bit RGB values. ''' orig_shape = None if isinstance(packed, np.ndarray): assert packed.dtype == int orig_shape = packed.shape packed = packed.reshape((-1, 1)) rgb = ((packed >> 16) & 0xff, (packed >> 8) & 0xff, (packed) & 0xff) if orig_shape is None: return rgb else: return np.hstack(rgb).reshape(orig_shape + (3,)) ###################################################################### def get_bg_color(image, bits_per_channel=None): '''Obtains the background color from an image or array of RGB colors by grouping similar colors into bins and finding the most frequent one. ''' assert image.shape[-1] == 3 quantized = quantize(image, bits_per_channel).astype(int) packed = pack_rgb(quantized) unique, counts = np.unique(packed, return_counts=True) packed_mode = unique[counts.argmax()] return unpack_rgb(packed_mode) ###################################################################### ###################################################################### def postprocess(output_filename, options): '''Runs the postprocessing command on the file provided.''' assert options.postprocess_cmd base, _ = os.path.splitext(output_filename) post_filename = base + options.postprocess_ext cmd = options.postprocess_cmd cmd = cmd.replace('%i', output_filename) cmd = cmd.replace('%o', post_filename) cmd = cmd.replace('%e', options.postprocess_ext) subprocess_args = shlex.split(cmd) if os.path.exists(post_filename): os.unlink(post_filename) if not options.quiet: print(' running "{}"...'.format(cmd), end=' ') sys.stdout.flush() try: result = subprocess.call(subprocess_args) before = os.stat(output_filename).st_size after = os.stat(post_filename).st_size except OSError: result = -1 if result == 0: if not options.quiet: print('{:.1f}% reduction'.format( 100*(1.0-float(after)/before))) return post_filename else: sys.stderr.write('warning: postprocessing failed!\n') return None ###################################################################### def percent(string): '''Convert a string (i.e. 85) to a fraction (i.e. .85).''' return float(string)/100.0 ###################################################################### def get_argument_parser(): '''Parse the command-line arguments for this program.''' parser = ArgumentParser( description='convert scanned, hand-written notes to PDF') show_default = ' (default %(default)s)' parser.add_argument('filenames', metavar='IMAGE', nargs='+', help='files to convert') parser.add_argument('-q', dest='quiet', action='store_true', default=False, help='reduce program output') parser.add_argument('-b', dest='basename', metavar='BASENAME', default='page', help='output PNG filename base' + show_default) parser.add_argument('-o', dest='pdfname', metavar='PDF', default='output.pdf', help='output PDF filename' + show_default) parser.add_argument('-v', dest='value_threshold', metavar='PERCENT', type=percent, default='25', help='background value threshold %%'+show_default) parser.add_argument('-s', dest='sat_threshold', metavar='PERCENT', type=percent, default='20', help='background saturation ' 'threshold %%'+show_default) parser.add_argument('-n', dest='num_colors', type=int, default='8', help='number of output colors '+show_default) parser.add_argument('-p', dest='sample_fraction', metavar='PERCENT', type=percent, default='5', help='%% of pixels to sample' + show_default) parser.add_argument('-w', dest='white_bg', action='store_true', default=False, help='make background white') parser.add_argument('-g', dest='global_palette', action='store_true', default=False, help='use one global palette for all pages') parser.add_argument('-S', dest='saturate', action='store_false', default=True, help='do not saturate colors') parser.add_argument('-K', dest='sort_numerically', action='store_false', default=True, help='keep filenames ordered as specified; ' 'use if you *really* want IMG_10.png to ' 'precede IMG_2.png') parser.add_argument('-P', dest='postprocess_cmd', default=None, help='set postprocessing command (see -O, -C, -Q)') parser.add_argument('-e', dest='postprocess_ext', default='_post.png', help='filename suffix/extension for ' 'postprocessing command') parser.add_argument('-O', dest='postprocess_cmd', action='store_const', const='optipng -silent %i -out %o', help='same as -P "%(const)s"') parser.add_argument('-C', dest='postprocess_cmd', action='store_const', const='pngcrush -q %i %o', help='same as -P "%(const)s"') parser.add_argument('-Q', dest='postprocess_cmd', action='store_const', const='pngquant --ext %e %i', help='same as -P "%(const)s"') parser.add_argument('-c', dest='pdf_cmd', metavar="COMMAND", default='convert %i %o', help='PDF command (default "%(default)s")') return parser ###################################################################### def get_filenames(options): '''Get the filenames from the command line, optionally sorted by number, so that IMG_10.png is re-arranged to come after IMG_9.png. This is a nice feature because some scanner programs (like Image Capture on Mac OS X) automatically number files without leading zeros, and this way you can supply files using a wildcard and still have the pages ordered correctly. ''' if not options.sort_numerically: return options.filenames filenames = [] for filename in options.filenames: basename = os.path.basename(filename) root, _ = os.path.splitext(basename) matches = re.findall(r'[0-9]+', root) if matches: num = int(matches[-1]) else: num = -1 filenames.append((num, filename)) return [fn for (_, fn) in sorted(filenames)] ###################################################################### def load(input_filename): '''Load an image with Pillow and convert it to numpy array. Also returns the image DPI in x and y as a tuple.''' try: pil_img = Image.open(input_filename) except IOError: sys.stderr.write('warning: error opening {}\n'.format( input_filename)) return None, None if pil_img.mode != 'RGB': pil_img = pil_img.convert('RGB') if 'dpi' in pil_img.info: dpi = pil_img.info['dpi'] else: dpi = (300, 300) img = np.array(pil_img) return img, dpi ###################################################################### def sample_pixels(img, options): '''Pick a fixed percentage of pixels in the image, returned in random order.''' pixels = img.reshape((-1, 3)) num_pixels = pixels.shape[0] num_samples = int(num_pixels*options.sample_fraction) idx = np.arange(num_pixels) np.random.shuffle(idx) return pixels[idx[:num_samples]] ###################################################################### def get_fg_mask(bg_color, samples, options): '''Determine whether each pixel in a set of samples is foreground by comparing it to the background color. A pixel is classified as a foreground pixel if either its value or saturation differs from the background by a threshold.''' s_bg, v_bg = rgb_to_sv(bg_color) s_samples, v_samples = rgb_to_sv(samples) s_diff = np.abs(s_bg - s_samples) v_diff = np.abs(v_bg - v_samples) return ((v_diff >= options.value_threshold) | (s_diff >= options.sat_threshold)) ###################################################################### def get_palette(samples, options, return_mask=False, kmeans_iter=40): '''Extract the palette for the set of sampled RGB values. The first palette entry is always the background color; the rest are determined from foreground pixels by running K-means clustering. Returns the palette, as well as a mask corresponding to the foreground pixels. ''' if not options.quiet: print(' getting palette...') bg_color = get_bg_color(samples, 6) fg_mask = get_fg_mask(bg_color, samples, options) centers, _ = kmeans(samples[fg_mask].astype(np.float32), options.num_colors-1, iter=kmeans_iter) palette = np.vstack((bg_color, centers)).astype(np.uint8) if not return_mask: return palette else: return palette, fg_mask ###################################################################### def apply_palette(img, palette, options): '''Apply the pallete to the given image. The first step is to set all background pixels to the background color; then, nearest-neighbor matching is used to map each foreground color to the closest one in the palette. ''' if not options.quiet: print(' applying palette...') bg_color = palette[0] fg_mask = get_fg_mask(bg_color, img, options) orig_shape = img.shape pixels = img.reshape((-1, 3)) fg_mask = fg_mask.flatten() num_pixels = pixels.shape[0] labels = np.zeros(num_pixels, dtype=np.uint8) labels[fg_mask], _ = vq(pixels[fg_mask], palette) return labels.reshape(orig_shape[:-1]) ###################################################################### def save(output_filename, labels, palette, dpi, options): '''Save the label/palette pair out as an indexed PNG image. This optionally saturates the pallete by mapping the smallest color component to zero and the largest one to 255, and also optionally sets the background color to pure white. ''' if not options.quiet: print(' saving {}...'.format(output_filename)) if options.saturate: palette = palette.astype(np.float32) pmin = palette.min() pmax = palette.max() palette = 255 * (palette - pmin)/(pmax-pmin) palette = palette.astype(np.uint8) if options.white_bg: palette = palette.copy() palette[0] = (255, 255, 255) output_img = Image.fromarray(labels, 'P') output_img.putpalette(palette.flatten()) output_img.save(output_filename, dpi=dpi) ###################################################################### def get_global_palette(filenames, options): '''Fetch the global palette for a series of input files by merging their samples together into one large array. ''' input_filenames = [] all_samples = [] if not options.quiet: print('building global palette...') for input_filename in filenames: img, _ = load(input_filename) if img is None: continue if not options.quiet: print(' processing {}...'.format(input_filename)) samples = sample_pixels(img, options) input_filenames.append(input_filename) all_samples.append(samples) num_inputs = len(input_filenames) all_samples = [s[:int(round(float(s.shape[0])/num_inputs))] for s in all_samples] all_samples = np.vstack(tuple(all_samples)) global_palette = get_palette(all_samples, options) if not options.quiet: print(' done\n') return input_filenames, global_palette ###################################################################### def emit_pdf(outputs, options): '''Runs the PDF conversion command to generate the PDF.''' cmd = options.pdf_cmd cmd = cmd.replace('%o', options.pdfname) if len(outputs) > 2: cmd_print = cmd.replace('%i', ' '.join(outputs[:2] + ['...'])) else: cmd_print = cmd.replace('%i', ' '.join(outputs)) cmd = cmd.replace('%i', ' '.join(outputs)) if not options.quiet: print('running PDF command "{}"...'.format(cmd_print)) try: result = subprocess.call(shlex.split(cmd)) except OSError: result = -1 if result == 0: if not options.quiet: print(' wrote', options.pdfname) else: sys.stderr.write('warning: PDF command failed\n') ###################################################################### def notescan_main(options): '''Main function for this program when run as script.''' filenames = get_filenames(options) outputs = [] do_global = options.global_palette and len(filenames) > 1 if do_global: filenames, palette = get_global_palette(filenames, options) do_postprocess = bool(options.postprocess_cmd) for input_filename in filenames: img, dpi = load(input_filename) if img is None: continue output_filename = '{}{:04d}.png'.format( options.basename, len(outputs)) if not options.quiet: print('opened', input_filename) if not do_global: samples = sample_pixels(img, options) palette = get_palette(samples, options) labels = apply_palette(img, palette, options) save(output_filename, labels, palette, dpi, options) if do_postprocess: post_filename = postprocess(output_filename, options) if post_filename: output_filename = post_filename else: do_postprocess = False outputs.append(output_filename) if not options.quiet: print(' done\n') emit_pdf(outputs, options) ###################################################################### def main(): '''Parse args and call notescan_main().''' notescan_main(options=get_argument_parser().parse_args()) if __name__ == '__main__': main()
mzucker/noteshrink
noteshrink.py
postprocess
python
def postprocess(output_filename, options): '''Runs the postprocessing command on the file provided.''' assert options.postprocess_cmd base, _ = os.path.splitext(output_filename) post_filename = base + options.postprocess_ext cmd = options.postprocess_cmd cmd = cmd.replace('%i', output_filename) cmd = cmd.replace('%o', post_filename) cmd = cmd.replace('%e', options.postprocess_ext) subprocess_args = shlex.split(cmd) if os.path.exists(post_filename): os.unlink(post_filename) if not options.quiet: print(' running "{}"...'.format(cmd), end=' ') sys.stdout.flush() try: result = subprocess.call(subprocess_args) before = os.stat(output_filename).st_size after = os.stat(post_filename).st_size except OSError: result = -1 if result == 0: if not options.quiet: print('{:.1f}% reduction'.format( 100*(1.0-float(after)/before))) return post_filename else: sys.stderr.write('warning: postprocessing failed!\n') return None
Runs the postprocessing command on the file provided.
train
https://github.com/mzucker/noteshrink/blob/7d876e5b43923c6bf8d64b7ef18f6855bfb30ce3/noteshrink.py#L141-L182
null
#!/usr/bin/env python '''Converts sequence of images to compact PDF while removing speckles, bleedthrough, etc. ''' # for some reason pylint complains about members being undefined :( # pylint: disable=E1101 from __future__ import print_function import sys import os import re import subprocess import shlex from argparse import ArgumentParser import numpy as np from PIL import Image from scipy.cluster.vq import kmeans, vq ###################################################################### def quantize(image, bits_per_channel=None): '''Reduces the number of bits per channel in the given image.''' if bits_per_channel is None: bits_per_channel = 6 assert image.dtype == np.uint8 shift = 8-bits_per_channel halfbin = (1 << shift) >> 1 return ((image.astype(int) >> shift) << shift) + halfbin ###################################################################### def pack_rgb(rgb): '''Packs a 24-bit RGB triples into a single integer, works on both arrays and tuples.''' orig_shape = None if isinstance(rgb, np.ndarray): assert rgb.shape[-1] == 3 orig_shape = rgb.shape[:-1] else: assert len(rgb) == 3 rgb = np.array(rgb) rgb = rgb.astype(int).reshape((-1, 3)) packed = (rgb[:, 0] << 16 | rgb[:, 1] << 8 | rgb[:, 2]) if orig_shape is None: return packed else: return packed.reshape(orig_shape) ###################################################################### def unpack_rgb(packed): '''Unpacks a single integer or array of integers into one or more 24-bit RGB values. ''' orig_shape = None if isinstance(packed, np.ndarray): assert packed.dtype == int orig_shape = packed.shape packed = packed.reshape((-1, 1)) rgb = ((packed >> 16) & 0xff, (packed >> 8) & 0xff, (packed) & 0xff) if orig_shape is None: return rgb else: return np.hstack(rgb).reshape(orig_shape + (3,)) ###################################################################### def get_bg_color(image, bits_per_channel=None): '''Obtains the background color from an image or array of RGB colors by grouping similar colors into bins and finding the most frequent one. ''' assert image.shape[-1] == 3 quantized = quantize(image, bits_per_channel).astype(int) packed = pack_rgb(quantized) unique, counts = np.unique(packed, return_counts=True) packed_mode = unique[counts.argmax()] return unpack_rgb(packed_mode) ###################################################################### def rgb_to_sv(rgb): '''Convert an RGB image or array of RGB colors to saturation and value, returning each one as a separate 32-bit floating point array or value. ''' if not isinstance(rgb, np.ndarray): rgb = np.array(rgb) axis = len(rgb.shape)-1 cmax = rgb.max(axis=axis).astype(np.float32) cmin = rgb.min(axis=axis).astype(np.float32) delta = cmax - cmin saturation = delta.astype(np.float32) / cmax.astype(np.float32) saturation = np.where(cmax == 0, 0, saturation) value = cmax/255.0 return saturation, value ###################################################################### ###################################################################### def percent(string): '''Convert a string (i.e. 85) to a fraction (i.e. .85).''' return float(string)/100.0 ###################################################################### def get_argument_parser(): '''Parse the command-line arguments for this program.''' parser = ArgumentParser( description='convert scanned, hand-written notes to PDF') show_default = ' (default %(default)s)' parser.add_argument('filenames', metavar='IMAGE', nargs='+', help='files to convert') parser.add_argument('-q', dest='quiet', action='store_true', default=False, help='reduce program output') parser.add_argument('-b', dest='basename', metavar='BASENAME', default='page', help='output PNG filename base' + show_default) parser.add_argument('-o', dest='pdfname', metavar='PDF', default='output.pdf', help='output PDF filename' + show_default) parser.add_argument('-v', dest='value_threshold', metavar='PERCENT', type=percent, default='25', help='background value threshold %%'+show_default) parser.add_argument('-s', dest='sat_threshold', metavar='PERCENT', type=percent, default='20', help='background saturation ' 'threshold %%'+show_default) parser.add_argument('-n', dest='num_colors', type=int, default='8', help='number of output colors '+show_default) parser.add_argument('-p', dest='sample_fraction', metavar='PERCENT', type=percent, default='5', help='%% of pixels to sample' + show_default) parser.add_argument('-w', dest='white_bg', action='store_true', default=False, help='make background white') parser.add_argument('-g', dest='global_palette', action='store_true', default=False, help='use one global palette for all pages') parser.add_argument('-S', dest='saturate', action='store_false', default=True, help='do not saturate colors') parser.add_argument('-K', dest='sort_numerically', action='store_false', default=True, help='keep filenames ordered as specified; ' 'use if you *really* want IMG_10.png to ' 'precede IMG_2.png') parser.add_argument('-P', dest='postprocess_cmd', default=None, help='set postprocessing command (see -O, -C, -Q)') parser.add_argument('-e', dest='postprocess_ext', default='_post.png', help='filename suffix/extension for ' 'postprocessing command') parser.add_argument('-O', dest='postprocess_cmd', action='store_const', const='optipng -silent %i -out %o', help='same as -P "%(const)s"') parser.add_argument('-C', dest='postprocess_cmd', action='store_const', const='pngcrush -q %i %o', help='same as -P "%(const)s"') parser.add_argument('-Q', dest='postprocess_cmd', action='store_const', const='pngquant --ext %e %i', help='same as -P "%(const)s"') parser.add_argument('-c', dest='pdf_cmd', metavar="COMMAND", default='convert %i %o', help='PDF command (default "%(default)s")') return parser ###################################################################### def get_filenames(options): '''Get the filenames from the command line, optionally sorted by number, so that IMG_10.png is re-arranged to come after IMG_9.png. This is a nice feature because some scanner programs (like Image Capture on Mac OS X) automatically number files without leading zeros, and this way you can supply files using a wildcard and still have the pages ordered correctly. ''' if not options.sort_numerically: return options.filenames filenames = [] for filename in options.filenames: basename = os.path.basename(filename) root, _ = os.path.splitext(basename) matches = re.findall(r'[0-9]+', root) if matches: num = int(matches[-1]) else: num = -1 filenames.append((num, filename)) return [fn for (_, fn) in sorted(filenames)] ###################################################################### def load(input_filename): '''Load an image with Pillow and convert it to numpy array. Also returns the image DPI in x and y as a tuple.''' try: pil_img = Image.open(input_filename) except IOError: sys.stderr.write('warning: error opening {}\n'.format( input_filename)) return None, None if pil_img.mode != 'RGB': pil_img = pil_img.convert('RGB') if 'dpi' in pil_img.info: dpi = pil_img.info['dpi'] else: dpi = (300, 300) img = np.array(pil_img) return img, dpi ###################################################################### def sample_pixels(img, options): '''Pick a fixed percentage of pixels in the image, returned in random order.''' pixels = img.reshape((-1, 3)) num_pixels = pixels.shape[0] num_samples = int(num_pixels*options.sample_fraction) idx = np.arange(num_pixels) np.random.shuffle(idx) return pixels[idx[:num_samples]] ###################################################################### def get_fg_mask(bg_color, samples, options): '''Determine whether each pixel in a set of samples is foreground by comparing it to the background color. A pixel is classified as a foreground pixel if either its value or saturation differs from the background by a threshold.''' s_bg, v_bg = rgb_to_sv(bg_color) s_samples, v_samples = rgb_to_sv(samples) s_diff = np.abs(s_bg - s_samples) v_diff = np.abs(v_bg - v_samples) return ((v_diff >= options.value_threshold) | (s_diff >= options.sat_threshold)) ###################################################################### def get_palette(samples, options, return_mask=False, kmeans_iter=40): '''Extract the palette for the set of sampled RGB values. The first palette entry is always the background color; the rest are determined from foreground pixels by running K-means clustering. Returns the palette, as well as a mask corresponding to the foreground pixels. ''' if not options.quiet: print(' getting palette...') bg_color = get_bg_color(samples, 6) fg_mask = get_fg_mask(bg_color, samples, options) centers, _ = kmeans(samples[fg_mask].astype(np.float32), options.num_colors-1, iter=kmeans_iter) palette = np.vstack((bg_color, centers)).astype(np.uint8) if not return_mask: return palette else: return palette, fg_mask ###################################################################### def apply_palette(img, palette, options): '''Apply the pallete to the given image. The first step is to set all background pixels to the background color; then, nearest-neighbor matching is used to map each foreground color to the closest one in the palette. ''' if not options.quiet: print(' applying palette...') bg_color = palette[0] fg_mask = get_fg_mask(bg_color, img, options) orig_shape = img.shape pixels = img.reshape((-1, 3)) fg_mask = fg_mask.flatten() num_pixels = pixels.shape[0] labels = np.zeros(num_pixels, dtype=np.uint8) labels[fg_mask], _ = vq(pixels[fg_mask], palette) return labels.reshape(orig_shape[:-1]) ###################################################################### def save(output_filename, labels, palette, dpi, options): '''Save the label/palette pair out as an indexed PNG image. This optionally saturates the pallete by mapping the smallest color component to zero and the largest one to 255, and also optionally sets the background color to pure white. ''' if not options.quiet: print(' saving {}...'.format(output_filename)) if options.saturate: palette = palette.astype(np.float32) pmin = palette.min() pmax = palette.max() palette = 255 * (palette - pmin)/(pmax-pmin) palette = palette.astype(np.uint8) if options.white_bg: palette = palette.copy() palette[0] = (255, 255, 255) output_img = Image.fromarray(labels, 'P') output_img.putpalette(palette.flatten()) output_img.save(output_filename, dpi=dpi) ###################################################################### def get_global_palette(filenames, options): '''Fetch the global palette for a series of input files by merging their samples together into one large array. ''' input_filenames = [] all_samples = [] if not options.quiet: print('building global palette...') for input_filename in filenames: img, _ = load(input_filename) if img is None: continue if not options.quiet: print(' processing {}...'.format(input_filename)) samples = sample_pixels(img, options) input_filenames.append(input_filename) all_samples.append(samples) num_inputs = len(input_filenames) all_samples = [s[:int(round(float(s.shape[0])/num_inputs))] for s in all_samples] all_samples = np.vstack(tuple(all_samples)) global_palette = get_palette(all_samples, options) if not options.quiet: print(' done\n') return input_filenames, global_palette ###################################################################### def emit_pdf(outputs, options): '''Runs the PDF conversion command to generate the PDF.''' cmd = options.pdf_cmd cmd = cmd.replace('%o', options.pdfname) if len(outputs) > 2: cmd_print = cmd.replace('%i', ' '.join(outputs[:2] + ['...'])) else: cmd_print = cmd.replace('%i', ' '.join(outputs)) cmd = cmd.replace('%i', ' '.join(outputs)) if not options.quiet: print('running PDF command "{}"...'.format(cmd_print)) try: result = subprocess.call(shlex.split(cmd)) except OSError: result = -1 if result == 0: if not options.quiet: print(' wrote', options.pdfname) else: sys.stderr.write('warning: PDF command failed\n') ###################################################################### def notescan_main(options): '''Main function for this program when run as script.''' filenames = get_filenames(options) outputs = [] do_global = options.global_palette and len(filenames) > 1 if do_global: filenames, palette = get_global_palette(filenames, options) do_postprocess = bool(options.postprocess_cmd) for input_filename in filenames: img, dpi = load(input_filename) if img is None: continue output_filename = '{}{:04d}.png'.format( options.basename, len(outputs)) if not options.quiet: print('opened', input_filename) if not do_global: samples = sample_pixels(img, options) palette = get_palette(samples, options) labels = apply_palette(img, palette, options) save(output_filename, labels, palette, dpi, options) if do_postprocess: post_filename = postprocess(output_filename, options) if post_filename: output_filename = post_filename else: do_postprocess = False outputs.append(output_filename) if not options.quiet: print(' done\n') emit_pdf(outputs, options) ###################################################################### def main(): '''Parse args and call notescan_main().''' notescan_main(options=get_argument_parser().parse_args()) if __name__ == '__main__': main()
mzucker/noteshrink
noteshrink.py
get_argument_parser
python
def get_argument_parser(): '''Parse the command-line arguments for this program.''' parser = ArgumentParser( description='convert scanned, hand-written notes to PDF') show_default = ' (default %(default)s)' parser.add_argument('filenames', metavar='IMAGE', nargs='+', help='files to convert') parser.add_argument('-q', dest='quiet', action='store_true', default=False, help='reduce program output') parser.add_argument('-b', dest='basename', metavar='BASENAME', default='page', help='output PNG filename base' + show_default) parser.add_argument('-o', dest='pdfname', metavar='PDF', default='output.pdf', help='output PDF filename' + show_default) parser.add_argument('-v', dest='value_threshold', metavar='PERCENT', type=percent, default='25', help='background value threshold %%'+show_default) parser.add_argument('-s', dest='sat_threshold', metavar='PERCENT', type=percent, default='20', help='background saturation ' 'threshold %%'+show_default) parser.add_argument('-n', dest='num_colors', type=int, default='8', help='number of output colors '+show_default) parser.add_argument('-p', dest='sample_fraction', metavar='PERCENT', type=percent, default='5', help='%% of pixels to sample' + show_default) parser.add_argument('-w', dest='white_bg', action='store_true', default=False, help='make background white') parser.add_argument('-g', dest='global_palette', action='store_true', default=False, help='use one global palette for all pages') parser.add_argument('-S', dest='saturate', action='store_false', default=True, help='do not saturate colors') parser.add_argument('-K', dest='sort_numerically', action='store_false', default=True, help='keep filenames ordered as specified; ' 'use if you *really* want IMG_10.png to ' 'precede IMG_2.png') parser.add_argument('-P', dest='postprocess_cmd', default=None, help='set postprocessing command (see -O, -C, -Q)') parser.add_argument('-e', dest='postprocess_ext', default='_post.png', help='filename suffix/extension for ' 'postprocessing command') parser.add_argument('-O', dest='postprocess_cmd', action='store_const', const='optipng -silent %i -out %o', help='same as -P "%(const)s"') parser.add_argument('-C', dest='postprocess_cmd', action='store_const', const='pngcrush -q %i %o', help='same as -P "%(const)s"') parser.add_argument('-Q', dest='postprocess_cmd', action='store_const', const='pngquant --ext %e %i', help='same as -P "%(const)s"') parser.add_argument('-c', dest='pdf_cmd', metavar="COMMAND", default='convert %i %o', help='PDF command (default "%(default)s")') return parser
Parse the command-line arguments for this program.
train
https://github.com/mzucker/noteshrink/blob/7d876e5b43923c6bf8d64b7ef18f6855bfb30ce3/noteshrink.py#L192-L277
null
#!/usr/bin/env python '''Converts sequence of images to compact PDF while removing speckles, bleedthrough, etc. ''' # for some reason pylint complains about members being undefined :( # pylint: disable=E1101 from __future__ import print_function import sys import os import re import subprocess import shlex from argparse import ArgumentParser import numpy as np from PIL import Image from scipy.cluster.vq import kmeans, vq ###################################################################### def quantize(image, bits_per_channel=None): '''Reduces the number of bits per channel in the given image.''' if bits_per_channel is None: bits_per_channel = 6 assert image.dtype == np.uint8 shift = 8-bits_per_channel halfbin = (1 << shift) >> 1 return ((image.astype(int) >> shift) << shift) + halfbin ###################################################################### def pack_rgb(rgb): '''Packs a 24-bit RGB triples into a single integer, works on both arrays and tuples.''' orig_shape = None if isinstance(rgb, np.ndarray): assert rgb.shape[-1] == 3 orig_shape = rgb.shape[:-1] else: assert len(rgb) == 3 rgb = np.array(rgb) rgb = rgb.astype(int).reshape((-1, 3)) packed = (rgb[:, 0] << 16 | rgb[:, 1] << 8 | rgb[:, 2]) if orig_shape is None: return packed else: return packed.reshape(orig_shape) ###################################################################### def unpack_rgb(packed): '''Unpacks a single integer or array of integers into one or more 24-bit RGB values. ''' orig_shape = None if isinstance(packed, np.ndarray): assert packed.dtype == int orig_shape = packed.shape packed = packed.reshape((-1, 1)) rgb = ((packed >> 16) & 0xff, (packed >> 8) & 0xff, (packed) & 0xff) if orig_shape is None: return rgb else: return np.hstack(rgb).reshape(orig_shape + (3,)) ###################################################################### def get_bg_color(image, bits_per_channel=None): '''Obtains the background color from an image or array of RGB colors by grouping similar colors into bins and finding the most frequent one. ''' assert image.shape[-1] == 3 quantized = quantize(image, bits_per_channel).astype(int) packed = pack_rgb(quantized) unique, counts = np.unique(packed, return_counts=True) packed_mode = unique[counts.argmax()] return unpack_rgb(packed_mode) ###################################################################### def rgb_to_sv(rgb): '''Convert an RGB image or array of RGB colors to saturation and value, returning each one as a separate 32-bit floating point array or value. ''' if not isinstance(rgb, np.ndarray): rgb = np.array(rgb) axis = len(rgb.shape)-1 cmax = rgb.max(axis=axis).astype(np.float32) cmin = rgb.min(axis=axis).astype(np.float32) delta = cmax - cmin saturation = delta.astype(np.float32) / cmax.astype(np.float32) saturation = np.where(cmax == 0, 0, saturation) value = cmax/255.0 return saturation, value ###################################################################### def postprocess(output_filename, options): '''Runs the postprocessing command on the file provided.''' assert options.postprocess_cmd base, _ = os.path.splitext(output_filename) post_filename = base + options.postprocess_ext cmd = options.postprocess_cmd cmd = cmd.replace('%i', output_filename) cmd = cmd.replace('%o', post_filename) cmd = cmd.replace('%e', options.postprocess_ext) subprocess_args = shlex.split(cmd) if os.path.exists(post_filename): os.unlink(post_filename) if not options.quiet: print(' running "{}"...'.format(cmd), end=' ') sys.stdout.flush() try: result = subprocess.call(subprocess_args) before = os.stat(output_filename).st_size after = os.stat(post_filename).st_size except OSError: result = -1 if result == 0: if not options.quiet: print('{:.1f}% reduction'.format( 100*(1.0-float(after)/before))) return post_filename else: sys.stderr.write('warning: postprocessing failed!\n') return None ###################################################################### def percent(string): '''Convert a string (i.e. 85) to a fraction (i.e. .85).''' return float(string)/100.0 ###################################################################### ###################################################################### def get_filenames(options): '''Get the filenames from the command line, optionally sorted by number, so that IMG_10.png is re-arranged to come after IMG_9.png. This is a nice feature because some scanner programs (like Image Capture on Mac OS X) automatically number files without leading zeros, and this way you can supply files using a wildcard and still have the pages ordered correctly. ''' if not options.sort_numerically: return options.filenames filenames = [] for filename in options.filenames: basename = os.path.basename(filename) root, _ = os.path.splitext(basename) matches = re.findall(r'[0-9]+', root) if matches: num = int(matches[-1]) else: num = -1 filenames.append((num, filename)) return [fn for (_, fn) in sorted(filenames)] ###################################################################### def load(input_filename): '''Load an image with Pillow and convert it to numpy array. Also returns the image DPI in x and y as a tuple.''' try: pil_img = Image.open(input_filename) except IOError: sys.stderr.write('warning: error opening {}\n'.format( input_filename)) return None, None if pil_img.mode != 'RGB': pil_img = pil_img.convert('RGB') if 'dpi' in pil_img.info: dpi = pil_img.info['dpi'] else: dpi = (300, 300) img = np.array(pil_img) return img, dpi ###################################################################### def sample_pixels(img, options): '''Pick a fixed percentage of pixels in the image, returned in random order.''' pixels = img.reshape((-1, 3)) num_pixels = pixels.shape[0] num_samples = int(num_pixels*options.sample_fraction) idx = np.arange(num_pixels) np.random.shuffle(idx) return pixels[idx[:num_samples]] ###################################################################### def get_fg_mask(bg_color, samples, options): '''Determine whether each pixel in a set of samples is foreground by comparing it to the background color. A pixel is classified as a foreground pixel if either its value or saturation differs from the background by a threshold.''' s_bg, v_bg = rgb_to_sv(bg_color) s_samples, v_samples = rgb_to_sv(samples) s_diff = np.abs(s_bg - s_samples) v_diff = np.abs(v_bg - v_samples) return ((v_diff >= options.value_threshold) | (s_diff >= options.sat_threshold)) ###################################################################### def get_palette(samples, options, return_mask=False, kmeans_iter=40): '''Extract the palette for the set of sampled RGB values. The first palette entry is always the background color; the rest are determined from foreground pixels by running K-means clustering. Returns the palette, as well as a mask corresponding to the foreground pixels. ''' if not options.quiet: print(' getting palette...') bg_color = get_bg_color(samples, 6) fg_mask = get_fg_mask(bg_color, samples, options) centers, _ = kmeans(samples[fg_mask].astype(np.float32), options.num_colors-1, iter=kmeans_iter) palette = np.vstack((bg_color, centers)).astype(np.uint8) if not return_mask: return palette else: return palette, fg_mask ###################################################################### def apply_palette(img, palette, options): '''Apply the pallete to the given image. The first step is to set all background pixels to the background color; then, nearest-neighbor matching is used to map each foreground color to the closest one in the palette. ''' if not options.quiet: print(' applying palette...') bg_color = palette[0] fg_mask = get_fg_mask(bg_color, img, options) orig_shape = img.shape pixels = img.reshape((-1, 3)) fg_mask = fg_mask.flatten() num_pixels = pixels.shape[0] labels = np.zeros(num_pixels, dtype=np.uint8) labels[fg_mask], _ = vq(pixels[fg_mask], palette) return labels.reshape(orig_shape[:-1]) ###################################################################### def save(output_filename, labels, palette, dpi, options): '''Save the label/palette pair out as an indexed PNG image. This optionally saturates the pallete by mapping the smallest color component to zero and the largest one to 255, and also optionally sets the background color to pure white. ''' if not options.quiet: print(' saving {}...'.format(output_filename)) if options.saturate: palette = palette.astype(np.float32) pmin = palette.min() pmax = palette.max() palette = 255 * (palette - pmin)/(pmax-pmin) palette = palette.astype(np.uint8) if options.white_bg: palette = palette.copy() palette[0] = (255, 255, 255) output_img = Image.fromarray(labels, 'P') output_img.putpalette(palette.flatten()) output_img.save(output_filename, dpi=dpi) ###################################################################### def get_global_palette(filenames, options): '''Fetch the global palette for a series of input files by merging their samples together into one large array. ''' input_filenames = [] all_samples = [] if not options.quiet: print('building global palette...') for input_filename in filenames: img, _ = load(input_filename) if img is None: continue if not options.quiet: print(' processing {}...'.format(input_filename)) samples = sample_pixels(img, options) input_filenames.append(input_filename) all_samples.append(samples) num_inputs = len(input_filenames) all_samples = [s[:int(round(float(s.shape[0])/num_inputs))] for s in all_samples] all_samples = np.vstack(tuple(all_samples)) global_palette = get_palette(all_samples, options) if not options.quiet: print(' done\n') return input_filenames, global_palette ###################################################################### def emit_pdf(outputs, options): '''Runs the PDF conversion command to generate the PDF.''' cmd = options.pdf_cmd cmd = cmd.replace('%o', options.pdfname) if len(outputs) > 2: cmd_print = cmd.replace('%i', ' '.join(outputs[:2] + ['...'])) else: cmd_print = cmd.replace('%i', ' '.join(outputs)) cmd = cmd.replace('%i', ' '.join(outputs)) if not options.quiet: print('running PDF command "{}"...'.format(cmd_print)) try: result = subprocess.call(shlex.split(cmd)) except OSError: result = -1 if result == 0: if not options.quiet: print(' wrote', options.pdfname) else: sys.stderr.write('warning: PDF command failed\n') ###################################################################### def notescan_main(options): '''Main function for this program when run as script.''' filenames = get_filenames(options) outputs = [] do_global = options.global_palette and len(filenames) > 1 if do_global: filenames, palette = get_global_palette(filenames, options) do_postprocess = bool(options.postprocess_cmd) for input_filename in filenames: img, dpi = load(input_filename) if img is None: continue output_filename = '{}{:04d}.png'.format( options.basename, len(outputs)) if not options.quiet: print('opened', input_filename) if not do_global: samples = sample_pixels(img, options) palette = get_palette(samples, options) labels = apply_palette(img, palette, options) save(output_filename, labels, palette, dpi, options) if do_postprocess: post_filename = postprocess(output_filename, options) if post_filename: output_filename = post_filename else: do_postprocess = False outputs.append(output_filename) if not options.quiet: print(' done\n') emit_pdf(outputs, options) ###################################################################### def main(): '''Parse args and call notescan_main().''' notescan_main(options=get_argument_parser().parse_args()) if __name__ == '__main__': main()
mzucker/noteshrink
noteshrink.py
get_filenames
python
def get_filenames(options): '''Get the filenames from the command line, optionally sorted by number, so that IMG_10.png is re-arranged to come after IMG_9.png. This is a nice feature because some scanner programs (like Image Capture on Mac OS X) automatically number files without leading zeros, and this way you can supply files using a wildcard and still have the pages ordered correctly. ''' if not options.sort_numerically: return options.filenames filenames = [] for filename in options.filenames: basename = os.path.basename(filename) root, _ = os.path.splitext(basename) matches = re.findall(r'[0-9]+', root) if matches: num = int(matches[-1]) else: num = -1 filenames.append((num, filename)) return [fn for (_, fn) in sorted(filenames)]
Get the filenames from the command line, optionally sorted by number, so that IMG_10.png is re-arranged to come after IMG_9.png. This is a nice feature because some scanner programs (like Image Capture on Mac OS X) automatically number files without leading zeros, and this way you can supply files using a wildcard and still have the pages ordered correctly.
train
https://github.com/mzucker/noteshrink/blob/7d876e5b43923c6bf8d64b7ef18f6855bfb30ce3/noteshrink.py#L281-L307
null
#!/usr/bin/env python '''Converts sequence of images to compact PDF while removing speckles, bleedthrough, etc. ''' # for some reason pylint complains about members being undefined :( # pylint: disable=E1101 from __future__ import print_function import sys import os import re import subprocess import shlex from argparse import ArgumentParser import numpy as np from PIL import Image from scipy.cluster.vq import kmeans, vq ###################################################################### def quantize(image, bits_per_channel=None): '''Reduces the number of bits per channel in the given image.''' if bits_per_channel is None: bits_per_channel = 6 assert image.dtype == np.uint8 shift = 8-bits_per_channel halfbin = (1 << shift) >> 1 return ((image.astype(int) >> shift) << shift) + halfbin ###################################################################### def pack_rgb(rgb): '''Packs a 24-bit RGB triples into a single integer, works on both arrays and tuples.''' orig_shape = None if isinstance(rgb, np.ndarray): assert rgb.shape[-1] == 3 orig_shape = rgb.shape[:-1] else: assert len(rgb) == 3 rgb = np.array(rgb) rgb = rgb.astype(int).reshape((-1, 3)) packed = (rgb[:, 0] << 16 | rgb[:, 1] << 8 | rgb[:, 2]) if orig_shape is None: return packed else: return packed.reshape(orig_shape) ###################################################################### def unpack_rgb(packed): '''Unpacks a single integer or array of integers into one or more 24-bit RGB values. ''' orig_shape = None if isinstance(packed, np.ndarray): assert packed.dtype == int orig_shape = packed.shape packed = packed.reshape((-1, 1)) rgb = ((packed >> 16) & 0xff, (packed >> 8) & 0xff, (packed) & 0xff) if orig_shape is None: return rgb else: return np.hstack(rgb).reshape(orig_shape + (3,)) ###################################################################### def get_bg_color(image, bits_per_channel=None): '''Obtains the background color from an image or array of RGB colors by grouping similar colors into bins and finding the most frequent one. ''' assert image.shape[-1] == 3 quantized = quantize(image, bits_per_channel).astype(int) packed = pack_rgb(quantized) unique, counts = np.unique(packed, return_counts=True) packed_mode = unique[counts.argmax()] return unpack_rgb(packed_mode) ###################################################################### def rgb_to_sv(rgb): '''Convert an RGB image or array of RGB colors to saturation and value, returning each one as a separate 32-bit floating point array or value. ''' if not isinstance(rgb, np.ndarray): rgb = np.array(rgb) axis = len(rgb.shape)-1 cmax = rgb.max(axis=axis).astype(np.float32) cmin = rgb.min(axis=axis).astype(np.float32) delta = cmax - cmin saturation = delta.astype(np.float32) / cmax.astype(np.float32) saturation = np.where(cmax == 0, 0, saturation) value = cmax/255.0 return saturation, value ###################################################################### def postprocess(output_filename, options): '''Runs the postprocessing command on the file provided.''' assert options.postprocess_cmd base, _ = os.path.splitext(output_filename) post_filename = base + options.postprocess_ext cmd = options.postprocess_cmd cmd = cmd.replace('%i', output_filename) cmd = cmd.replace('%o', post_filename) cmd = cmd.replace('%e', options.postprocess_ext) subprocess_args = shlex.split(cmd) if os.path.exists(post_filename): os.unlink(post_filename) if not options.quiet: print(' running "{}"...'.format(cmd), end=' ') sys.stdout.flush() try: result = subprocess.call(subprocess_args) before = os.stat(output_filename).st_size after = os.stat(post_filename).st_size except OSError: result = -1 if result == 0: if not options.quiet: print('{:.1f}% reduction'.format( 100*(1.0-float(after)/before))) return post_filename else: sys.stderr.write('warning: postprocessing failed!\n') return None ###################################################################### def percent(string): '''Convert a string (i.e. 85) to a fraction (i.e. .85).''' return float(string)/100.0 ###################################################################### def get_argument_parser(): '''Parse the command-line arguments for this program.''' parser = ArgumentParser( description='convert scanned, hand-written notes to PDF') show_default = ' (default %(default)s)' parser.add_argument('filenames', metavar='IMAGE', nargs='+', help='files to convert') parser.add_argument('-q', dest='quiet', action='store_true', default=False, help='reduce program output') parser.add_argument('-b', dest='basename', metavar='BASENAME', default='page', help='output PNG filename base' + show_default) parser.add_argument('-o', dest='pdfname', metavar='PDF', default='output.pdf', help='output PDF filename' + show_default) parser.add_argument('-v', dest='value_threshold', metavar='PERCENT', type=percent, default='25', help='background value threshold %%'+show_default) parser.add_argument('-s', dest='sat_threshold', metavar='PERCENT', type=percent, default='20', help='background saturation ' 'threshold %%'+show_default) parser.add_argument('-n', dest='num_colors', type=int, default='8', help='number of output colors '+show_default) parser.add_argument('-p', dest='sample_fraction', metavar='PERCENT', type=percent, default='5', help='%% of pixels to sample' + show_default) parser.add_argument('-w', dest='white_bg', action='store_true', default=False, help='make background white') parser.add_argument('-g', dest='global_palette', action='store_true', default=False, help='use one global palette for all pages') parser.add_argument('-S', dest='saturate', action='store_false', default=True, help='do not saturate colors') parser.add_argument('-K', dest='sort_numerically', action='store_false', default=True, help='keep filenames ordered as specified; ' 'use if you *really* want IMG_10.png to ' 'precede IMG_2.png') parser.add_argument('-P', dest='postprocess_cmd', default=None, help='set postprocessing command (see -O, -C, -Q)') parser.add_argument('-e', dest='postprocess_ext', default='_post.png', help='filename suffix/extension for ' 'postprocessing command') parser.add_argument('-O', dest='postprocess_cmd', action='store_const', const='optipng -silent %i -out %o', help='same as -P "%(const)s"') parser.add_argument('-C', dest='postprocess_cmd', action='store_const', const='pngcrush -q %i %o', help='same as -P "%(const)s"') parser.add_argument('-Q', dest='postprocess_cmd', action='store_const', const='pngquant --ext %e %i', help='same as -P "%(const)s"') parser.add_argument('-c', dest='pdf_cmd', metavar="COMMAND", default='convert %i %o', help='PDF command (default "%(default)s")') return parser ###################################################################### ###################################################################### def load(input_filename): '''Load an image with Pillow and convert it to numpy array. Also returns the image DPI in x and y as a tuple.''' try: pil_img = Image.open(input_filename) except IOError: sys.stderr.write('warning: error opening {}\n'.format( input_filename)) return None, None if pil_img.mode != 'RGB': pil_img = pil_img.convert('RGB') if 'dpi' in pil_img.info: dpi = pil_img.info['dpi'] else: dpi = (300, 300) img = np.array(pil_img) return img, dpi ###################################################################### def sample_pixels(img, options): '''Pick a fixed percentage of pixels in the image, returned in random order.''' pixels = img.reshape((-1, 3)) num_pixels = pixels.shape[0] num_samples = int(num_pixels*options.sample_fraction) idx = np.arange(num_pixels) np.random.shuffle(idx) return pixels[idx[:num_samples]] ###################################################################### def get_fg_mask(bg_color, samples, options): '''Determine whether each pixel in a set of samples is foreground by comparing it to the background color. A pixel is classified as a foreground pixel if either its value or saturation differs from the background by a threshold.''' s_bg, v_bg = rgb_to_sv(bg_color) s_samples, v_samples = rgb_to_sv(samples) s_diff = np.abs(s_bg - s_samples) v_diff = np.abs(v_bg - v_samples) return ((v_diff >= options.value_threshold) | (s_diff >= options.sat_threshold)) ###################################################################### def get_palette(samples, options, return_mask=False, kmeans_iter=40): '''Extract the palette for the set of sampled RGB values. The first palette entry is always the background color; the rest are determined from foreground pixels by running K-means clustering. Returns the palette, as well as a mask corresponding to the foreground pixels. ''' if not options.quiet: print(' getting palette...') bg_color = get_bg_color(samples, 6) fg_mask = get_fg_mask(bg_color, samples, options) centers, _ = kmeans(samples[fg_mask].astype(np.float32), options.num_colors-1, iter=kmeans_iter) palette = np.vstack((bg_color, centers)).astype(np.uint8) if not return_mask: return palette else: return palette, fg_mask ###################################################################### def apply_palette(img, palette, options): '''Apply the pallete to the given image. The first step is to set all background pixels to the background color; then, nearest-neighbor matching is used to map each foreground color to the closest one in the palette. ''' if not options.quiet: print(' applying palette...') bg_color = palette[0] fg_mask = get_fg_mask(bg_color, img, options) orig_shape = img.shape pixels = img.reshape((-1, 3)) fg_mask = fg_mask.flatten() num_pixels = pixels.shape[0] labels = np.zeros(num_pixels, dtype=np.uint8) labels[fg_mask], _ = vq(pixels[fg_mask], palette) return labels.reshape(orig_shape[:-1]) ###################################################################### def save(output_filename, labels, palette, dpi, options): '''Save the label/palette pair out as an indexed PNG image. This optionally saturates the pallete by mapping the smallest color component to zero and the largest one to 255, and also optionally sets the background color to pure white. ''' if not options.quiet: print(' saving {}...'.format(output_filename)) if options.saturate: palette = palette.astype(np.float32) pmin = palette.min() pmax = palette.max() palette = 255 * (palette - pmin)/(pmax-pmin) palette = palette.astype(np.uint8) if options.white_bg: palette = palette.copy() palette[0] = (255, 255, 255) output_img = Image.fromarray(labels, 'P') output_img.putpalette(palette.flatten()) output_img.save(output_filename, dpi=dpi) ###################################################################### def get_global_palette(filenames, options): '''Fetch the global palette for a series of input files by merging their samples together into one large array. ''' input_filenames = [] all_samples = [] if not options.quiet: print('building global palette...') for input_filename in filenames: img, _ = load(input_filename) if img is None: continue if not options.quiet: print(' processing {}...'.format(input_filename)) samples = sample_pixels(img, options) input_filenames.append(input_filename) all_samples.append(samples) num_inputs = len(input_filenames) all_samples = [s[:int(round(float(s.shape[0])/num_inputs))] for s in all_samples] all_samples = np.vstack(tuple(all_samples)) global_palette = get_palette(all_samples, options) if not options.quiet: print(' done\n') return input_filenames, global_palette ###################################################################### def emit_pdf(outputs, options): '''Runs the PDF conversion command to generate the PDF.''' cmd = options.pdf_cmd cmd = cmd.replace('%o', options.pdfname) if len(outputs) > 2: cmd_print = cmd.replace('%i', ' '.join(outputs[:2] + ['...'])) else: cmd_print = cmd.replace('%i', ' '.join(outputs)) cmd = cmd.replace('%i', ' '.join(outputs)) if not options.quiet: print('running PDF command "{}"...'.format(cmd_print)) try: result = subprocess.call(shlex.split(cmd)) except OSError: result = -1 if result == 0: if not options.quiet: print(' wrote', options.pdfname) else: sys.stderr.write('warning: PDF command failed\n') ###################################################################### def notescan_main(options): '''Main function for this program when run as script.''' filenames = get_filenames(options) outputs = [] do_global = options.global_palette and len(filenames) > 1 if do_global: filenames, palette = get_global_palette(filenames, options) do_postprocess = bool(options.postprocess_cmd) for input_filename in filenames: img, dpi = load(input_filename) if img is None: continue output_filename = '{}{:04d}.png'.format( options.basename, len(outputs)) if not options.quiet: print('opened', input_filename) if not do_global: samples = sample_pixels(img, options) palette = get_palette(samples, options) labels = apply_palette(img, palette, options) save(output_filename, labels, palette, dpi, options) if do_postprocess: post_filename = postprocess(output_filename, options) if post_filename: output_filename = post_filename else: do_postprocess = False outputs.append(output_filename) if not options.quiet: print(' done\n') emit_pdf(outputs, options) ###################################################################### def main(): '''Parse args and call notescan_main().''' notescan_main(options=get_argument_parser().parse_args()) if __name__ == '__main__': main()
mzucker/noteshrink
noteshrink.py
load
python
def load(input_filename): '''Load an image with Pillow and convert it to numpy array. Also returns the image DPI in x and y as a tuple.''' try: pil_img = Image.open(input_filename) except IOError: sys.stderr.write('warning: error opening {}\n'.format( input_filename)) return None, None if pil_img.mode != 'RGB': pil_img = pil_img.convert('RGB') if 'dpi' in pil_img.info: dpi = pil_img.info['dpi'] else: dpi = (300, 300) img = np.array(pil_img) return img, dpi
Load an image with Pillow and convert it to numpy array. Also returns the image DPI in x and y as a tuple.
train
https://github.com/mzucker/noteshrink/blob/7d876e5b43923c6bf8d64b7ef18f6855bfb30ce3/noteshrink.py#L311-L333
null
#!/usr/bin/env python '''Converts sequence of images to compact PDF while removing speckles, bleedthrough, etc. ''' # for some reason pylint complains about members being undefined :( # pylint: disable=E1101 from __future__ import print_function import sys import os import re import subprocess import shlex from argparse import ArgumentParser import numpy as np from PIL import Image from scipy.cluster.vq import kmeans, vq ###################################################################### def quantize(image, bits_per_channel=None): '''Reduces the number of bits per channel in the given image.''' if bits_per_channel is None: bits_per_channel = 6 assert image.dtype == np.uint8 shift = 8-bits_per_channel halfbin = (1 << shift) >> 1 return ((image.astype(int) >> shift) << shift) + halfbin ###################################################################### def pack_rgb(rgb): '''Packs a 24-bit RGB triples into a single integer, works on both arrays and tuples.''' orig_shape = None if isinstance(rgb, np.ndarray): assert rgb.shape[-1] == 3 orig_shape = rgb.shape[:-1] else: assert len(rgb) == 3 rgb = np.array(rgb) rgb = rgb.astype(int).reshape((-1, 3)) packed = (rgb[:, 0] << 16 | rgb[:, 1] << 8 | rgb[:, 2]) if orig_shape is None: return packed else: return packed.reshape(orig_shape) ###################################################################### def unpack_rgb(packed): '''Unpacks a single integer or array of integers into one or more 24-bit RGB values. ''' orig_shape = None if isinstance(packed, np.ndarray): assert packed.dtype == int orig_shape = packed.shape packed = packed.reshape((-1, 1)) rgb = ((packed >> 16) & 0xff, (packed >> 8) & 0xff, (packed) & 0xff) if orig_shape is None: return rgb else: return np.hstack(rgb).reshape(orig_shape + (3,)) ###################################################################### def get_bg_color(image, bits_per_channel=None): '''Obtains the background color from an image or array of RGB colors by grouping similar colors into bins and finding the most frequent one. ''' assert image.shape[-1] == 3 quantized = quantize(image, bits_per_channel).astype(int) packed = pack_rgb(quantized) unique, counts = np.unique(packed, return_counts=True) packed_mode = unique[counts.argmax()] return unpack_rgb(packed_mode) ###################################################################### def rgb_to_sv(rgb): '''Convert an RGB image or array of RGB colors to saturation and value, returning each one as a separate 32-bit floating point array or value. ''' if not isinstance(rgb, np.ndarray): rgb = np.array(rgb) axis = len(rgb.shape)-1 cmax = rgb.max(axis=axis).astype(np.float32) cmin = rgb.min(axis=axis).astype(np.float32) delta = cmax - cmin saturation = delta.astype(np.float32) / cmax.astype(np.float32) saturation = np.where(cmax == 0, 0, saturation) value = cmax/255.0 return saturation, value ###################################################################### def postprocess(output_filename, options): '''Runs the postprocessing command on the file provided.''' assert options.postprocess_cmd base, _ = os.path.splitext(output_filename) post_filename = base + options.postprocess_ext cmd = options.postprocess_cmd cmd = cmd.replace('%i', output_filename) cmd = cmd.replace('%o', post_filename) cmd = cmd.replace('%e', options.postprocess_ext) subprocess_args = shlex.split(cmd) if os.path.exists(post_filename): os.unlink(post_filename) if not options.quiet: print(' running "{}"...'.format(cmd), end=' ') sys.stdout.flush() try: result = subprocess.call(subprocess_args) before = os.stat(output_filename).st_size after = os.stat(post_filename).st_size except OSError: result = -1 if result == 0: if not options.quiet: print('{:.1f}% reduction'.format( 100*(1.0-float(after)/before))) return post_filename else: sys.stderr.write('warning: postprocessing failed!\n') return None ###################################################################### def percent(string): '''Convert a string (i.e. 85) to a fraction (i.e. .85).''' return float(string)/100.0 ###################################################################### def get_argument_parser(): '''Parse the command-line arguments for this program.''' parser = ArgumentParser( description='convert scanned, hand-written notes to PDF') show_default = ' (default %(default)s)' parser.add_argument('filenames', metavar='IMAGE', nargs='+', help='files to convert') parser.add_argument('-q', dest='quiet', action='store_true', default=False, help='reduce program output') parser.add_argument('-b', dest='basename', metavar='BASENAME', default='page', help='output PNG filename base' + show_default) parser.add_argument('-o', dest='pdfname', metavar='PDF', default='output.pdf', help='output PDF filename' + show_default) parser.add_argument('-v', dest='value_threshold', metavar='PERCENT', type=percent, default='25', help='background value threshold %%'+show_default) parser.add_argument('-s', dest='sat_threshold', metavar='PERCENT', type=percent, default='20', help='background saturation ' 'threshold %%'+show_default) parser.add_argument('-n', dest='num_colors', type=int, default='8', help='number of output colors '+show_default) parser.add_argument('-p', dest='sample_fraction', metavar='PERCENT', type=percent, default='5', help='%% of pixels to sample' + show_default) parser.add_argument('-w', dest='white_bg', action='store_true', default=False, help='make background white') parser.add_argument('-g', dest='global_palette', action='store_true', default=False, help='use one global palette for all pages') parser.add_argument('-S', dest='saturate', action='store_false', default=True, help='do not saturate colors') parser.add_argument('-K', dest='sort_numerically', action='store_false', default=True, help='keep filenames ordered as specified; ' 'use if you *really* want IMG_10.png to ' 'precede IMG_2.png') parser.add_argument('-P', dest='postprocess_cmd', default=None, help='set postprocessing command (see -O, -C, -Q)') parser.add_argument('-e', dest='postprocess_ext', default='_post.png', help='filename suffix/extension for ' 'postprocessing command') parser.add_argument('-O', dest='postprocess_cmd', action='store_const', const='optipng -silent %i -out %o', help='same as -P "%(const)s"') parser.add_argument('-C', dest='postprocess_cmd', action='store_const', const='pngcrush -q %i %o', help='same as -P "%(const)s"') parser.add_argument('-Q', dest='postprocess_cmd', action='store_const', const='pngquant --ext %e %i', help='same as -P "%(const)s"') parser.add_argument('-c', dest='pdf_cmd', metavar="COMMAND", default='convert %i %o', help='PDF command (default "%(default)s")') return parser ###################################################################### def get_filenames(options): '''Get the filenames from the command line, optionally sorted by number, so that IMG_10.png is re-arranged to come after IMG_9.png. This is a nice feature because some scanner programs (like Image Capture on Mac OS X) automatically number files without leading zeros, and this way you can supply files using a wildcard and still have the pages ordered correctly. ''' if not options.sort_numerically: return options.filenames filenames = [] for filename in options.filenames: basename = os.path.basename(filename) root, _ = os.path.splitext(basename) matches = re.findall(r'[0-9]+', root) if matches: num = int(matches[-1]) else: num = -1 filenames.append((num, filename)) return [fn for (_, fn) in sorted(filenames)] ###################################################################### ###################################################################### def sample_pixels(img, options): '''Pick a fixed percentage of pixels in the image, returned in random order.''' pixels = img.reshape((-1, 3)) num_pixels = pixels.shape[0] num_samples = int(num_pixels*options.sample_fraction) idx = np.arange(num_pixels) np.random.shuffle(idx) return pixels[idx[:num_samples]] ###################################################################### def get_fg_mask(bg_color, samples, options): '''Determine whether each pixel in a set of samples is foreground by comparing it to the background color. A pixel is classified as a foreground pixel if either its value or saturation differs from the background by a threshold.''' s_bg, v_bg = rgb_to_sv(bg_color) s_samples, v_samples = rgb_to_sv(samples) s_diff = np.abs(s_bg - s_samples) v_diff = np.abs(v_bg - v_samples) return ((v_diff >= options.value_threshold) | (s_diff >= options.sat_threshold)) ###################################################################### def get_palette(samples, options, return_mask=False, kmeans_iter=40): '''Extract the palette for the set of sampled RGB values. The first palette entry is always the background color; the rest are determined from foreground pixels by running K-means clustering. Returns the palette, as well as a mask corresponding to the foreground pixels. ''' if not options.quiet: print(' getting palette...') bg_color = get_bg_color(samples, 6) fg_mask = get_fg_mask(bg_color, samples, options) centers, _ = kmeans(samples[fg_mask].astype(np.float32), options.num_colors-1, iter=kmeans_iter) palette = np.vstack((bg_color, centers)).astype(np.uint8) if not return_mask: return palette else: return palette, fg_mask ###################################################################### def apply_palette(img, palette, options): '''Apply the pallete to the given image. The first step is to set all background pixels to the background color; then, nearest-neighbor matching is used to map each foreground color to the closest one in the palette. ''' if not options.quiet: print(' applying palette...') bg_color = palette[0] fg_mask = get_fg_mask(bg_color, img, options) orig_shape = img.shape pixels = img.reshape((-1, 3)) fg_mask = fg_mask.flatten() num_pixels = pixels.shape[0] labels = np.zeros(num_pixels, dtype=np.uint8) labels[fg_mask], _ = vq(pixels[fg_mask], palette) return labels.reshape(orig_shape[:-1]) ###################################################################### def save(output_filename, labels, palette, dpi, options): '''Save the label/palette pair out as an indexed PNG image. This optionally saturates the pallete by mapping the smallest color component to zero and the largest one to 255, and also optionally sets the background color to pure white. ''' if not options.quiet: print(' saving {}...'.format(output_filename)) if options.saturate: palette = palette.astype(np.float32) pmin = palette.min() pmax = palette.max() palette = 255 * (palette - pmin)/(pmax-pmin) palette = palette.astype(np.uint8) if options.white_bg: palette = palette.copy() palette[0] = (255, 255, 255) output_img = Image.fromarray(labels, 'P') output_img.putpalette(palette.flatten()) output_img.save(output_filename, dpi=dpi) ###################################################################### def get_global_palette(filenames, options): '''Fetch the global palette for a series of input files by merging their samples together into one large array. ''' input_filenames = [] all_samples = [] if not options.quiet: print('building global palette...') for input_filename in filenames: img, _ = load(input_filename) if img is None: continue if not options.quiet: print(' processing {}...'.format(input_filename)) samples = sample_pixels(img, options) input_filenames.append(input_filename) all_samples.append(samples) num_inputs = len(input_filenames) all_samples = [s[:int(round(float(s.shape[0])/num_inputs))] for s in all_samples] all_samples = np.vstack(tuple(all_samples)) global_palette = get_palette(all_samples, options) if not options.quiet: print(' done\n') return input_filenames, global_palette ###################################################################### def emit_pdf(outputs, options): '''Runs the PDF conversion command to generate the PDF.''' cmd = options.pdf_cmd cmd = cmd.replace('%o', options.pdfname) if len(outputs) > 2: cmd_print = cmd.replace('%i', ' '.join(outputs[:2] + ['...'])) else: cmd_print = cmd.replace('%i', ' '.join(outputs)) cmd = cmd.replace('%i', ' '.join(outputs)) if not options.quiet: print('running PDF command "{}"...'.format(cmd_print)) try: result = subprocess.call(shlex.split(cmd)) except OSError: result = -1 if result == 0: if not options.quiet: print(' wrote', options.pdfname) else: sys.stderr.write('warning: PDF command failed\n') ###################################################################### def notescan_main(options): '''Main function for this program when run as script.''' filenames = get_filenames(options) outputs = [] do_global = options.global_palette and len(filenames) > 1 if do_global: filenames, palette = get_global_palette(filenames, options) do_postprocess = bool(options.postprocess_cmd) for input_filename in filenames: img, dpi = load(input_filename) if img is None: continue output_filename = '{}{:04d}.png'.format( options.basename, len(outputs)) if not options.quiet: print('opened', input_filename) if not do_global: samples = sample_pixels(img, options) palette = get_palette(samples, options) labels = apply_palette(img, palette, options) save(output_filename, labels, palette, dpi, options) if do_postprocess: post_filename = postprocess(output_filename, options) if post_filename: output_filename = post_filename else: do_postprocess = False outputs.append(output_filename) if not options.quiet: print(' done\n') emit_pdf(outputs, options) ###################################################################### def main(): '''Parse args and call notescan_main().''' notescan_main(options=get_argument_parser().parse_args()) if __name__ == '__main__': main()
mzucker/noteshrink
noteshrink.py
sample_pixels
python
def sample_pixels(img, options): '''Pick a fixed percentage of pixels in the image, returned in random order.''' pixels = img.reshape((-1, 3)) num_pixels = pixels.shape[0] num_samples = int(num_pixels*options.sample_fraction) idx = np.arange(num_pixels) np.random.shuffle(idx) return pixels[idx[:num_samples]]
Pick a fixed percentage of pixels in the image, returned in random order.
train
https://github.com/mzucker/noteshrink/blob/7d876e5b43923c6bf8d64b7ef18f6855bfb30ce3/noteshrink.py#L337-L349
null
#!/usr/bin/env python '''Converts sequence of images to compact PDF while removing speckles, bleedthrough, etc. ''' # for some reason pylint complains about members being undefined :( # pylint: disable=E1101 from __future__ import print_function import sys import os import re import subprocess import shlex from argparse import ArgumentParser import numpy as np from PIL import Image from scipy.cluster.vq import kmeans, vq ###################################################################### def quantize(image, bits_per_channel=None): '''Reduces the number of bits per channel in the given image.''' if bits_per_channel is None: bits_per_channel = 6 assert image.dtype == np.uint8 shift = 8-bits_per_channel halfbin = (1 << shift) >> 1 return ((image.astype(int) >> shift) << shift) + halfbin ###################################################################### def pack_rgb(rgb): '''Packs a 24-bit RGB triples into a single integer, works on both arrays and tuples.''' orig_shape = None if isinstance(rgb, np.ndarray): assert rgb.shape[-1] == 3 orig_shape = rgb.shape[:-1] else: assert len(rgb) == 3 rgb = np.array(rgb) rgb = rgb.astype(int).reshape((-1, 3)) packed = (rgb[:, 0] << 16 | rgb[:, 1] << 8 | rgb[:, 2]) if orig_shape is None: return packed else: return packed.reshape(orig_shape) ###################################################################### def unpack_rgb(packed): '''Unpacks a single integer or array of integers into one or more 24-bit RGB values. ''' orig_shape = None if isinstance(packed, np.ndarray): assert packed.dtype == int orig_shape = packed.shape packed = packed.reshape((-1, 1)) rgb = ((packed >> 16) & 0xff, (packed >> 8) & 0xff, (packed) & 0xff) if orig_shape is None: return rgb else: return np.hstack(rgb).reshape(orig_shape + (3,)) ###################################################################### def get_bg_color(image, bits_per_channel=None): '''Obtains the background color from an image or array of RGB colors by grouping similar colors into bins and finding the most frequent one. ''' assert image.shape[-1] == 3 quantized = quantize(image, bits_per_channel).astype(int) packed = pack_rgb(quantized) unique, counts = np.unique(packed, return_counts=True) packed_mode = unique[counts.argmax()] return unpack_rgb(packed_mode) ###################################################################### def rgb_to_sv(rgb): '''Convert an RGB image or array of RGB colors to saturation and value, returning each one as a separate 32-bit floating point array or value. ''' if not isinstance(rgb, np.ndarray): rgb = np.array(rgb) axis = len(rgb.shape)-1 cmax = rgb.max(axis=axis).astype(np.float32) cmin = rgb.min(axis=axis).astype(np.float32) delta = cmax - cmin saturation = delta.astype(np.float32) / cmax.astype(np.float32) saturation = np.where(cmax == 0, 0, saturation) value = cmax/255.0 return saturation, value ###################################################################### def postprocess(output_filename, options): '''Runs the postprocessing command on the file provided.''' assert options.postprocess_cmd base, _ = os.path.splitext(output_filename) post_filename = base + options.postprocess_ext cmd = options.postprocess_cmd cmd = cmd.replace('%i', output_filename) cmd = cmd.replace('%o', post_filename) cmd = cmd.replace('%e', options.postprocess_ext) subprocess_args = shlex.split(cmd) if os.path.exists(post_filename): os.unlink(post_filename) if not options.quiet: print(' running "{}"...'.format(cmd), end=' ') sys.stdout.flush() try: result = subprocess.call(subprocess_args) before = os.stat(output_filename).st_size after = os.stat(post_filename).st_size except OSError: result = -1 if result == 0: if not options.quiet: print('{:.1f}% reduction'.format( 100*(1.0-float(after)/before))) return post_filename else: sys.stderr.write('warning: postprocessing failed!\n') return None ###################################################################### def percent(string): '''Convert a string (i.e. 85) to a fraction (i.e. .85).''' return float(string)/100.0 ###################################################################### def get_argument_parser(): '''Parse the command-line arguments for this program.''' parser = ArgumentParser( description='convert scanned, hand-written notes to PDF') show_default = ' (default %(default)s)' parser.add_argument('filenames', metavar='IMAGE', nargs='+', help='files to convert') parser.add_argument('-q', dest='quiet', action='store_true', default=False, help='reduce program output') parser.add_argument('-b', dest='basename', metavar='BASENAME', default='page', help='output PNG filename base' + show_default) parser.add_argument('-o', dest='pdfname', metavar='PDF', default='output.pdf', help='output PDF filename' + show_default) parser.add_argument('-v', dest='value_threshold', metavar='PERCENT', type=percent, default='25', help='background value threshold %%'+show_default) parser.add_argument('-s', dest='sat_threshold', metavar='PERCENT', type=percent, default='20', help='background saturation ' 'threshold %%'+show_default) parser.add_argument('-n', dest='num_colors', type=int, default='8', help='number of output colors '+show_default) parser.add_argument('-p', dest='sample_fraction', metavar='PERCENT', type=percent, default='5', help='%% of pixels to sample' + show_default) parser.add_argument('-w', dest='white_bg', action='store_true', default=False, help='make background white') parser.add_argument('-g', dest='global_palette', action='store_true', default=False, help='use one global palette for all pages') parser.add_argument('-S', dest='saturate', action='store_false', default=True, help='do not saturate colors') parser.add_argument('-K', dest='sort_numerically', action='store_false', default=True, help='keep filenames ordered as specified; ' 'use if you *really* want IMG_10.png to ' 'precede IMG_2.png') parser.add_argument('-P', dest='postprocess_cmd', default=None, help='set postprocessing command (see -O, -C, -Q)') parser.add_argument('-e', dest='postprocess_ext', default='_post.png', help='filename suffix/extension for ' 'postprocessing command') parser.add_argument('-O', dest='postprocess_cmd', action='store_const', const='optipng -silent %i -out %o', help='same as -P "%(const)s"') parser.add_argument('-C', dest='postprocess_cmd', action='store_const', const='pngcrush -q %i %o', help='same as -P "%(const)s"') parser.add_argument('-Q', dest='postprocess_cmd', action='store_const', const='pngquant --ext %e %i', help='same as -P "%(const)s"') parser.add_argument('-c', dest='pdf_cmd', metavar="COMMAND", default='convert %i %o', help='PDF command (default "%(default)s")') return parser ###################################################################### def get_filenames(options): '''Get the filenames from the command line, optionally sorted by number, so that IMG_10.png is re-arranged to come after IMG_9.png. This is a nice feature because some scanner programs (like Image Capture on Mac OS X) automatically number files without leading zeros, and this way you can supply files using a wildcard and still have the pages ordered correctly. ''' if not options.sort_numerically: return options.filenames filenames = [] for filename in options.filenames: basename = os.path.basename(filename) root, _ = os.path.splitext(basename) matches = re.findall(r'[0-9]+', root) if matches: num = int(matches[-1]) else: num = -1 filenames.append((num, filename)) return [fn for (_, fn) in sorted(filenames)] ###################################################################### def load(input_filename): '''Load an image with Pillow and convert it to numpy array. Also returns the image DPI in x and y as a tuple.''' try: pil_img = Image.open(input_filename) except IOError: sys.stderr.write('warning: error opening {}\n'.format( input_filename)) return None, None if pil_img.mode != 'RGB': pil_img = pil_img.convert('RGB') if 'dpi' in pil_img.info: dpi = pil_img.info['dpi'] else: dpi = (300, 300) img = np.array(pil_img) return img, dpi ###################################################################### ###################################################################### def get_fg_mask(bg_color, samples, options): '''Determine whether each pixel in a set of samples is foreground by comparing it to the background color. A pixel is classified as a foreground pixel if either its value or saturation differs from the background by a threshold.''' s_bg, v_bg = rgb_to_sv(bg_color) s_samples, v_samples = rgb_to_sv(samples) s_diff = np.abs(s_bg - s_samples) v_diff = np.abs(v_bg - v_samples) return ((v_diff >= options.value_threshold) | (s_diff >= options.sat_threshold)) ###################################################################### def get_palette(samples, options, return_mask=False, kmeans_iter=40): '''Extract the palette for the set of sampled RGB values. The first palette entry is always the background color; the rest are determined from foreground pixels by running K-means clustering. Returns the palette, as well as a mask corresponding to the foreground pixels. ''' if not options.quiet: print(' getting palette...') bg_color = get_bg_color(samples, 6) fg_mask = get_fg_mask(bg_color, samples, options) centers, _ = kmeans(samples[fg_mask].astype(np.float32), options.num_colors-1, iter=kmeans_iter) palette = np.vstack((bg_color, centers)).astype(np.uint8) if not return_mask: return palette else: return palette, fg_mask ###################################################################### def apply_palette(img, palette, options): '''Apply the pallete to the given image. The first step is to set all background pixels to the background color; then, nearest-neighbor matching is used to map each foreground color to the closest one in the palette. ''' if not options.quiet: print(' applying palette...') bg_color = palette[0] fg_mask = get_fg_mask(bg_color, img, options) orig_shape = img.shape pixels = img.reshape((-1, 3)) fg_mask = fg_mask.flatten() num_pixels = pixels.shape[0] labels = np.zeros(num_pixels, dtype=np.uint8) labels[fg_mask], _ = vq(pixels[fg_mask], palette) return labels.reshape(orig_shape[:-1]) ###################################################################### def save(output_filename, labels, palette, dpi, options): '''Save the label/palette pair out as an indexed PNG image. This optionally saturates the pallete by mapping the smallest color component to zero and the largest one to 255, and also optionally sets the background color to pure white. ''' if not options.quiet: print(' saving {}...'.format(output_filename)) if options.saturate: palette = palette.astype(np.float32) pmin = palette.min() pmax = palette.max() palette = 255 * (palette - pmin)/(pmax-pmin) palette = palette.astype(np.uint8) if options.white_bg: palette = palette.copy() palette[0] = (255, 255, 255) output_img = Image.fromarray(labels, 'P') output_img.putpalette(palette.flatten()) output_img.save(output_filename, dpi=dpi) ###################################################################### def get_global_palette(filenames, options): '''Fetch the global palette for a series of input files by merging their samples together into one large array. ''' input_filenames = [] all_samples = [] if not options.quiet: print('building global palette...') for input_filename in filenames: img, _ = load(input_filename) if img is None: continue if not options.quiet: print(' processing {}...'.format(input_filename)) samples = sample_pixels(img, options) input_filenames.append(input_filename) all_samples.append(samples) num_inputs = len(input_filenames) all_samples = [s[:int(round(float(s.shape[0])/num_inputs))] for s in all_samples] all_samples = np.vstack(tuple(all_samples)) global_palette = get_palette(all_samples, options) if not options.quiet: print(' done\n') return input_filenames, global_palette ###################################################################### def emit_pdf(outputs, options): '''Runs the PDF conversion command to generate the PDF.''' cmd = options.pdf_cmd cmd = cmd.replace('%o', options.pdfname) if len(outputs) > 2: cmd_print = cmd.replace('%i', ' '.join(outputs[:2] + ['...'])) else: cmd_print = cmd.replace('%i', ' '.join(outputs)) cmd = cmd.replace('%i', ' '.join(outputs)) if not options.quiet: print('running PDF command "{}"...'.format(cmd_print)) try: result = subprocess.call(shlex.split(cmd)) except OSError: result = -1 if result == 0: if not options.quiet: print(' wrote', options.pdfname) else: sys.stderr.write('warning: PDF command failed\n') ###################################################################### def notescan_main(options): '''Main function for this program when run as script.''' filenames = get_filenames(options) outputs = [] do_global = options.global_palette and len(filenames) > 1 if do_global: filenames, palette = get_global_palette(filenames, options) do_postprocess = bool(options.postprocess_cmd) for input_filename in filenames: img, dpi = load(input_filename) if img is None: continue output_filename = '{}{:04d}.png'.format( options.basename, len(outputs)) if not options.quiet: print('opened', input_filename) if not do_global: samples = sample_pixels(img, options) palette = get_palette(samples, options) labels = apply_palette(img, palette, options) save(output_filename, labels, palette, dpi, options) if do_postprocess: post_filename = postprocess(output_filename, options) if post_filename: output_filename = post_filename else: do_postprocess = False outputs.append(output_filename) if not options.quiet: print(' done\n') emit_pdf(outputs, options) ###################################################################### def main(): '''Parse args and call notescan_main().''' notescan_main(options=get_argument_parser().parse_args()) if __name__ == '__main__': main()
mzucker/noteshrink
noteshrink.py
get_fg_mask
python
def get_fg_mask(bg_color, samples, options): '''Determine whether each pixel in a set of samples is foreground by comparing it to the background color. A pixel is classified as a foreground pixel if either its value or saturation differs from the background by a threshold.''' s_bg, v_bg = rgb_to_sv(bg_color) s_samples, v_samples = rgb_to_sv(samples) s_diff = np.abs(s_bg - s_samples) v_diff = np.abs(v_bg - v_samples) return ((v_diff >= options.value_threshold) | (s_diff >= options.sat_threshold))
Determine whether each pixel in a set of samples is foreground by comparing it to the background color. A pixel is classified as a foreground pixel if either its value or saturation differs from the background by a threshold.
train
https://github.com/mzucker/noteshrink/blob/7d876e5b43923c6bf8d64b7ef18f6855bfb30ce3/noteshrink.py#L353-L367
[ "def rgb_to_sv(rgb):\n\n '''Convert an RGB image or array of RGB colors to saturation and\nvalue, returning each one as a separate 32-bit floating point array or\nvalue.\n\n '''\n\n if not isinstance(rgb, np.ndarray):\n rgb = np.array(rgb)\n\n axis = len(rgb.shape)-1\n cmax = rgb.max(axis=axis).astype(np.float32)\n cmin = rgb.min(axis=axis).astype(np.float32)\n delta = cmax - cmin\n\n saturation = delta.astype(np.float32) / cmax.astype(np.float32)\n saturation = np.where(cmax == 0, 0, saturation)\n\n value = cmax/255.0\n\n return saturation, value\n" ]
#!/usr/bin/env python '''Converts sequence of images to compact PDF while removing speckles, bleedthrough, etc. ''' # for some reason pylint complains about members being undefined :( # pylint: disable=E1101 from __future__ import print_function import sys import os import re import subprocess import shlex from argparse import ArgumentParser import numpy as np from PIL import Image from scipy.cluster.vq import kmeans, vq ###################################################################### def quantize(image, bits_per_channel=None): '''Reduces the number of bits per channel in the given image.''' if bits_per_channel is None: bits_per_channel = 6 assert image.dtype == np.uint8 shift = 8-bits_per_channel halfbin = (1 << shift) >> 1 return ((image.astype(int) >> shift) << shift) + halfbin ###################################################################### def pack_rgb(rgb): '''Packs a 24-bit RGB triples into a single integer, works on both arrays and tuples.''' orig_shape = None if isinstance(rgb, np.ndarray): assert rgb.shape[-1] == 3 orig_shape = rgb.shape[:-1] else: assert len(rgb) == 3 rgb = np.array(rgb) rgb = rgb.astype(int).reshape((-1, 3)) packed = (rgb[:, 0] << 16 | rgb[:, 1] << 8 | rgb[:, 2]) if orig_shape is None: return packed else: return packed.reshape(orig_shape) ###################################################################### def unpack_rgb(packed): '''Unpacks a single integer or array of integers into one or more 24-bit RGB values. ''' orig_shape = None if isinstance(packed, np.ndarray): assert packed.dtype == int orig_shape = packed.shape packed = packed.reshape((-1, 1)) rgb = ((packed >> 16) & 0xff, (packed >> 8) & 0xff, (packed) & 0xff) if orig_shape is None: return rgb else: return np.hstack(rgb).reshape(orig_shape + (3,)) ###################################################################### def get_bg_color(image, bits_per_channel=None): '''Obtains the background color from an image or array of RGB colors by grouping similar colors into bins and finding the most frequent one. ''' assert image.shape[-1] == 3 quantized = quantize(image, bits_per_channel).astype(int) packed = pack_rgb(quantized) unique, counts = np.unique(packed, return_counts=True) packed_mode = unique[counts.argmax()] return unpack_rgb(packed_mode) ###################################################################### def rgb_to_sv(rgb): '''Convert an RGB image or array of RGB colors to saturation and value, returning each one as a separate 32-bit floating point array or value. ''' if not isinstance(rgb, np.ndarray): rgb = np.array(rgb) axis = len(rgb.shape)-1 cmax = rgb.max(axis=axis).astype(np.float32) cmin = rgb.min(axis=axis).astype(np.float32) delta = cmax - cmin saturation = delta.astype(np.float32) / cmax.astype(np.float32) saturation = np.where(cmax == 0, 0, saturation) value = cmax/255.0 return saturation, value ###################################################################### def postprocess(output_filename, options): '''Runs the postprocessing command on the file provided.''' assert options.postprocess_cmd base, _ = os.path.splitext(output_filename) post_filename = base + options.postprocess_ext cmd = options.postprocess_cmd cmd = cmd.replace('%i', output_filename) cmd = cmd.replace('%o', post_filename) cmd = cmd.replace('%e', options.postprocess_ext) subprocess_args = shlex.split(cmd) if os.path.exists(post_filename): os.unlink(post_filename) if not options.quiet: print(' running "{}"...'.format(cmd), end=' ') sys.stdout.flush() try: result = subprocess.call(subprocess_args) before = os.stat(output_filename).st_size after = os.stat(post_filename).st_size except OSError: result = -1 if result == 0: if not options.quiet: print('{:.1f}% reduction'.format( 100*(1.0-float(after)/before))) return post_filename else: sys.stderr.write('warning: postprocessing failed!\n') return None ###################################################################### def percent(string): '''Convert a string (i.e. 85) to a fraction (i.e. .85).''' return float(string)/100.0 ###################################################################### def get_argument_parser(): '''Parse the command-line arguments for this program.''' parser = ArgumentParser( description='convert scanned, hand-written notes to PDF') show_default = ' (default %(default)s)' parser.add_argument('filenames', metavar='IMAGE', nargs='+', help='files to convert') parser.add_argument('-q', dest='quiet', action='store_true', default=False, help='reduce program output') parser.add_argument('-b', dest='basename', metavar='BASENAME', default='page', help='output PNG filename base' + show_default) parser.add_argument('-o', dest='pdfname', metavar='PDF', default='output.pdf', help='output PDF filename' + show_default) parser.add_argument('-v', dest='value_threshold', metavar='PERCENT', type=percent, default='25', help='background value threshold %%'+show_default) parser.add_argument('-s', dest='sat_threshold', metavar='PERCENT', type=percent, default='20', help='background saturation ' 'threshold %%'+show_default) parser.add_argument('-n', dest='num_colors', type=int, default='8', help='number of output colors '+show_default) parser.add_argument('-p', dest='sample_fraction', metavar='PERCENT', type=percent, default='5', help='%% of pixels to sample' + show_default) parser.add_argument('-w', dest='white_bg', action='store_true', default=False, help='make background white') parser.add_argument('-g', dest='global_palette', action='store_true', default=False, help='use one global palette for all pages') parser.add_argument('-S', dest='saturate', action='store_false', default=True, help='do not saturate colors') parser.add_argument('-K', dest='sort_numerically', action='store_false', default=True, help='keep filenames ordered as specified; ' 'use if you *really* want IMG_10.png to ' 'precede IMG_2.png') parser.add_argument('-P', dest='postprocess_cmd', default=None, help='set postprocessing command (see -O, -C, -Q)') parser.add_argument('-e', dest='postprocess_ext', default='_post.png', help='filename suffix/extension for ' 'postprocessing command') parser.add_argument('-O', dest='postprocess_cmd', action='store_const', const='optipng -silent %i -out %o', help='same as -P "%(const)s"') parser.add_argument('-C', dest='postprocess_cmd', action='store_const', const='pngcrush -q %i %o', help='same as -P "%(const)s"') parser.add_argument('-Q', dest='postprocess_cmd', action='store_const', const='pngquant --ext %e %i', help='same as -P "%(const)s"') parser.add_argument('-c', dest='pdf_cmd', metavar="COMMAND", default='convert %i %o', help='PDF command (default "%(default)s")') return parser ###################################################################### def get_filenames(options): '''Get the filenames from the command line, optionally sorted by number, so that IMG_10.png is re-arranged to come after IMG_9.png. This is a nice feature because some scanner programs (like Image Capture on Mac OS X) automatically number files without leading zeros, and this way you can supply files using a wildcard and still have the pages ordered correctly. ''' if not options.sort_numerically: return options.filenames filenames = [] for filename in options.filenames: basename = os.path.basename(filename) root, _ = os.path.splitext(basename) matches = re.findall(r'[0-9]+', root) if matches: num = int(matches[-1]) else: num = -1 filenames.append((num, filename)) return [fn for (_, fn) in sorted(filenames)] ###################################################################### def load(input_filename): '''Load an image with Pillow and convert it to numpy array. Also returns the image DPI in x and y as a tuple.''' try: pil_img = Image.open(input_filename) except IOError: sys.stderr.write('warning: error opening {}\n'.format( input_filename)) return None, None if pil_img.mode != 'RGB': pil_img = pil_img.convert('RGB') if 'dpi' in pil_img.info: dpi = pil_img.info['dpi'] else: dpi = (300, 300) img = np.array(pil_img) return img, dpi ###################################################################### def sample_pixels(img, options): '''Pick a fixed percentage of pixels in the image, returned in random order.''' pixels = img.reshape((-1, 3)) num_pixels = pixels.shape[0] num_samples = int(num_pixels*options.sample_fraction) idx = np.arange(num_pixels) np.random.shuffle(idx) return pixels[idx[:num_samples]] ###################################################################### ###################################################################### def get_palette(samples, options, return_mask=False, kmeans_iter=40): '''Extract the palette for the set of sampled RGB values. The first palette entry is always the background color; the rest are determined from foreground pixels by running K-means clustering. Returns the palette, as well as a mask corresponding to the foreground pixels. ''' if not options.quiet: print(' getting palette...') bg_color = get_bg_color(samples, 6) fg_mask = get_fg_mask(bg_color, samples, options) centers, _ = kmeans(samples[fg_mask].astype(np.float32), options.num_colors-1, iter=kmeans_iter) palette = np.vstack((bg_color, centers)).astype(np.uint8) if not return_mask: return palette else: return palette, fg_mask ###################################################################### def apply_palette(img, palette, options): '''Apply the pallete to the given image. The first step is to set all background pixels to the background color; then, nearest-neighbor matching is used to map each foreground color to the closest one in the palette. ''' if not options.quiet: print(' applying palette...') bg_color = palette[0] fg_mask = get_fg_mask(bg_color, img, options) orig_shape = img.shape pixels = img.reshape((-1, 3)) fg_mask = fg_mask.flatten() num_pixels = pixels.shape[0] labels = np.zeros(num_pixels, dtype=np.uint8) labels[fg_mask], _ = vq(pixels[fg_mask], palette) return labels.reshape(orig_shape[:-1]) ###################################################################### def save(output_filename, labels, palette, dpi, options): '''Save the label/palette pair out as an indexed PNG image. This optionally saturates the pallete by mapping the smallest color component to zero and the largest one to 255, and also optionally sets the background color to pure white. ''' if not options.quiet: print(' saving {}...'.format(output_filename)) if options.saturate: palette = palette.astype(np.float32) pmin = palette.min() pmax = palette.max() palette = 255 * (palette - pmin)/(pmax-pmin) palette = palette.astype(np.uint8) if options.white_bg: palette = palette.copy() palette[0] = (255, 255, 255) output_img = Image.fromarray(labels, 'P') output_img.putpalette(palette.flatten()) output_img.save(output_filename, dpi=dpi) ###################################################################### def get_global_palette(filenames, options): '''Fetch the global palette for a series of input files by merging their samples together into one large array. ''' input_filenames = [] all_samples = [] if not options.quiet: print('building global palette...') for input_filename in filenames: img, _ = load(input_filename) if img is None: continue if not options.quiet: print(' processing {}...'.format(input_filename)) samples = sample_pixels(img, options) input_filenames.append(input_filename) all_samples.append(samples) num_inputs = len(input_filenames) all_samples = [s[:int(round(float(s.shape[0])/num_inputs))] for s in all_samples] all_samples = np.vstack(tuple(all_samples)) global_palette = get_palette(all_samples, options) if not options.quiet: print(' done\n') return input_filenames, global_palette ###################################################################### def emit_pdf(outputs, options): '''Runs the PDF conversion command to generate the PDF.''' cmd = options.pdf_cmd cmd = cmd.replace('%o', options.pdfname) if len(outputs) > 2: cmd_print = cmd.replace('%i', ' '.join(outputs[:2] + ['...'])) else: cmd_print = cmd.replace('%i', ' '.join(outputs)) cmd = cmd.replace('%i', ' '.join(outputs)) if not options.quiet: print('running PDF command "{}"...'.format(cmd_print)) try: result = subprocess.call(shlex.split(cmd)) except OSError: result = -1 if result == 0: if not options.quiet: print(' wrote', options.pdfname) else: sys.stderr.write('warning: PDF command failed\n') ###################################################################### def notescan_main(options): '''Main function for this program when run as script.''' filenames = get_filenames(options) outputs = [] do_global = options.global_palette and len(filenames) > 1 if do_global: filenames, palette = get_global_palette(filenames, options) do_postprocess = bool(options.postprocess_cmd) for input_filename in filenames: img, dpi = load(input_filename) if img is None: continue output_filename = '{}{:04d}.png'.format( options.basename, len(outputs)) if not options.quiet: print('opened', input_filename) if not do_global: samples = sample_pixels(img, options) palette = get_palette(samples, options) labels = apply_palette(img, palette, options) save(output_filename, labels, palette, dpi, options) if do_postprocess: post_filename = postprocess(output_filename, options) if post_filename: output_filename = post_filename else: do_postprocess = False outputs.append(output_filename) if not options.quiet: print(' done\n') emit_pdf(outputs, options) ###################################################################### def main(): '''Parse args and call notescan_main().''' notescan_main(options=get_argument_parser().parse_args()) if __name__ == '__main__': main()
mzucker/noteshrink
noteshrink.py
get_palette
python
def get_palette(samples, options, return_mask=False, kmeans_iter=40): '''Extract the palette for the set of sampled RGB values. The first palette entry is always the background color; the rest are determined from foreground pixels by running K-means clustering. Returns the palette, as well as a mask corresponding to the foreground pixels. ''' if not options.quiet: print(' getting palette...') bg_color = get_bg_color(samples, 6) fg_mask = get_fg_mask(bg_color, samples, options) centers, _ = kmeans(samples[fg_mask].astype(np.float32), options.num_colors-1, iter=kmeans_iter) palette = np.vstack((bg_color, centers)).astype(np.uint8) if not return_mask: return palette else: return palette, fg_mask
Extract the palette for the set of sampled RGB values. The first palette entry is always the background color; the rest are determined from foreground pixels by running K-means clustering. Returns the palette, as well as a mask corresponding to the foreground pixels.
train
https://github.com/mzucker/noteshrink/blob/7d876e5b43923c6bf8d64b7ef18f6855bfb30ce3/noteshrink.py#L371-L396
[ "def get_bg_color(image, bits_per_channel=None):\n\n '''Obtains the background color from an image or array of RGB colors\nby grouping similar colors into bins and finding the most frequent\none.\n\n '''\n\n assert image.shape[-1] == 3\n\n quantized = quantize(image, bits_per_channel).astype(int)\n packed = pack_rgb(quantized)\n\n unique, counts = np.unique(packed, return_counts=True)\n\n packed_mode = unique[counts.argmax()]\n\n return unpack_rgb(packed_mode)\n", "def get_fg_mask(bg_color, samples, options):\n\n '''Determine whether each pixel in a set of samples is foreground by\ncomparing it to the background color. A pixel is classified as a\nforeground pixel if either its value or saturation differs from the\nbackground by a threshold.'''\n\n s_bg, v_bg = rgb_to_sv(bg_color)\n s_samples, v_samples = rgb_to_sv(samples)\n\n s_diff = np.abs(s_bg - s_samples)\n v_diff = np.abs(v_bg - v_samples)\n\n return ((v_diff >= options.value_threshold) |\n (s_diff >= options.sat_threshold))\n" ]
#!/usr/bin/env python '''Converts sequence of images to compact PDF while removing speckles, bleedthrough, etc. ''' # for some reason pylint complains about members being undefined :( # pylint: disable=E1101 from __future__ import print_function import sys import os import re import subprocess import shlex from argparse import ArgumentParser import numpy as np from PIL import Image from scipy.cluster.vq import kmeans, vq ###################################################################### def quantize(image, bits_per_channel=None): '''Reduces the number of bits per channel in the given image.''' if bits_per_channel is None: bits_per_channel = 6 assert image.dtype == np.uint8 shift = 8-bits_per_channel halfbin = (1 << shift) >> 1 return ((image.astype(int) >> shift) << shift) + halfbin ###################################################################### def pack_rgb(rgb): '''Packs a 24-bit RGB triples into a single integer, works on both arrays and tuples.''' orig_shape = None if isinstance(rgb, np.ndarray): assert rgb.shape[-1] == 3 orig_shape = rgb.shape[:-1] else: assert len(rgb) == 3 rgb = np.array(rgb) rgb = rgb.astype(int).reshape((-1, 3)) packed = (rgb[:, 0] << 16 | rgb[:, 1] << 8 | rgb[:, 2]) if orig_shape is None: return packed else: return packed.reshape(orig_shape) ###################################################################### def unpack_rgb(packed): '''Unpacks a single integer or array of integers into one or more 24-bit RGB values. ''' orig_shape = None if isinstance(packed, np.ndarray): assert packed.dtype == int orig_shape = packed.shape packed = packed.reshape((-1, 1)) rgb = ((packed >> 16) & 0xff, (packed >> 8) & 0xff, (packed) & 0xff) if orig_shape is None: return rgb else: return np.hstack(rgb).reshape(orig_shape + (3,)) ###################################################################### def get_bg_color(image, bits_per_channel=None): '''Obtains the background color from an image or array of RGB colors by grouping similar colors into bins and finding the most frequent one. ''' assert image.shape[-1] == 3 quantized = quantize(image, bits_per_channel).astype(int) packed = pack_rgb(quantized) unique, counts = np.unique(packed, return_counts=True) packed_mode = unique[counts.argmax()] return unpack_rgb(packed_mode) ###################################################################### def rgb_to_sv(rgb): '''Convert an RGB image or array of RGB colors to saturation and value, returning each one as a separate 32-bit floating point array or value. ''' if not isinstance(rgb, np.ndarray): rgb = np.array(rgb) axis = len(rgb.shape)-1 cmax = rgb.max(axis=axis).astype(np.float32) cmin = rgb.min(axis=axis).astype(np.float32) delta = cmax - cmin saturation = delta.astype(np.float32) / cmax.astype(np.float32) saturation = np.where(cmax == 0, 0, saturation) value = cmax/255.0 return saturation, value ###################################################################### def postprocess(output_filename, options): '''Runs the postprocessing command on the file provided.''' assert options.postprocess_cmd base, _ = os.path.splitext(output_filename) post_filename = base + options.postprocess_ext cmd = options.postprocess_cmd cmd = cmd.replace('%i', output_filename) cmd = cmd.replace('%o', post_filename) cmd = cmd.replace('%e', options.postprocess_ext) subprocess_args = shlex.split(cmd) if os.path.exists(post_filename): os.unlink(post_filename) if not options.quiet: print(' running "{}"...'.format(cmd), end=' ') sys.stdout.flush() try: result = subprocess.call(subprocess_args) before = os.stat(output_filename).st_size after = os.stat(post_filename).st_size except OSError: result = -1 if result == 0: if not options.quiet: print('{:.1f}% reduction'.format( 100*(1.0-float(after)/before))) return post_filename else: sys.stderr.write('warning: postprocessing failed!\n') return None ###################################################################### def percent(string): '''Convert a string (i.e. 85) to a fraction (i.e. .85).''' return float(string)/100.0 ###################################################################### def get_argument_parser(): '''Parse the command-line arguments for this program.''' parser = ArgumentParser( description='convert scanned, hand-written notes to PDF') show_default = ' (default %(default)s)' parser.add_argument('filenames', metavar='IMAGE', nargs='+', help='files to convert') parser.add_argument('-q', dest='quiet', action='store_true', default=False, help='reduce program output') parser.add_argument('-b', dest='basename', metavar='BASENAME', default='page', help='output PNG filename base' + show_default) parser.add_argument('-o', dest='pdfname', metavar='PDF', default='output.pdf', help='output PDF filename' + show_default) parser.add_argument('-v', dest='value_threshold', metavar='PERCENT', type=percent, default='25', help='background value threshold %%'+show_default) parser.add_argument('-s', dest='sat_threshold', metavar='PERCENT', type=percent, default='20', help='background saturation ' 'threshold %%'+show_default) parser.add_argument('-n', dest='num_colors', type=int, default='8', help='number of output colors '+show_default) parser.add_argument('-p', dest='sample_fraction', metavar='PERCENT', type=percent, default='5', help='%% of pixels to sample' + show_default) parser.add_argument('-w', dest='white_bg', action='store_true', default=False, help='make background white') parser.add_argument('-g', dest='global_palette', action='store_true', default=False, help='use one global palette for all pages') parser.add_argument('-S', dest='saturate', action='store_false', default=True, help='do not saturate colors') parser.add_argument('-K', dest='sort_numerically', action='store_false', default=True, help='keep filenames ordered as specified; ' 'use if you *really* want IMG_10.png to ' 'precede IMG_2.png') parser.add_argument('-P', dest='postprocess_cmd', default=None, help='set postprocessing command (see -O, -C, -Q)') parser.add_argument('-e', dest='postprocess_ext', default='_post.png', help='filename suffix/extension for ' 'postprocessing command') parser.add_argument('-O', dest='postprocess_cmd', action='store_const', const='optipng -silent %i -out %o', help='same as -P "%(const)s"') parser.add_argument('-C', dest='postprocess_cmd', action='store_const', const='pngcrush -q %i %o', help='same as -P "%(const)s"') parser.add_argument('-Q', dest='postprocess_cmd', action='store_const', const='pngquant --ext %e %i', help='same as -P "%(const)s"') parser.add_argument('-c', dest='pdf_cmd', metavar="COMMAND", default='convert %i %o', help='PDF command (default "%(default)s")') return parser ###################################################################### def get_filenames(options): '''Get the filenames from the command line, optionally sorted by number, so that IMG_10.png is re-arranged to come after IMG_9.png. This is a nice feature because some scanner programs (like Image Capture on Mac OS X) automatically number files without leading zeros, and this way you can supply files using a wildcard and still have the pages ordered correctly. ''' if not options.sort_numerically: return options.filenames filenames = [] for filename in options.filenames: basename = os.path.basename(filename) root, _ = os.path.splitext(basename) matches = re.findall(r'[0-9]+', root) if matches: num = int(matches[-1]) else: num = -1 filenames.append((num, filename)) return [fn for (_, fn) in sorted(filenames)] ###################################################################### def load(input_filename): '''Load an image with Pillow and convert it to numpy array. Also returns the image DPI in x and y as a tuple.''' try: pil_img = Image.open(input_filename) except IOError: sys.stderr.write('warning: error opening {}\n'.format( input_filename)) return None, None if pil_img.mode != 'RGB': pil_img = pil_img.convert('RGB') if 'dpi' in pil_img.info: dpi = pil_img.info['dpi'] else: dpi = (300, 300) img = np.array(pil_img) return img, dpi ###################################################################### def sample_pixels(img, options): '''Pick a fixed percentage of pixels in the image, returned in random order.''' pixels = img.reshape((-1, 3)) num_pixels = pixels.shape[0] num_samples = int(num_pixels*options.sample_fraction) idx = np.arange(num_pixels) np.random.shuffle(idx) return pixels[idx[:num_samples]] ###################################################################### def get_fg_mask(bg_color, samples, options): '''Determine whether each pixel in a set of samples is foreground by comparing it to the background color. A pixel is classified as a foreground pixel if either its value or saturation differs from the background by a threshold.''' s_bg, v_bg = rgb_to_sv(bg_color) s_samples, v_samples = rgb_to_sv(samples) s_diff = np.abs(s_bg - s_samples) v_diff = np.abs(v_bg - v_samples) return ((v_diff >= options.value_threshold) | (s_diff >= options.sat_threshold)) ###################################################################### ###################################################################### def apply_palette(img, palette, options): '''Apply the pallete to the given image. The first step is to set all background pixels to the background color; then, nearest-neighbor matching is used to map each foreground color to the closest one in the palette. ''' if not options.quiet: print(' applying palette...') bg_color = palette[0] fg_mask = get_fg_mask(bg_color, img, options) orig_shape = img.shape pixels = img.reshape((-1, 3)) fg_mask = fg_mask.flatten() num_pixels = pixels.shape[0] labels = np.zeros(num_pixels, dtype=np.uint8) labels[fg_mask], _ = vq(pixels[fg_mask], palette) return labels.reshape(orig_shape[:-1]) ###################################################################### def save(output_filename, labels, palette, dpi, options): '''Save the label/palette pair out as an indexed PNG image. This optionally saturates the pallete by mapping the smallest color component to zero and the largest one to 255, and also optionally sets the background color to pure white. ''' if not options.quiet: print(' saving {}...'.format(output_filename)) if options.saturate: palette = palette.astype(np.float32) pmin = palette.min() pmax = palette.max() palette = 255 * (palette - pmin)/(pmax-pmin) palette = palette.astype(np.uint8) if options.white_bg: palette = palette.copy() palette[0] = (255, 255, 255) output_img = Image.fromarray(labels, 'P') output_img.putpalette(palette.flatten()) output_img.save(output_filename, dpi=dpi) ###################################################################### def get_global_palette(filenames, options): '''Fetch the global palette for a series of input files by merging their samples together into one large array. ''' input_filenames = [] all_samples = [] if not options.quiet: print('building global palette...') for input_filename in filenames: img, _ = load(input_filename) if img is None: continue if not options.quiet: print(' processing {}...'.format(input_filename)) samples = sample_pixels(img, options) input_filenames.append(input_filename) all_samples.append(samples) num_inputs = len(input_filenames) all_samples = [s[:int(round(float(s.shape[0])/num_inputs))] for s in all_samples] all_samples = np.vstack(tuple(all_samples)) global_palette = get_palette(all_samples, options) if not options.quiet: print(' done\n') return input_filenames, global_palette ###################################################################### def emit_pdf(outputs, options): '''Runs the PDF conversion command to generate the PDF.''' cmd = options.pdf_cmd cmd = cmd.replace('%o', options.pdfname) if len(outputs) > 2: cmd_print = cmd.replace('%i', ' '.join(outputs[:2] + ['...'])) else: cmd_print = cmd.replace('%i', ' '.join(outputs)) cmd = cmd.replace('%i', ' '.join(outputs)) if not options.quiet: print('running PDF command "{}"...'.format(cmd_print)) try: result = subprocess.call(shlex.split(cmd)) except OSError: result = -1 if result == 0: if not options.quiet: print(' wrote', options.pdfname) else: sys.stderr.write('warning: PDF command failed\n') ###################################################################### def notescan_main(options): '''Main function for this program when run as script.''' filenames = get_filenames(options) outputs = [] do_global = options.global_palette and len(filenames) > 1 if do_global: filenames, palette = get_global_palette(filenames, options) do_postprocess = bool(options.postprocess_cmd) for input_filename in filenames: img, dpi = load(input_filename) if img is None: continue output_filename = '{}{:04d}.png'.format( options.basename, len(outputs)) if not options.quiet: print('opened', input_filename) if not do_global: samples = sample_pixels(img, options) palette = get_palette(samples, options) labels = apply_palette(img, palette, options) save(output_filename, labels, palette, dpi, options) if do_postprocess: post_filename = postprocess(output_filename, options) if post_filename: output_filename = post_filename else: do_postprocess = False outputs.append(output_filename) if not options.quiet: print(' done\n') emit_pdf(outputs, options) ###################################################################### def main(): '''Parse args and call notescan_main().''' notescan_main(options=get_argument_parser().parse_args()) if __name__ == '__main__': main()
mzucker/noteshrink
noteshrink.py
apply_palette
python
def apply_palette(img, palette, options): '''Apply the pallete to the given image. The first step is to set all background pixels to the background color; then, nearest-neighbor matching is used to map each foreground color to the closest one in the palette. ''' if not options.quiet: print(' applying palette...') bg_color = palette[0] fg_mask = get_fg_mask(bg_color, img, options) orig_shape = img.shape pixels = img.reshape((-1, 3)) fg_mask = fg_mask.flatten() num_pixels = pixels.shape[0] labels = np.zeros(num_pixels, dtype=np.uint8) labels[fg_mask], _ = vq(pixels[fg_mask], palette) return labels.reshape(orig_shape[:-1])
Apply the pallete to the given image. The first step is to set all background pixels to the background color; then, nearest-neighbor matching is used to map each foreground color to the closest one in the palette.
train
https://github.com/mzucker/noteshrink/blob/7d876e5b43923c6bf8d64b7ef18f6855bfb30ce3/noteshrink.py#L400-L427
[ "def get_fg_mask(bg_color, samples, options):\n\n '''Determine whether each pixel in a set of samples is foreground by\ncomparing it to the background color. A pixel is classified as a\nforeground pixel if either its value or saturation differs from the\nbackground by a threshold.'''\n\n s_bg, v_bg = rgb_to_sv(bg_color)\n s_samples, v_samples = rgb_to_sv(samples)\n\n s_diff = np.abs(s_bg - s_samples)\n v_diff = np.abs(v_bg - v_samples)\n\n return ((v_diff >= options.value_threshold) |\n (s_diff >= options.sat_threshold))\n" ]
#!/usr/bin/env python '''Converts sequence of images to compact PDF while removing speckles, bleedthrough, etc. ''' # for some reason pylint complains about members being undefined :( # pylint: disable=E1101 from __future__ import print_function import sys import os import re import subprocess import shlex from argparse import ArgumentParser import numpy as np from PIL import Image from scipy.cluster.vq import kmeans, vq ###################################################################### def quantize(image, bits_per_channel=None): '''Reduces the number of bits per channel in the given image.''' if bits_per_channel is None: bits_per_channel = 6 assert image.dtype == np.uint8 shift = 8-bits_per_channel halfbin = (1 << shift) >> 1 return ((image.astype(int) >> shift) << shift) + halfbin ###################################################################### def pack_rgb(rgb): '''Packs a 24-bit RGB triples into a single integer, works on both arrays and tuples.''' orig_shape = None if isinstance(rgb, np.ndarray): assert rgb.shape[-1] == 3 orig_shape = rgb.shape[:-1] else: assert len(rgb) == 3 rgb = np.array(rgb) rgb = rgb.astype(int).reshape((-1, 3)) packed = (rgb[:, 0] << 16 | rgb[:, 1] << 8 | rgb[:, 2]) if orig_shape is None: return packed else: return packed.reshape(orig_shape) ###################################################################### def unpack_rgb(packed): '''Unpacks a single integer or array of integers into one or more 24-bit RGB values. ''' orig_shape = None if isinstance(packed, np.ndarray): assert packed.dtype == int orig_shape = packed.shape packed = packed.reshape((-1, 1)) rgb = ((packed >> 16) & 0xff, (packed >> 8) & 0xff, (packed) & 0xff) if orig_shape is None: return rgb else: return np.hstack(rgb).reshape(orig_shape + (3,)) ###################################################################### def get_bg_color(image, bits_per_channel=None): '''Obtains the background color from an image or array of RGB colors by grouping similar colors into bins and finding the most frequent one. ''' assert image.shape[-1] == 3 quantized = quantize(image, bits_per_channel).astype(int) packed = pack_rgb(quantized) unique, counts = np.unique(packed, return_counts=True) packed_mode = unique[counts.argmax()] return unpack_rgb(packed_mode) ###################################################################### def rgb_to_sv(rgb): '''Convert an RGB image or array of RGB colors to saturation and value, returning each one as a separate 32-bit floating point array or value. ''' if not isinstance(rgb, np.ndarray): rgb = np.array(rgb) axis = len(rgb.shape)-1 cmax = rgb.max(axis=axis).astype(np.float32) cmin = rgb.min(axis=axis).astype(np.float32) delta = cmax - cmin saturation = delta.astype(np.float32) / cmax.astype(np.float32) saturation = np.where(cmax == 0, 0, saturation) value = cmax/255.0 return saturation, value ###################################################################### def postprocess(output_filename, options): '''Runs the postprocessing command on the file provided.''' assert options.postprocess_cmd base, _ = os.path.splitext(output_filename) post_filename = base + options.postprocess_ext cmd = options.postprocess_cmd cmd = cmd.replace('%i', output_filename) cmd = cmd.replace('%o', post_filename) cmd = cmd.replace('%e', options.postprocess_ext) subprocess_args = shlex.split(cmd) if os.path.exists(post_filename): os.unlink(post_filename) if not options.quiet: print(' running "{}"...'.format(cmd), end=' ') sys.stdout.flush() try: result = subprocess.call(subprocess_args) before = os.stat(output_filename).st_size after = os.stat(post_filename).st_size except OSError: result = -1 if result == 0: if not options.quiet: print('{:.1f}% reduction'.format( 100*(1.0-float(after)/before))) return post_filename else: sys.stderr.write('warning: postprocessing failed!\n') return None ###################################################################### def percent(string): '''Convert a string (i.e. 85) to a fraction (i.e. .85).''' return float(string)/100.0 ###################################################################### def get_argument_parser(): '''Parse the command-line arguments for this program.''' parser = ArgumentParser( description='convert scanned, hand-written notes to PDF') show_default = ' (default %(default)s)' parser.add_argument('filenames', metavar='IMAGE', nargs='+', help='files to convert') parser.add_argument('-q', dest='quiet', action='store_true', default=False, help='reduce program output') parser.add_argument('-b', dest='basename', metavar='BASENAME', default='page', help='output PNG filename base' + show_default) parser.add_argument('-o', dest='pdfname', metavar='PDF', default='output.pdf', help='output PDF filename' + show_default) parser.add_argument('-v', dest='value_threshold', metavar='PERCENT', type=percent, default='25', help='background value threshold %%'+show_default) parser.add_argument('-s', dest='sat_threshold', metavar='PERCENT', type=percent, default='20', help='background saturation ' 'threshold %%'+show_default) parser.add_argument('-n', dest='num_colors', type=int, default='8', help='number of output colors '+show_default) parser.add_argument('-p', dest='sample_fraction', metavar='PERCENT', type=percent, default='5', help='%% of pixels to sample' + show_default) parser.add_argument('-w', dest='white_bg', action='store_true', default=False, help='make background white') parser.add_argument('-g', dest='global_palette', action='store_true', default=False, help='use one global palette for all pages') parser.add_argument('-S', dest='saturate', action='store_false', default=True, help='do not saturate colors') parser.add_argument('-K', dest='sort_numerically', action='store_false', default=True, help='keep filenames ordered as specified; ' 'use if you *really* want IMG_10.png to ' 'precede IMG_2.png') parser.add_argument('-P', dest='postprocess_cmd', default=None, help='set postprocessing command (see -O, -C, -Q)') parser.add_argument('-e', dest='postprocess_ext', default='_post.png', help='filename suffix/extension for ' 'postprocessing command') parser.add_argument('-O', dest='postprocess_cmd', action='store_const', const='optipng -silent %i -out %o', help='same as -P "%(const)s"') parser.add_argument('-C', dest='postprocess_cmd', action='store_const', const='pngcrush -q %i %o', help='same as -P "%(const)s"') parser.add_argument('-Q', dest='postprocess_cmd', action='store_const', const='pngquant --ext %e %i', help='same as -P "%(const)s"') parser.add_argument('-c', dest='pdf_cmd', metavar="COMMAND", default='convert %i %o', help='PDF command (default "%(default)s")') return parser ###################################################################### def get_filenames(options): '''Get the filenames from the command line, optionally sorted by number, so that IMG_10.png is re-arranged to come after IMG_9.png. This is a nice feature because some scanner programs (like Image Capture on Mac OS X) automatically number files without leading zeros, and this way you can supply files using a wildcard and still have the pages ordered correctly. ''' if not options.sort_numerically: return options.filenames filenames = [] for filename in options.filenames: basename = os.path.basename(filename) root, _ = os.path.splitext(basename) matches = re.findall(r'[0-9]+', root) if matches: num = int(matches[-1]) else: num = -1 filenames.append((num, filename)) return [fn for (_, fn) in sorted(filenames)] ###################################################################### def load(input_filename): '''Load an image with Pillow and convert it to numpy array. Also returns the image DPI in x and y as a tuple.''' try: pil_img = Image.open(input_filename) except IOError: sys.stderr.write('warning: error opening {}\n'.format( input_filename)) return None, None if pil_img.mode != 'RGB': pil_img = pil_img.convert('RGB') if 'dpi' in pil_img.info: dpi = pil_img.info['dpi'] else: dpi = (300, 300) img = np.array(pil_img) return img, dpi ###################################################################### def sample_pixels(img, options): '''Pick a fixed percentage of pixels in the image, returned in random order.''' pixels = img.reshape((-1, 3)) num_pixels = pixels.shape[0] num_samples = int(num_pixels*options.sample_fraction) idx = np.arange(num_pixels) np.random.shuffle(idx) return pixels[idx[:num_samples]] ###################################################################### def get_fg_mask(bg_color, samples, options): '''Determine whether each pixel in a set of samples is foreground by comparing it to the background color. A pixel is classified as a foreground pixel if either its value or saturation differs from the background by a threshold.''' s_bg, v_bg = rgb_to_sv(bg_color) s_samples, v_samples = rgb_to_sv(samples) s_diff = np.abs(s_bg - s_samples) v_diff = np.abs(v_bg - v_samples) return ((v_diff >= options.value_threshold) | (s_diff >= options.sat_threshold)) ###################################################################### def get_palette(samples, options, return_mask=False, kmeans_iter=40): '''Extract the palette for the set of sampled RGB values. The first palette entry is always the background color; the rest are determined from foreground pixels by running K-means clustering. Returns the palette, as well as a mask corresponding to the foreground pixels. ''' if not options.quiet: print(' getting palette...') bg_color = get_bg_color(samples, 6) fg_mask = get_fg_mask(bg_color, samples, options) centers, _ = kmeans(samples[fg_mask].astype(np.float32), options.num_colors-1, iter=kmeans_iter) palette = np.vstack((bg_color, centers)).astype(np.uint8) if not return_mask: return palette else: return palette, fg_mask ###################################################################### ###################################################################### def save(output_filename, labels, palette, dpi, options): '''Save the label/palette pair out as an indexed PNG image. This optionally saturates the pallete by mapping the smallest color component to zero and the largest one to 255, and also optionally sets the background color to pure white. ''' if not options.quiet: print(' saving {}...'.format(output_filename)) if options.saturate: palette = palette.astype(np.float32) pmin = palette.min() pmax = palette.max() palette = 255 * (palette - pmin)/(pmax-pmin) palette = palette.astype(np.uint8) if options.white_bg: palette = palette.copy() palette[0] = (255, 255, 255) output_img = Image.fromarray(labels, 'P') output_img.putpalette(palette.flatten()) output_img.save(output_filename, dpi=dpi) ###################################################################### def get_global_palette(filenames, options): '''Fetch the global palette for a series of input files by merging their samples together into one large array. ''' input_filenames = [] all_samples = [] if not options.quiet: print('building global palette...') for input_filename in filenames: img, _ = load(input_filename) if img is None: continue if not options.quiet: print(' processing {}...'.format(input_filename)) samples = sample_pixels(img, options) input_filenames.append(input_filename) all_samples.append(samples) num_inputs = len(input_filenames) all_samples = [s[:int(round(float(s.shape[0])/num_inputs))] for s in all_samples] all_samples = np.vstack(tuple(all_samples)) global_palette = get_palette(all_samples, options) if not options.quiet: print(' done\n') return input_filenames, global_palette ###################################################################### def emit_pdf(outputs, options): '''Runs the PDF conversion command to generate the PDF.''' cmd = options.pdf_cmd cmd = cmd.replace('%o', options.pdfname) if len(outputs) > 2: cmd_print = cmd.replace('%i', ' '.join(outputs[:2] + ['...'])) else: cmd_print = cmd.replace('%i', ' '.join(outputs)) cmd = cmd.replace('%i', ' '.join(outputs)) if not options.quiet: print('running PDF command "{}"...'.format(cmd_print)) try: result = subprocess.call(shlex.split(cmd)) except OSError: result = -1 if result == 0: if not options.quiet: print(' wrote', options.pdfname) else: sys.stderr.write('warning: PDF command failed\n') ###################################################################### def notescan_main(options): '''Main function for this program when run as script.''' filenames = get_filenames(options) outputs = [] do_global = options.global_palette and len(filenames) > 1 if do_global: filenames, palette = get_global_palette(filenames, options) do_postprocess = bool(options.postprocess_cmd) for input_filename in filenames: img, dpi = load(input_filename) if img is None: continue output_filename = '{}{:04d}.png'.format( options.basename, len(outputs)) if not options.quiet: print('opened', input_filename) if not do_global: samples = sample_pixels(img, options) palette = get_palette(samples, options) labels = apply_palette(img, palette, options) save(output_filename, labels, palette, dpi, options) if do_postprocess: post_filename = postprocess(output_filename, options) if post_filename: output_filename = post_filename else: do_postprocess = False outputs.append(output_filename) if not options.quiet: print(' done\n') emit_pdf(outputs, options) ###################################################################### def main(): '''Parse args and call notescan_main().''' notescan_main(options=get_argument_parser().parse_args()) if __name__ == '__main__': main()
mzucker/noteshrink
noteshrink.py
save
python
def save(output_filename, labels, palette, dpi, options): '''Save the label/palette pair out as an indexed PNG image. This optionally saturates the pallete by mapping the smallest color component to zero and the largest one to 255, and also optionally sets the background color to pure white. ''' if not options.quiet: print(' saving {}...'.format(output_filename)) if options.saturate: palette = palette.astype(np.float32) pmin = palette.min() pmax = palette.max() palette = 255 * (palette - pmin)/(pmax-pmin) palette = palette.astype(np.uint8) if options.white_bg: palette = palette.copy() palette[0] = (255, 255, 255) output_img = Image.fromarray(labels, 'P') output_img.putpalette(palette.flatten()) output_img.save(output_filename, dpi=dpi)
Save the label/palette pair out as an indexed PNG image. This optionally saturates the pallete by mapping the smallest color component to zero and the largest one to 255, and also optionally sets the background color to pure white.
train
https://github.com/mzucker/noteshrink/blob/7d876e5b43923c6bf8d64b7ef18f6855bfb30ce3/noteshrink.py#L431-L456
null
#!/usr/bin/env python '''Converts sequence of images to compact PDF while removing speckles, bleedthrough, etc. ''' # for some reason pylint complains about members being undefined :( # pylint: disable=E1101 from __future__ import print_function import sys import os import re import subprocess import shlex from argparse import ArgumentParser import numpy as np from PIL import Image from scipy.cluster.vq import kmeans, vq ###################################################################### def quantize(image, bits_per_channel=None): '''Reduces the number of bits per channel in the given image.''' if bits_per_channel is None: bits_per_channel = 6 assert image.dtype == np.uint8 shift = 8-bits_per_channel halfbin = (1 << shift) >> 1 return ((image.astype(int) >> shift) << shift) + halfbin ###################################################################### def pack_rgb(rgb): '''Packs a 24-bit RGB triples into a single integer, works on both arrays and tuples.''' orig_shape = None if isinstance(rgb, np.ndarray): assert rgb.shape[-1] == 3 orig_shape = rgb.shape[:-1] else: assert len(rgb) == 3 rgb = np.array(rgb) rgb = rgb.astype(int).reshape((-1, 3)) packed = (rgb[:, 0] << 16 | rgb[:, 1] << 8 | rgb[:, 2]) if orig_shape is None: return packed else: return packed.reshape(orig_shape) ###################################################################### def unpack_rgb(packed): '''Unpacks a single integer or array of integers into one or more 24-bit RGB values. ''' orig_shape = None if isinstance(packed, np.ndarray): assert packed.dtype == int orig_shape = packed.shape packed = packed.reshape((-1, 1)) rgb = ((packed >> 16) & 0xff, (packed >> 8) & 0xff, (packed) & 0xff) if orig_shape is None: return rgb else: return np.hstack(rgb).reshape(orig_shape + (3,)) ###################################################################### def get_bg_color(image, bits_per_channel=None): '''Obtains the background color from an image or array of RGB colors by grouping similar colors into bins and finding the most frequent one. ''' assert image.shape[-1] == 3 quantized = quantize(image, bits_per_channel).astype(int) packed = pack_rgb(quantized) unique, counts = np.unique(packed, return_counts=True) packed_mode = unique[counts.argmax()] return unpack_rgb(packed_mode) ###################################################################### def rgb_to_sv(rgb): '''Convert an RGB image or array of RGB colors to saturation and value, returning each one as a separate 32-bit floating point array or value. ''' if not isinstance(rgb, np.ndarray): rgb = np.array(rgb) axis = len(rgb.shape)-1 cmax = rgb.max(axis=axis).astype(np.float32) cmin = rgb.min(axis=axis).astype(np.float32) delta = cmax - cmin saturation = delta.astype(np.float32) / cmax.astype(np.float32) saturation = np.where(cmax == 0, 0, saturation) value = cmax/255.0 return saturation, value ###################################################################### def postprocess(output_filename, options): '''Runs the postprocessing command on the file provided.''' assert options.postprocess_cmd base, _ = os.path.splitext(output_filename) post_filename = base + options.postprocess_ext cmd = options.postprocess_cmd cmd = cmd.replace('%i', output_filename) cmd = cmd.replace('%o', post_filename) cmd = cmd.replace('%e', options.postprocess_ext) subprocess_args = shlex.split(cmd) if os.path.exists(post_filename): os.unlink(post_filename) if not options.quiet: print(' running "{}"...'.format(cmd), end=' ') sys.stdout.flush() try: result = subprocess.call(subprocess_args) before = os.stat(output_filename).st_size after = os.stat(post_filename).st_size except OSError: result = -1 if result == 0: if not options.quiet: print('{:.1f}% reduction'.format( 100*(1.0-float(after)/before))) return post_filename else: sys.stderr.write('warning: postprocessing failed!\n') return None ###################################################################### def percent(string): '''Convert a string (i.e. 85) to a fraction (i.e. .85).''' return float(string)/100.0 ###################################################################### def get_argument_parser(): '''Parse the command-line arguments for this program.''' parser = ArgumentParser( description='convert scanned, hand-written notes to PDF') show_default = ' (default %(default)s)' parser.add_argument('filenames', metavar='IMAGE', nargs='+', help='files to convert') parser.add_argument('-q', dest='quiet', action='store_true', default=False, help='reduce program output') parser.add_argument('-b', dest='basename', metavar='BASENAME', default='page', help='output PNG filename base' + show_default) parser.add_argument('-o', dest='pdfname', metavar='PDF', default='output.pdf', help='output PDF filename' + show_default) parser.add_argument('-v', dest='value_threshold', metavar='PERCENT', type=percent, default='25', help='background value threshold %%'+show_default) parser.add_argument('-s', dest='sat_threshold', metavar='PERCENT', type=percent, default='20', help='background saturation ' 'threshold %%'+show_default) parser.add_argument('-n', dest='num_colors', type=int, default='8', help='number of output colors '+show_default) parser.add_argument('-p', dest='sample_fraction', metavar='PERCENT', type=percent, default='5', help='%% of pixels to sample' + show_default) parser.add_argument('-w', dest='white_bg', action='store_true', default=False, help='make background white') parser.add_argument('-g', dest='global_palette', action='store_true', default=False, help='use one global palette for all pages') parser.add_argument('-S', dest='saturate', action='store_false', default=True, help='do not saturate colors') parser.add_argument('-K', dest='sort_numerically', action='store_false', default=True, help='keep filenames ordered as specified; ' 'use if you *really* want IMG_10.png to ' 'precede IMG_2.png') parser.add_argument('-P', dest='postprocess_cmd', default=None, help='set postprocessing command (see -O, -C, -Q)') parser.add_argument('-e', dest='postprocess_ext', default='_post.png', help='filename suffix/extension for ' 'postprocessing command') parser.add_argument('-O', dest='postprocess_cmd', action='store_const', const='optipng -silent %i -out %o', help='same as -P "%(const)s"') parser.add_argument('-C', dest='postprocess_cmd', action='store_const', const='pngcrush -q %i %o', help='same as -P "%(const)s"') parser.add_argument('-Q', dest='postprocess_cmd', action='store_const', const='pngquant --ext %e %i', help='same as -P "%(const)s"') parser.add_argument('-c', dest='pdf_cmd', metavar="COMMAND", default='convert %i %o', help='PDF command (default "%(default)s")') return parser ###################################################################### def get_filenames(options): '''Get the filenames from the command line, optionally sorted by number, so that IMG_10.png is re-arranged to come after IMG_9.png. This is a nice feature because some scanner programs (like Image Capture on Mac OS X) automatically number files without leading zeros, and this way you can supply files using a wildcard and still have the pages ordered correctly. ''' if not options.sort_numerically: return options.filenames filenames = [] for filename in options.filenames: basename = os.path.basename(filename) root, _ = os.path.splitext(basename) matches = re.findall(r'[0-9]+', root) if matches: num = int(matches[-1]) else: num = -1 filenames.append((num, filename)) return [fn for (_, fn) in sorted(filenames)] ###################################################################### def load(input_filename): '''Load an image with Pillow and convert it to numpy array. Also returns the image DPI in x and y as a tuple.''' try: pil_img = Image.open(input_filename) except IOError: sys.stderr.write('warning: error opening {}\n'.format( input_filename)) return None, None if pil_img.mode != 'RGB': pil_img = pil_img.convert('RGB') if 'dpi' in pil_img.info: dpi = pil_img.info['dpi'] else: dpi = (300, 300) img = np.array(pil_img) return img, dpi ###################################################################### def sample_pixels(img, options): '''Pick a fixed percentage of pixels in the image, returned in random order.''' pixels = img.reshape((-1, 3)) num_pixels = pixels.shape[0] num_samples = int(num_pixels*options.sample_fraction) idx = np.arange(num_pixels) np.random.shuffle(idx) return pixels[idx[:num_samples]] ###################################################################### def get_fg_mask(bg_color, samples, options): '''Determine whether each pixel in a set of samples is foreground by comparing it to the background color. A pixel is classified as a foreground pixel if either its value or saturation differs from the background by a threshold.''' s_bg, v_bg = rgb_to_sv(bg_color) s_samples, v_samples = rgb_to_sv(samples) s_diff = np.abs(s_bg - s_samples) v_diff = np.abs(v_bg - v_samples) return ((v_diff >= options.value_threshold) | (s_diff >= options.sat_threshold)) ###################################################################### def get_palette(samples, options, return_mask=False, kmeans_iter=40): '''Extract the palette for the set of sampled RGB values. The first palette entry is always the background color; the rest are determined from foreground pixels by running K-means clustering. Returns the palette, as well as a mask corresponding to the foreground pixels. ''' if not options.quiet: print(' getting palette...') bg_color = get_bg_color(samples, 6) fg_mask = get_fg_mask(bg_color, samples, options) centers, _ = kmeans(samples[fg_mask].astype(np.float32), options.num_colors-1, iter=kmeans_iter) palette = np.vstack((bg_color, centers)).astype(np.uint8) if not return_mask: return palette else: return palette, fg_mask ###################################################################### def apply_palette(img, palette, options): '''Apply the pallete to the given image. The first step is to set all background pixels to the background color; then, nearest-neighbor matching is used to map each foreground color to the closest one in the palette. ''' if not options.quiet: print(' applying palette...') bg_color = palette[0] fg_mask = get_fg_mask(bg_color, img, options) orig_shape = img.shape pixels = img.reshape((-1, 3)) fg_mask = fg_mask.flatten() num_pixels = pixels.shape[0] labels = np.zeros(num_pixels, dtype=np.uint8) labels[fg_mask], _ = vq(pixels[fg_mask], palette) return labels.reshape(orig_shape[:-1]) ###################################################################### ###################################################################### def get_global_palette(filenames, options): '''Fetch the global palette for a series of input files by merging their samples together into one large array. ''' input_filenames = [] all_samples = [] if not options.quiet: print('building global palette...') for input_filename in filenames: img, _ = load(input_filename) if img is None: continue if not options.quiet: print(' processing {}...'.format(input_filename)) samples = sample_pixels(img, options) input_filenames.append(input_filename) all_samples.append(samples) num_inputs = len(input_filenames) all_samples = [s[:int(round(float(s.shape[0])/num_inputs))] for s in all_samples] all_samples = np.vstack(tuple(all_samples)) global_palette = get_palette(all_samples, options) if not options.quiet: print(' done\n') return input_filenames, global_palette ###################################################################### def emit_pdf(outputs, options): '''Runs the PDF conversion command to generate the PDF.''' cmd = options.pdf_cmd cmd = cmd.replace('%o', options.pdfname) if len(outputs) > 2: cmd_print = cmd.replace('%i', ' '.join(outputs[:2] + ['...'])) else: cmd_print = cmd.replace('%i', ' '.join(outputs)) cmd = cmd.replace('%i', ' '.join(outputs)) if not options.quiet: print('running PDF command "{}"...'.format(cmd_print)) try: result = subprocess.call(shlex.split(cmd)) except OSError: result = -1 if result == 0: if not options.quiet: print(' wrote', options.pdfname) else: sys.stderr.write('warning: PDF command failed\n') ###################################################################### def notescan_main(options): '''Main function for this program when run as script.''' filenames = get_filenames(options) outputs = [] do_global = options.global_palette and len(filenames) > 1 if do_global: filenames, palette = get_global_palette(filenames, options) do_postprocess = bool(options.postprocess_cmd) for input_filename in filenames: img, dpi = load(input_filename) if img is None: continue output_filename = '{}{:04d}.png'.format( options.basename, len(outputs)) if not options.quiet: print('opened', input_filename) if not do_global: samples = sample_pixels(img, options) palette = get_palette(samples, options) labels = apply_palette(img, palette, options) save(output_filename, labels, palette, dpi, options) if do_postprocess: post_filename = postprocess(output_filename, options) if post_filename: output_filename = post_filename else: do_postprocess = False outputs.append(output_filename) if not options.quiet: print(' done\n') emit_pdf(outputs, options) ###################################################################### def main(): '''Parse args and call notescan_main().''' notescan_main(options=get_argument_parser().parse_args()) if __name__ == '__main__': main()
mzucker/noteshrink
noteshrink.py
get_global_palette
python
def get_global_palette(filenames, options): '''Fetch the global palette for a series of input files by merging their samples together into one large array. ''' input_filenames = [] all_samples = [] if not options.quiet: print('building global palette...') for input_filename in filenames: img, _ = load(input_filename) if img is None: continue if not options.quiet: print(' processing {}...'.format(input_filename)) samples = sample_pixels(img, options) input_filenames.append(input_filename) all_samples.append(samples) num_inputs = len(input_filenames) all_samples = [s[:int(round(float(s.shape[0])/num_inputs))] for s in all_samples] all_samples = np.vstack(tuple(all_samples)) global_palette = get_palette(all_samples, options) if not options.quiet: print(' done\n') return input_filenames, global_palette
Fetch the global palette for a series of input files by merging their samples together into one large array.
train
https://github.com/mzucker/noteshrink/blob/7d876e5b43923c6bf8d64b7ef18f6855bfb30ce3/noteshrink.py#L460-L499
[ "def load(input_filename):\n\n '''Load an image with Pillow and convert it to numpy array. Also\nreturns the image DPI in x and y as a tuple.'''\n\n try:\n pil_img = Image.open(input_filename)\n except IOError:\n sys.stderr.write('warning: error opening {}\\n'.format(\n input_filename))\n return None, None\n\n if pil_img.mode != 'RGB':\n pil_img = pil_img.convert('RGB')\n\n if 'dpi' in pil_img.info:\n dpi = pil_img.info['dpi']\n else:\n dpi = (300, 300)\n\n img = np.array(pil_img)\n\n return img, dpi\n", "def sample_pixels(img, options):\n\n '''Pick a fixed percentage of pixels in the image, returned in random\norder.'''\n\n pixels = img.reshape((-1, 3))\n num_pixels = pixels.shape[0]\n num_samples = int(num_pixels*options.sample_fraction)\n\n idx = np.arange(num_pixels)\n np.random.shuffle(idx)\n\n return pixels[idx[:num_samples]]\n", "def get_palette(samples, options, return_mask=False, kmeans_iter=40):\n\n '''Extract the palette for the set of sampled RGB values. The first\npalette entry is always the background color; the rest are determined\nfrom foreground pixels by running K-means clustering. Returns the\npalette, as well as a mask corresponding to the foreground pixels.\n\n '''\n\n if not options.quiet:\n print(' getting palette...')\n\n bg_color = get_bg_color(samples, 6)\n\n fg_mask = get_fg_mask(bg_color, samples, options)\n\n centers, _ = kmeans(samples[fg_mask].astype(np.float32),\n options.num_colors-1,\n iter=kmeans_iter)\n\n palette = np.vstack((bg_color, centers)).astype(np.uint8)\n\n if not return_mask:\n return palette\n else:\n return palette, fg_mask\n" ]
#!/usr/bin/env python '''Converts sequence of images to compact PDF while removing speckles, bleedthrough, etc. ''' # for some reason pylint complains about members being undefined :( # pylint: disable=E1101 from __future__ import print_function import sys import os import re import subprocess import shlex from argparse import ArgumentParser import numpy as np from PIL import Image from scipy.cluster.vq import kmeans, vq ###################################################################### def quantize(image, bits_per_channel=None): '''Reduces the number of bits per channel in the given image.''' if bits_per_channel is None: bits_per_channel = 6 assert image.dtype == np.uint8 shift = 8-bits_per_channel halfbin = (1 << shift) >> 1 return ((image.astype(int) >> shift) << shift) + halfbin ###################################################################### def pack_rgb(rgb): '''Packs a 24-bit RGB triples into a single integer, works on both arrays and tuples.''' orig_shape = None if isinstance(rgb, np.ndarray): assert rgb.shape[-1] == 3 orig_shape = rgb.shape[:-1] else: assert len(rgb) == 3 rgb = np.array(rgb) rgb = rgb.astype(int).reshape((-1, 3)) packed = (rgb[:, 0] << 16 | rgb[:, 1] << 8 | rgb[:, 2]) if orig_shape is None: return packed else: return packed.reshape(orig_shape) ###################################################################### def unpack_rgb(packed): '''Unpacks a single integer or array of integers into one or more 24-bit RGB values. ''' orig_shape = None if isinstance(packed, np.ndarray): assert packed.dtype == int orig_shape = packed.shape packed = packed.reshape((-1, 1)) rgb = ((packed >> 16) & 0xff, (packed >> 8) & 0xff, (packed) & 0xff) if orig_shape is None: return rgb else: return np.hstack(rgb).reshape(orig_shape + (3,)) ###################################################################### def get_bg_color(image, bits_per_channel=None): '''Obtains the background color from an image or array of RGB colors by grouping similar colors into bins and finding the most frequent one. ''' assert image.shape[-1] == 3 quantized = quantize(image, bits_per_channel).astype(int) packed = pack_rgb(quantized) unique, counts = np.unique(packed, return_counts=True) packed_mode = unique[counts.argmax()] return unpack_rgb(packed_mode) ###################################################################### def rgb_to_sv(rgb): '''Convert an RGB image or array of RGB colors to saturation and value, returning each one as a separate 32-bit floating point array or value. ''' if not isinstance(rgb, np.ndarray): rgb = np.array(rgb) axis = len(rgb.shape)-1 cmax = rgb.max(axis=axis).astype(np.float32) cmin = rgb.min(axis=axis).astype(np.float32) delta = cmax - cmin saturation = delta.astype(np.float32) / cmax.astype(np.float32) saturation = np.where(cmax == 0, 0, saturation) value = cmax/255.0 return saturation, value ###################################################################### def postprocess(output_filename, options): '''Runs the postprocessing command on the file provided.''' assert options.postprocess_cmd base, _ = os.path.splitext(output_filename) post_filename = base + options.postprocess_ext cmd = options.postprocess_cmd cmd = cmd.replace('%i', output_filename) cmd = cmd.replace('%o', post_filename) cmd = cmd.replace('%e', options.postprocess_ext) subprocess_args = shlex.split(cmd) if os.path.exists(post_filename): os.unlink(post_filename) if not options.quiet: print(' running "{}"...'.format(cmd), end=' ') sys.stdout.flush() try: result = subprocess.call(subprocess_args) before = os.stat(output_filename).st_size after = os.stat(post_filename).st_size except OSError: result = -1 if result == 0: if not options.quiet: print('{:.1f}% reduction'.format( 100*(1.0-float(after)/before))) return post_filename else: sys.stderr.write('warning: postprocessing failed!\n') return None ###################################################################### def percent(string): '''Convert a string (i.e. 85) to a fraction (i.e. .85).''' return float(string)/100.0 ###################################################################### def get_argument_parser(): '''Parse the command-line arguments for this program.''' parser = ArgumentParser( description='convert scanned, hand-written notes to PDF') show_default = ' (default %(default)s)' parser.add_argument('filenames', metavar='IMAGE', nargs='+', help='files to convert') parser.add_argument('-q', dest='quiet', action='store_true', default=False, help='reduce program output') parser.add_argument('-b', dest='basename', metavar='BASENAME', default='page', help='output PNG filename base' + show_default) parser.add_argument('-o', dest='pdfname', metavar='PDF', default='output.pdf', help='output PDF filename' + show_default) parser.add_argument('-v', dest='value_threshold', metavar='PERCENT', type=percent, default='25', help='background value threshold %%'+show_default) parser.add_argument('-s', dest='sat_threshold', metavar='PERCENT', type=percent, default='20', help='background saturation ' 'threshold %%'+show_default) parser.add_argument('-n', dest='num_colors', type=int, default='8', help='number of output colors '+show_default) parser.add_argument('-p', dest='sample_fraction', metavar='PERCENT', type=percent, default='5', help='%% of pixels to sample' + show_default) parser.add_argument('-w', dest='white_bg', action='store_true', default=False, help='make background white') parser.add_argument('-g', dest='global_palette', action='store_true', default=False, help='use one global palette for all pages') parser.add_argument('-S', dest='saturate', action='store_false', default=True, help='do not saturate colors') parser.add_argument('-K', dest='sort_numerically', action='store_false', default=True, help='keep filenames ordered as specified; ' 'use if you *really* want IMG_10.png to ' 'precede IMG_2.png') parser.add_argument('-P', dest='postprocess_cmd', default=None, help='set postprocessing command (see -O, -C, -Q)') parser.add_argument('-e', dest='postprocess_ext', default='_post.png', help='filename suffix/extension for ' 'postprocessing command') parser.add_argument('-O', dest='postprocess_cmd', action='store_const', const='optipng -silent %i -out %o', help='same as -P "%(const)s"') parser.add_argument('-C', dest='postprocess_cmd', action='store_const', const='pngcrush -q %i %o', help='same as -P "%(const)s"') parser.add_argument('-Q', dest='postprocess_cmd', action='store_const', const='pngquant --ext %e %i', help='same as -P "%(const)s"') parser.add_argument('-c', dest='pdf_cmd', metavar="COMMAND", default='convert %i %o', help='PDF command (default "%(default)s")') return parser ###################################################################### def get_filenames(options): '''Get the filenames from the command line, optionally sorted by number, so that IMG_10.png is re-arranged to come after IMG_9.png. This is a nice feature because some scanner programs (like Image Capture on Mac OS X) automatically number files without leading zeros, and this way you can supply files using a wildcard and still have the pages ordered correctly. ''' if not options.sort_numerically: return options.filenames filenames = [] for filename in options.filenames: basename = os.path.basename(filename) root, _ = os.path.splitext(basename) matches = re.findall(r'[0-9]+', root) if matches: num = int(matches[-1]) else: num = -1 filenames.append((num, filename)) return [fn for (_, fn) in sorted(filenames)] ###################################################################### def load(input_filename): '''Load an image with Pillow and convert it to numpy array. Also returns the image DPI in x and y as a tuple.''' try: pil_img = Image.open(input_filename) except IOError: sys.stderr.write('warning: error opening {}\n'.format( input_filename)) return None, None if pil_img.mode != 'RGB': pil_img = pil_img.convert('RGB') if 'dpi' in pil_img.info: dpi = pil_img.info['dpi'] else: dpi = (300, 300) img = np.array(pil_img) return img, dpi ###################################################################### def sample_pixels(img, options): '''Pick a fixed percentage of pixels in the image, returned in random order.''' pixels = img.reshape((-1, 3)) num_pixels = pixels.shape[0] num_samples = int(num_pixels*options.sample_fraction) idx = np.arange(num_pixels) np.random.shuffle(idx) return pixels[idx[:num_samples]] ###################################################################### def get_fg_mask(bg_color, samples, options): '''Determine whether each pixel in a set of samples is foreground by comparing it to the background color. A pixel is classified as a foreground pixel if either its value or saturation differs from the background by a threshold.''' s_bg, v_bg = rgb_to_sv(bg_color) s_samples, v_samples = rgb_to_sv(samples) s_diff = np.abs(s_bg - s_samples) v_diff = np.abs(v_bg - v_samples) return ((v_diff >= options.value_threshold) | (s_diff >= options.sat_threshold)) ###################################################################### def get_palette(samples, options, return_mask=False, kmeans_iter=40): '''Extract the palette for the set of sampled RGB values. The first palette entry is always the background color; the rest are determined from foreground pixels by running K-means clustering. Returns the palette, as well as a mask corresponding to the foreground pixels. ''' if not options.quiet: print(' getting palette...') bg_color = get_bg_color(samples, 6) fg_mask = get_fg_mask(bg_color, samples, options) centers, _ = kmeans(samples[fg_mask].astype(np.float32), options.num_colors-1, iter=kmeans_iter) palette = np.vstack((bg_color, centers)).astype(np.uint8) if not return_mask: return palette else: return palette, fg_mask ###################################################################### def apply_palette(img, palette, options): '''Apply the pallete to the given image. The first step is to set all background pixels to the background color; then, nearest-neighbor matching is used to map each foreground color to the closest one in the palette. ''' if not options.quiet: print(' applying palette...') bg_color = palette[0] fg_mask = get_fg_mask(bg_color, img, options) orig_shape = img.shape pixels = img.reshape((-1, 3)) fg_mask = fg_mask.flatten() num_pixels = pixels.shape[0] labels = np.zeros(num_pixels, dtype=np.uint8) labels[fg_mask], _ = vq(pixels[fg_mask], palette) return labels.reshape(orig_shape[:-1]) ###################################################################### def save(output_filename, labels, palette, dpi, options): '''Save the label/palette pair out as an indexed PNG image. This optionally saturates the pallete by mapping the smallest color component to zero and the largest one to 255, and also optionally sets the background color to pure white. ''' if not options.quiet: print(' saving {}...'.format(output_filename)) if options.saturate: palette = palette.astype(np.float32) pmin = palette.min() pmax = palette.max() palette = 255 * (palette - pmin)/(pmax-pmin) palette = palette.astype(np.uint8) if options.white_bg: palette = palette.copy() palette[0] = (255, 255, 255) output_img = Image.fromarray(labels, 'P') output_img.putpalette(palette.flatten()) output_img.save(output_filename, dpi=dpi) ###################################################################### ###################################################################### def emit_pdf(outputs, options): '''Runs the PDF conversion command to generate the PDF.''' cmd = options.pdf_cmd cmd = cmd.replace('%o', options.pdfname) if len(outputs) > 2: cmd_print = cmd.replace('%i', ' '.join(outputs[:2] + ['...'])) else: cmd_print = cmd.replace('%i', ' '.join(outputs)) cmd = cmd.replace('%i', ' '.join(outputs)) if not options.quiet: print('running PDF command "{}"...'.format(cmd_print)) try: result = subprocess.call(shlex.split(cmd)) except OSError: result = -1 if result == 0: if not options.quiet: print(' wrote', options.pdfname) else: sys.stderr.write('warning: PDF command failed\n') ###################################################################### def notescan_main(options): '''Main function for this program when run as script.''' filenames = get_filenames(options) outputs = [] do_global = options.global_palette and len(filenames) > 1 if do_global: filenames, palette = get_global_palette(filenames, options) do_postprocess = bool(options.postprocess_cmd) for input_filename in filenames: img, dpi = load(input_filename) if img is None: continue output_filename = '{}{:04d}.png'.format( options.basename, len(outputs)) if not options.quiet: print('opened', input_filename) if not do_global: samples = sample_pixels(img, options) palette = get_palette(samples, options) labels = apply_palette(img, palette, options) save(output_filename, labels, palette, dpi, options) if do_postprocess: post_filename = postprocess(output_filename, options) if post_filename: output_filename = post_filename else: do_postprocess = False outputs.append(output_filename) if not options.quiet: print(' done\n') emit_pdf(outputs, options) ###################################################################### def main(): '''Parse args and call notescan_main().''' notescan_main(options=get_argument_parser().parse_args()) if __name__ == '__main__': main()
mzucker/noteshrink
noteshrink.py
emit_pdf
python
def emit_pdf(outputs, options): '''Runs the PDF conversion command to generate the PDF.''' cmd = options.pdf_cmd cmd = cmd.replace('%o', options.pdfname) if len(outputs) > 2: cmd_print = cmd.replace('%i', ' '.join(outputs[:2] + ['...'])) else: cmd_print = cmd.replace('%i', ' '.join(outputs)) cmd = cmd.replace('%i', ' '.join(outputs)) if not options.quiet: print('running PDF command "{}"...'.format(cmd_print)) try: result = subprocess.call(shlex.split(cmd)) except OSError: result = -1 if result == 0: if not options.quiet: print(' wrote', options.pdfname) else: sys.stderr.write('warning: PDF command failed\n')
Runs the PDF conversion command to generate the PDF.
train
https://github.com/mzucker/noteshrink/blob/7d876e5b43923c6bf8d64b7ef18f6855bfb30ce3/noteshrink.py#L503-L527
null
#!/usr/bin/env python '''Converts sequence of images to compact PDF while removing speckles, bleedthrough, etc. ''' # for some reason pylint complains about members being undefined :( # pylint: disable=E1101 from __future__ import print_function import sys import os import re import subprocess import shlex from argparse import ArgumentParser import numpy as np from PIL import Image from scipy.cluster.vq import kmeans, vq ###################################################################### def quantize(image, bits_per_channel=None): '''Reduces the number of bits per channel in the given image.''' if bits_per_channel is None: bits_per_channel = 6 assert image.dtype == np.uint8 shift = 8-bits_per_channel halfbin = (1 << shift) >> 1 return ((image.astype(int) >> shift) << shift) + halfbin ###################################################################### def pack_rgb(rgb): '''Packs a 24-bit RGB triples into a single integer, works on both arrays and tuples.''' orig_shape = None if isinstance(rgb, np.ndarray): assert rgb.shape[-1] == 3 orig_shape = rgb.shape[:-1] else: assert len(rgb) == 3 rgb = np.array(rgb) rgb = rgb.astype(int).reshape((-1, 3)) packed = (rgb[:, 0] << 16 | rgb[:, 1] << 8 | rgb[:, 2]) if orig_shape is None: return packed else: return packed.reshape(orig_shape) ###################################################################### def unpack_rgb(packed): '''Unpacks a single integer or array of integers into one or more 24-bit RGB values. ''' orig_shape = None if isinstance(packed, np.ndarray): assert packed.dtype == int orig_shape = packed.shape packed = packed.reshape((-1, 1)) rgb = ((packed >> 16) & 0xff, (packed >> 8) & 0xff, (packed) & 0xff) if orig_shape is None: return rgb else: return np.hstack(rgb).reshape(orig_shape + (3,)) ###################################################################### def get_bg_color(image, bits_per_channel=None): '''Obtains the background color from an image or array of RGB colors by grouping similar colors into bins and finding the most frequent one. ''' assert image.shape[-1] == 3 quantized = quantize(image, bits_per_channel).astype(int) packed = pack_rgb(quantized) unique, counts = np.unique(packed, return_counts=True) packed_mode = unique[counts.argmax()] return unpack_rgb(packed_mode) ###################################################################### def rgb_to_sv(rgb): '''Convert an RGB image or array of RGB colors to saturation and value, returning each one as a separate 32-bit floating point array or value. ''' if not isinstance(rgb, np.ndarray): rgb = np.array(rgb) axis = len(rgb.shape)-1 cmax = rgb.max(axis=axis).astype(np.float32) cmin = rgb.min(axis=axis).astype(np.float32) delta = cmax - cmin saturation = delta.astype(np.float32) / cmax.astype(np.float32) saturation = np.where(cmax == 0, 0, saturation) value = cmax/255.0 return saturation, value ###################################################################### def postprocess(output_filename, options): '''Runs the postprocessing command on the file provided.''' assert options.postprocess_cmd base, _ = os.path.splitext(output_filename) post_filename = base + options.postprocess_ext cmd = options.postprocess_cmd cmd = cmd.replace('%i', output_filename) cmd = cmd.replace('%o', post_filename) cmd = cmd.replace('%e', options.postprocess_ext) subprocess_args = shlex.split(cmd) if os.path.exists(post_filename): os.unlink(post_filename) if not options.quiet: print(' running "{}"...'.format(cmd), end=' ') sys.stdout.flush() try: result = subprocess.call(subprocess_args) before = os.stat(output_filename).st_size after = os.stat(post_filename).st_size except OSError: result = -1 if result == 0: if not options.quiet: print('{:.1f}% reduction'.format( 100*(1.0-float(after)/before))) return post_filename else: sys.stderr.write('warning: postprocessing failed!\n') return None ###################################################################### def percent(string): '''Convert a string (i.e. 85) to a fraction (i.e. .85).''' return float(string)/100.0 ###################################################################### def get_argument_parser(): '''Parse the command-line arguments for this program.''' parser = ArgumentParser( description='convert scanned, hand-written notes to PDF') show_default = ' (default %(default)s)' parser.add_argument('filenames', metavar='IMAGE', nargs='+', help='files to convert') parser.add_argument('-q', dest='quiet', action='store_true', default=False, help='reduce program output') parser.add_argument('-b', dest='basename', metavar='BASENAME', default='page', help='output PNG filename base' + show_default) parser.add_argument('-o', dest='pdfname', metavar='PDF', default='output.pdf', help='output PDF filename' + show_default) parser.add_argument('-v', dest='value_threshold', metavar='PERCENT', type=percent, default='25', help='background value threshold %%'+show_default) parser.add_argument('-s', dest='sat_threshold', metavar='PERCENT', type=percent, default='20', help='background saturation ' 'threshold %%'+show_default) parser.add_argument('-n', dest='num_colors', type=int, default='8', help='number of output colors '+show_default) parser.add_argument('-p', dest='sample_fraction', metavar='PERCENT', type=percent, default='5', help='%% of pixels to sample' + show_default) parser.add_argument('-w', dest='white_bg', action='store_true', default=False, help='make background white') parser.add_argument('-g', dest='global_palette', action='store_true', default=False, help='use one global palette for all pages') parser.add_argument('-S', dest='saturate', action='store_false', default=True, help='do not saturate colors') parser.add_argument('-K', dest='sort_numerically', action='store_false', default=True, help='keep filenames ordered as specified; ' 'use if you *really* want IMG_10.png to ' 'precede IMG_2.png') parser.add_argument('-P', dest='postprocess_cmd', default=None, help='set postprocessing command (see -O, -C, -Q)') parser.add_argument('-e', dest='postprocess_ext', default='_post.png', help='filename suffix/extension for ' 'postprocessing command') parser.add_argument('-O', dest='postprocess_cmd', action='store_const', const='optipng -silent %i -out %o', help='same as -P "%(const)s"') parser.add_argument('-C', dest='postprocess_cmd', action='store_const', const='pngcrush -q %i %o', help='same as -P "%(const)s"') parser.add_argument('-Q', dest='postprocess_cmd', action='store_const', const='pngquant --ext %e %i', help='same as -P "%(const)s"') parser.add_argument('-c', dest='pdf_cmd', metavar="COMMAND", default='convert %i %o', help='PDF command (default "%(default)s")') return parser ###################################################################### def get_filenames(options): '''Get the filenames from the command line, optionally sorted by number, so that IMG_10.png is re-arranged to come after IMG_9.png. This is a nice feature because some scanner programs (like Image Capture on Mac OS X) automatically number files without leading zeros, and this way you can supply files using a wildcard and still have the pages ordered correctly. ''' if not options.sort_numerically: return options.filenames filenames = [] for filename in options.filenames: basename = os.path.basename(filename) root, _ = os.path.splitext(basename) matches = re.findall(r'[0-9]+', root) if matches: num = int(matches[-1]) else: num = -1 filenames.append((num, filename)) return [fn for (_, fn) in sorted(filenames)] ###################################################################### def load(input_filename): '''Load an image with Pillow and convert it to numpy array. Also returns the image DPI in x and y as a tuple.''' try: pil_img = Image.open(input_filename) except IOError: sys.stderr.write('warning: error opening {}\n'.format( input_filename)) return None, None if pil_img.mode != 'RGB': pil_img = pil_img.convert('RGB') if 'dpi' in pil_img.info: dpi = pil_img.info['dpi'] else: dpi = (300, 300) img = np.array(pil_img) return img, dpi ###################################################################### def sample_pixels(img, options): '''Pick a fixed percentage of pixels in the image, returned in random order.''' pixels = img.reshape((-1, 3)) num_pixels = pixels.shape[0] num_samples = int(num_pixels*options.sample_fraction) idx = np.arange(num_pixels) np.random.shuffle(idx) return pixels[idx[:num_samples]] ###################################################################### def get_fg_mask(bg_color, samples, options): '''Determine whether each pixel in a set of samples is foreground by comparing it to the background color. A pixel is classified as a foreground pixel if either its value or saturation differs from the background by a threshold.''' s_bg, v_bg = rgb_to_sv(bg_color) s_samples, v_samples = rgb_to_sv(samples) s_diff = np.abs(s_bg - s_samples) v_diff = np.abs(v_bg - v_samples) return ((v_diff >= options.value_threshold) | (s_diff >= options.sat_threshold)) ###################################################################### def get_palette(samples, options, return_mask=False, kmeans_iter=40): '''Extract the palette for the set of sampled RGB values. The first palette entry is always the background color; the rest are determined from foreground pixels by running K-means clustering. Returns the palette, as well as a mask corresponding to the foreground pixels. ''' if not options.quiet: print(' getting palette...') bg_color = get_bg_color(samples, 6) fg_mask = get_fg_mask(bg_color, samples, options) centers, _ = kmeans(samples[fg_mask].astype(np.float32), options.num_colors-1, iter=kmeans_iter) palette = np.vstack((bg_color, centers)).astype(np.uint8) if not return_mask: return palette else: return palette, fg_mask ###################################################################### def apply_palette(img, palette, options): '''Apply the pallete to the given image. The first step is to set all background pixels to the background color; then, nearest-neighbor matching is used to map each foreground color to the closest one in the palette. ''' if not options.quiet: print(' applying palette...') bg_color = palette[0] fg_mask = get_fg_mask(bg_color, img, options) orig_shape = img.shape pixels = img.reshape((-1, 3)) fg_mask = fg_mask.flatten() num_pixels = pixels.shape[0] labels = np.zeros(num_pixels, dtype=np.uint8) labels[fg_mask], _ = vq(pixels[fg_mask], palette) return labels.reshape(orig_shape[:-1]) ###################################################################### def save(output_filename, labels, palette, dpi, options): '''Save the label/palette pair out as an indexed PNG image. This optionally saturates the pallete by mapping the smallest color component to zero and the largest one to 255, and also optionally sets the background color to pure white. ''' if not options.quiet: print(' saving {}...'.format(output_filename)) if options.saturate: palette = palette.astype(np.float32) pmin = palette.min() pmax = palette.max() palette = 255 * (palette - pmin)/(pmax-pmin) palette = palette.astype(np.uint8) if options.white_bg: palette = palette.copy() palette[0] = (255, 255, 255) output_img = Image.fromarray(labels, 'P') output_img.putpalette(palette.flatten()) output_img.save(output_filename, dpi=dpi) ###################################################################### def get_global_palette(filenames, options): '''Fetch the global palette for a series of input files by merging their samples together into one large array. ''' input_filenames = [] all_samples = [] if not options.quiet: print('building global palette...') for input_filename in filenames: img, _ = load(input_filename) if img is None: continue if not options.quiet: print(' processing {}...'.format(input_filename)) samples = sample_pixels(img, options) input_filenames.append(input_filename) all_samples.append(samples) num_inputs = len(input_filenames) all_samples = [s[:int(round(float(s.shape[0])/num_inputs))] for s in all_samples] all_samples = np.vstack(tuple(all_samples)) global_palette = get_palette(all_samples, options) if not options.quiet: print(' done\n') return input_filenames, global_palette ###################################################################### ###################################################################### def notescan_main(options): '''Main function for this program when run as script.''' filenames = get_filenames(options) outputs = [] do_global = options.global_palette and len(filenames) > 1 if do_global: filenames, palette = get_global_palette(filenames, options) do_postprocess = bool(options.postprocess_cmd) for input_filename in filenames: img, dpi = load(input_filename) if img is None: continue output_filename = '{}{:04d}.png'.format( options.basename, len(outputs)) if not options.quiet: print('opened', input_filename) if not do_global: samples = sample_pixels(img, options) palette = get_palette(samples, options) labels = apply_palette(img, palette, options) save(output_filename, labels, palette, dpi, options) if do_postprocess: post_filename = postprocess(output_filename, options) if post_filename: output_filename = post_filename else: do_postprocess = False outputs.append(output_filename) if not options.quiet: print(' done\n') emit_pdf(outputs, options) ###################################################################### def main(): '''Parse args and call notescan_main().''' notescan_main(options=get_argument_parser().parse_args()) if __name__ == '__main__': main()
mzucker/noteshrink
noteshrink.py
notescan_main
python
def notescan_main(options): '''Main function for this program when run as script.''' filenames = get_filenames(options) outputs = [] do_global = options.global_palette and len(filenames) > 1 if do_global: filenames, palette = get_global_palette(filenames, options) do_postprocess = bool(options.postprocess_cmd) for input_filename in filenames: img, dpi = load(input_filename) if img is None: continue output_filename = '{}{:04d}.png'.format( options.basename, len(outputs)) if not options.quiet: print('opened', input_filename) if not do_global: samples = sample_pixels(img, options) palette = get_palette(samples, options) labels = apply_palette(img, palette, options) save(output_filename, labels, palette, dpi, options) if do_postprocess: post_filename = postprocess(output_filename, options) if post_filename: output_filename = post_filename else: do_postprocess = False outputs.append(output_filename) if not options.quiet: print(' done\n') emit_pdf(outputs, options)
Main function for this program when run as script.
train
https://github.com/mzucker/noteshrink/blob/7d876e5b43923c6bf8d64b7ef18f6855bfb30ce3/noteshrink.py#L531-L578
[ "def get_filenames(options):\n\n '''Get the filenames from the command line, optionally sorted by\nnumber, so that IMG_10.png is re-arranged to come after IMG_9.png.\nThis is a nice feature because some scanner programs (like Image\nCapture on Mac OS X) automatically number files without leading zeros,\nand this way you can supply files using a wildcard and still have the\npages ordered correctly.\n\n '''\n\n if not options.sort_numerically:\n return options.filenames\n\n filenames = []\n\n for filename in options.filenames:\n basename = os.path.basename(filename)\n root, _ = os.path.splitext(basename)\n matches = re.findall(r'[0-9]+', root)\n if matches:\n num = int(matches[-1])\n else:\n num = -1\n filenames.append((num, filename))\n\n return [fn for (_, fn) in sorted(filenames)]\n" ]
#!/usr/bin/env python '''Converts sequence of images to compact PDF while removing speckles, bleedthrough, etc. ''' # for some reason pylint complains about members being undefined :( # pylint: disable=E1101 from __future__ import print_function import sys import os import re import subprocess import shlex from argparse import ArgumentParser import numpy as np from PIL import Image from scipy.cluster.vq import kmeans, vq ###################################################################### def quantize(image, bits_per_channel=None): '''Reduces the number of bits per channel in the given image.''' if bits_per_channel is None: bits_per_channel = 6 assert image.dtype == np.uint8 shift = 8-bits_per_channel halfbin = (1 << shift) >> 1 return ((image.astype(int) >> shift) << shift) + halfbin ###################################################################### def pack_rgb(rgb): '''Packs a 24-bit RGB triples into a single integer, works on both arrays and tuples.''' orig_shape = None if isinstance(rgb, np.ndarray): assert rgb.shape[-1] == 3 orig_shape = rgb.shape[:-1] else: assert len(rgb) == 3 rgb = np.array(rgb) rgb = rgb.astype(int).reshape((-1, 3)) packed = (rgb[:, 0] << 16 | rgb[:, 1] << 8 | rgb[:, 2]) if orig_shape is None: return packed else: return packed.reshape(orig_shape) ###################################################################### def unpack_rgb(packed): '''Unpacks a single integer or array of integers into one or more 24-bit RGB values. ''' orig_shape = None if isinstance(packed, np.ndarray): assert packed.dtype == int orig_shape = packed.shape packed = packed.reshape((-1, 1)) rgb = ((packed >> 16) & 0xff, (packed >> 8) & 0xff, (packed) & 0xff) if orig_shape is None: return rgb else: return np.hstack(rgb).reshape(orig_shape + (3,)) ###################################################################### def get_bg_color(image, bits_per_channel=None): '''Obtains the background color from an image or array of RGB colors by grouping similar colors into bins and finding the most frequent one. ''' assert image.shape[-1] == 3 quantized = quantize(image, bits_per_channel).astype(int) packed = pack_rgb(quantized) unique, counts = np.unique(packed, return_counts=True) packed_mode = unique[counts.argmax()] return unpack_rgb(packed_mode) ###################################################################### def rgb_to_sv(rgb): '''Convert an RGB image or array of RGB colors to saturation and value, returning each one as a separate 32-bit floating point array or value. ''' if not isinstance(rgb, np.ndarray): rgb = np.array(rgb) axis = len(rgb.shape)-1 cmax = rgb.max(axis=axis).astype(np.float32) cmin = rgb.min(axis=axis).astype(np.float32) delta = cmax - cmin saturation = delta.astype(np.float32) / cmax.astype(np.float32) saturation = np.where(cmax == 0, 0, saturation) value = cmax/255.0 return saturation, value ###################################################################### def postprocess(output_filename, options): '''Runs the postprocessing command on the file provided.''' assert options.postprocess_cmd base, _ = os.path.splitext(output_filename) post_filename = base + options.postprocess_ext cmd = options.postprocess_cmd cmd = cmd.replace('%i', output_filename) cmd = cmd.replace('%o', post_filename) cmd = cmd.replace('%e', options.postprocess_ext) subprocess_args = shlex.split(cmd) if os.path.exists(post_filename): os.unlink(post_filename) if not options.quiet: print(' running "{}"...'.format(cmd), end=' ') sys.stdout.flush() try: result = subprocess.call(subprocess_args) before = os.stat(output_filename).st_size after = os.stat(post_filename).st_size except OSError: result = -1 if result == 0: if not options.quiet: print('{:.1f}% reduction'.format( 100*(1.0-float(after)/before))) return post_filename else: sys.stderr.write('warning: postprocessing failed!\n') return None ###################################################################### def percent(string): '''Convert a string (i.e. 85) to a fraction (i.e. .85).''' return float(string)/100.0 ###################################################################### def get_argument_parser(): '''Parse the command-line arguments for this program.''' parser = ArgumentParser( description='convert scanned, hand-written notes to PDF') show_default = ' (default %(default)s)' parser.add_argument('filenames', metavar='IMAGE', nargs='+', help='files to convert') parser.add_argument('-q', dest='quiet', action='store_true', default=False, help='reduce program output') parser.add_argument('-b', dest='basename', metavar='BASENAME', default='page', help='output PNG filename base' + show_default) parser.add_argument('-o', dest='pdfname', metavar='PDF', default='output.pdf', help='output PDF filename' + show_default) parser.add_argument('-v', dest='value_threshold', metavar='PERCENT', type=percent, default='25', help='background value threshold %%'+show_default) parser.add_argument('-s', dest='sat_threshold', metavar='PERCENT', type=percent, default='20', help='background saturation ' 'threshold %%'+show_default) parser.add_argument('-n', dest='num_colors', type=int, default='8', help='number of output colors '+show_default) parser.add_argument('-p', dest='sample_fraction', metavar='PERCENT', type=percent, default='5', help='%% of pixels to sample' + show_default) parser.add_argument('-w', dest='white_bg', action='store_true', default=False, help='make background white') parser.add_argument('-g', dest='global_palette', action='store_true', default=False, help='use one global palette for all pages') parser.add_argument('-S', dest='saturate', action='store_false', default=True, help='do not saturate colors') parser.add_argument('-K', dest='sort_numerically', action='store_false', default=True, help='keep filenames ordered as specified; ' 'use if you *really* want IMG_10.png to ' 'precede IMG_2.png') parser.add_argument('-P', dest='postprocess_cmd', default=None, help='set postprocessing command (see -O, -C, -Q)') parser.add_argument('-e', dest='postprocess_ext', default='_post.png', help='filename suffix/extension for ' 'postprocessing command') parser.add_argument('-O', dest='postprocess_cmd', action='store_const', const='optipng -silent %i -out %o', help='same as -P "%(const)s"') parser.add_argument('-C', dest='postprocess_cmd', action='store_const', const='pngcrush -q %i %o', help='same as -P "%(const)s"') parser.add_argument('-Q', dest='postprocess_cmd', action='store_const', const='pngquant --ext %e %i', help='same as -P "%(const)s"') parser.add_argument('-c', dest='pdf_cmd', metavar="COMMAND", default='convert %i %o', help='PDF command (default "%(default)s")') return parser ###################################################################### def get_filenames(options): '''Get the filenames from the command line, optionally sorted by number, so that IMG_10.png is re-arranged to come after IMG_9.png. This is a nice feature because some scanner programs (like Image Capture on Mac OS X) automatically number files without leading zeros, and this way you can supply files using a wildcard and still have the pages ordered correctly. ''' if not options.sort_numerically: return options.filenames filenames = [] for filename in options.filenames: basename = os.path.basename(filename) root, _ = os.path.splitext(basename) matches = re.findall(r'[0-9]+', root) if matches: num = int(matches[-1]) else: num = -1 filenames.append((num, filename)) return [fn for (_, fn) in sorted(filenames)] ###################################################################### def load(input_filename): '''Load an image with Pillow and convert it to numpy array. Also returns the image DPI in x and y as a tuple.''' try: pil_img = Image.open(input_filename) except IOError: sys.stderr.write('warning: error opening {}\n'.format( input_filename)) return None, None if pil_img.mode != 'RGB': pil_img = pil_img.convert('RGB') if 'dpi' in pil_img.info: dpi = pil_img.info['dpi'] else: dpi = (300, 300) img = np.array(pil_img) return img, dpi ###################################################################### def sample_pixels(img, options): '''Pick a fixed percentage of pixels in the image, returned in random order.''' pixels = img.reshape((-1, 3)) num_pixels = pixels.shape[0] num_samples = int(num_pixels*options.sample_fraction) idx = np.arange(num_pixels) np.random.shuffle(idx) return pixels[idx[:num_samples]] ###################################################################### def get_fg_mask(bg_color, samples, options): '''Determine whether each pixel in a set of samples is foreground by comparing it to the background color. A pixel is classified as a foreground pixel if either its value or saturation differs from the background by a threshold.''' s_bg, v_bg = rgb_to_sv(bg_color) s_samples, v_samples = rgb_to_sv(samples) s_diff = np.abs(s_bg - s_samples) v_diff = np.abs(v_bg - v_samples) return ((v_diff >= options.value_threshold) | (s_diff >= options.sat_threshold)) ###################################################################### def get_palette(samples, options, return_mask=False, kmeans_iter=40): '''Extract the palette for the set of sampled RGB values. The first palette entry is always the background color; the rest are determined from foreground pixels by running K-means clustering. Returns the palette, as well as a mask corresponding to the foreground pixels. ''' if not options.quiet: print(' getting palette...') bg_color = get_bg_color(samples, 6) fg_mask = get_fg_mask(bg_color, samples, options) centers, _ = kmeans(samples[fg_mask].astype(np.float32), options.num_colors-1, iter=kmeans_iter) palette = np.vstack((bg_color, centers)).astype(np.uint8) if not return_mask: return palette else: return palette, fg_mask ###################################################################### def apply_palette(img, palette, options): '''Apply the pallete to the given image. The first step is to set all background pixels to the background color; then, nearest-neighbor matching is used to map each foreground color to the closest one in the palette. ''' if not options.quiet: print(' applying palette...') bg_color = palette[0] fg_mask = get_fg_mask(bg_color, img, options) orig_shape = img.shape pixels = img.reshape((-1, 3)) fg_mask = fg_mask.flatten() num_pixels = pixels.shape[0] labels = np.zeros(num_pixels, dtype=np.uint8) labels[fg_mask], _ = vq(pixels[fg_mask], palette) return labels.reshape(orig_shape[:-1]) ###################################################################### def save(output_filename, labels, palette, dpi, options): '''Save the label/palette pair out as an indexed PNG image. This optionally saturates the pallete by mapping the smallest color component to zero and the largest one to 255, and also optionally sets the background color to pure white. ''' if not options.quiet: print(' saving {}...'.format(output_filename)) if options.saturate: palette = palette.astype(np.float32) pmin = palette.min() pmax = palette.max() palette = 255 * (palette - pmin)/(pmax-pmin) palette = palette.astype(np.uint8) if options.white_bg: palette = palette.copy() palette[0] = (255, 255, 255) output_img = Image.fromarray(labels, 'P') output_img.putpalette(palette.flatten()) output_img.save(output_filename, dpi=dpi) ###################################################################### def get_global_palette(filenames, options): '''Fetch the global palette for a series of input files by merging their samples together into one large array. ''' input_filenames = [] all_samples = [] if not options.quiet: print('building global palette...') for input_filename in filenames: img, _ = load(input_filename) if img is None: continue if not options.quiet: print(' processing {}...'.format(input_filename)) samples = sample_pixels(img, options) input_filenames.append(input_filename) all_samples.append(samples) num_inputs = len(input_filenames) all_samples = [s[:int(round(float(s.shape[0])/num_inputs))] for s in all_samples] all_samples = np.vstack(tuple(all_samples)) global_palette = get_palette(all_samples, options) if not options.quiet: print(' done\n') return input_filenames, global_palette ###################################################################### def emit_pdf(outputs, options): '''Runs the PDF conversion command to generate the PDF.''' cmd = options.pdf_cmd cmd = cmd.replace('%o', options.pdfname) if len(outputs) > 2: cmd_print = cmd.replace('%i', ' '.join(outputs[:2] + ['...'])) else: cmd_print = cmd.replace('%i', ' '.join(outputs)) cmd = cmd.replace('%i', ' '.join(outputs)) if not options.quiet: print('running PDF command "{}"...'.format(cmd_print)) try: result = subprocess.call(shlex.split(cmd)) except OSError: result = -1 if result == 0: if not options.quiet: print(' wrote', options.pdfname) else: sys.stderr.write('warning: PDF command failed\n') ###################################################################### ###################################################################### def main(): '''Parse args and call notescan_main().''' notescan_main(options=get_argument_parser().parse_args()) if __name__ == '__main__': main()
SmileyChris/django-countries
django_countries/__init__.py
Countries.get_option
python
def get_option(self, option): value = getattr(self, option, None) if value is not None: return value return getattr(settings, "COUNTRIES_{0}".format(option.upper()))
Get a configuration option, trying the options attribute first and falling back to a Django project setting.
train
https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/__init__.py#L56-L64
null
class Countries(CountriesBase): """ An object containing a list of ISO3166-1 countries. Iterating this object will return the countries as namedtuples (of the country ``code`` and ``name``), sorted by name. """ @property def countries(self): """ Return the a dictionary of countries, modified by any overriding options. The result is cached so future lookups are less work intensive. """ if not hasattr(self, "_countries"): only = self.get_option("only") if only: only_choices = True if not isinstance(only, dict): for item in only: if isinstance(item, six.string_types): only_choices = False break if only and only_choices: self._countries = dict(only) else: # Local import so that countries aren't loaded into memory # until first used. from django_countries.data import COUNTRIES self._countries = dict(COUNTRIES) if self.get_option("common_names"): self._countries.update(self.COMMON_NAMES) override = self.get_option("override") if override: self._countries.update(override) self._countries = dict( (code, name) for code, name in self._countries.items() if name is not None ) if only and not only_choices: countries = {} for item in only: if isinstance(item, six.string_types): countries[item] = self._countries[item] else: key, value = item countries[key] = value self._countries = countries self.countries_first = [] first = self.get_option("first") or [] for code in first: code = self.alpha2(code) if code in self._countries: self.countries_first.append(code) return self._countries @property def alt_codes(self): if not hasattr(self, "_alt_codes"): # Again, local import so data is not loaded unless it's needed. from django_countries.data import ALT_CODES self._alt_codes = ALT_CODES return self._alt_codes @countries.deleter def countries(self): """ Reset the countries cache in case for some crazy reason the settings or internal options change. But surely no one is crazy enough to do that, right? """ if hasattr(self, "_countries"): del self._countries def translate_pair(self, code): """ Force a country to the current activated translation. :returns: ``CountryTuple(code, translated_country_name)`` namedtuple """ name = self.countries[code] if code in self.OLD_NAMES: # Check if there's an older translation available if there's no # translation for the newest name. with override(None): source_name = force_text(name) name = force_text(name) if name == source_name: for old_name in self.OLD_NAMES[code]: with override(None): source_old_name = force_text(old_name) old_name = force_text(old_name) if old_name != source_old_name: name = old_name break else: name = force_text(name) return CountryTuple(code, name) def __iter__(self): """ Iterate through countries, sorted by name. Each country record consists of a namedtuple of the two letter ISO3166-1 country ``code`` and short ``name``. The sorting happens based on the thread's current translation. Countries that are in ``settings.COUNTRIES_FIRST`` will be displayed before any sorted countries (in the order provided), and are only repeated in the sorted list if ``settings.COUNTRIES_FIRST_REPEAT`` is ``True``. The first countries can be separated from the sorted list by the value provided in ``settings.COUNTRIES_FIRST_BREAK``. """ # Initializes countries_first, so needs to happen first. countries = self.countries # Yield countries that should be displayed first. countries_first = (self.translate_pair(code) for code in self.countries_first) if self.get_option("first_sort"): countries_first = sorted(countries_first, key=sort_key) for item in countries_first: yield item if self.countries_first: first_break = self.get_option("first_break") if first_break: yield ("", force_text(first_break)) # Force translation before sorting. first_repeat = self.get_option("first_repeat") countries = ( self.translate_pair(code) for code in countries if first_repeat or code not in self.countries_first ) # Return sorted country list. for item in sorted(countries, key=sort_key): yield item def alpha2(self, code): """ Return the two letter country code when passed any type of ISO 3166-1 country code. If no match is found, returns an empty string. """ code = force_text(code).upper() if code.isdigit(): lookup_code = int(code) def find(alt_codes): return alt_codes[1] == lookup_code elif len(code) == 3: lookup_code = code def find(alt_codes): return alt_codes[0] == lookup_code else: find = None if find: code = None for alpha2, alt_codes in self.alt_codes.items(): if find(alt_codes): code = alpha2 break if code in self.countries: return code return "" def name(self, code): """ Return the name of a country, based on the code. If no match is found, returns an empty string. """ code = self.alpha2(code) if code not in self.countries: return "" return self.translate_pair(code)[1] def by_name(self, country, language="en"): """ Fetch a country's ISO3166-1 two letter country code from its name. An optional language parameter is also available. Warning: This depends on the quality of the available translations. If no match is found, returns an empty string. ..warning:: Be cautious about relying on this returning a country code (especially with any hard-coded string) since the ISO names of countries may change over time. """ with override(language): for code, name in self: if name.lower() == country.lower(): return code if code in self.OLD_NAMES: for old_name in self.OLD_NAMES[code]: if old_name.lower() == country.lower(): return code return "" def alpha3(self, code): """ Return the ISO 3166-1 three letter country code matching the provided country code. If no match is found, returns an empty string. """ code = self.alpha2(code) try: return self.alt_codes[code][0] except KeyError: return "" def numeric(self, code, padded=False): """ Return the ISO 3166-1 numeric country code matching the provided country code. If no match is found, returns ``None``. :param padded: Pass ``True`` to return a 0-padded three character string, otherwise an integer will be returned. """ code = self.alpha2(code) try: num = self.alt_codes[code][1] except KeyError: return None if padded: return "%03d" % num return num def __len__(self): """ len() used by several third party applications to calculate the length of choices. This will solve a bug related to generating fixtures. """ count = len(self.countries) # Add first countries, and the break if necessary. count += len(self.countries_first) if self.countries_first and self.get_option("first_break"): count += 1 return count def __bool__(self): return bool(self.countries) __nonzero__ = __bool__ def __contains__(self, code): """ Check to see if the countries contains the given code. """ return code in self.countries def __getitem__(self, index): """ Some applications expect to be able to access members of the field choices by index. """ try: return next(islice(self.__iter__(), index, index + 1)) except TypeError: return list(islice(self.__iter__(), index.start, index.stop, index.step))
SmileyChris/django-countries
django_countries/__init__.py
Countries.countries
python
def countries(self): if not hasattr(self, "_countries"): only = self.get_option("only") if only: only_choices = True if not isinstance(only, dict): for item in only: if isinstance(item, six.string_types): only_choices = False break if only and only_choices: self._countries = dict(only) else: # Local import so that countries aren't loaded into memory # until first used. from django_countries.data import COUNTRIES self._countries = dict(COUNTRIES) if self.get_option("common_names"): self._countries.update(self.COMMON_NAMES) override = self.get_option("override") if override: self._countries.update(override) self._countries = dict( (code, name) for code, name in self._countries.items() if name is not None ) if only and not only_choices: countries = {} for item in only: if isinstance(item, six.string_types): countries[item] = self._countries[item] else: key, value = item countries[key] = value self._countries = countries self.countries_first = [] first = self.get_option("first") or [] for code in first: code = self.alpha2(code) if code in self._countries: self.countries_first.append(code) return self._countries
Return the a dictionary of countries, modified by any overriding options. The result is cached so future lookups are less work intensive.
train
https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/__init__.py#L67-L116
[ "def get_option(self, option):\n \"\"\"\n Get a configuration option, trying the options attribute first and\n falling back to a Django project setting.\n \"\"\"\n value = getattr(self, option, None)\n if value is not None:\n return value\n return getattr(settings, \"COUNTRIES_{0}\".format(option.upper()))\n", "def alpha2(self, code):\n \"\"\"\n Return the two letter country code when passed any type of ISO 3166-1\n country code.\n\n If no match is found, returns an empty string.\n \"\"\"\n code = force_text(code).upper()\n if code.isdigit():\n lookup_code = int(code)\n\n def find(alt_codes):\n return alt_codes[1] == lookup_code\n\n elif len(code) == 3:\n lookup_code = code\n\n def find(alt_codes):\n return alt_codes[0] == lookup_code\n\n else:\n find = None\n if find:\n code = None\n for alpha2, alt_codes in self.alt_codes.items():\n if find(alt_codes):\n code = alpha2\n break\n if code in self.countries:\n return code\n return \"\"\n" ]
class Countries(CountriesBase): """ An object containing a list of ISO3166-1 countries. Iterating this object will return the countries as namedtuples (of the country ``code`` and ``name``), sorted by name. """ def get_option(self, option): """ Get a configuration option, trying the options attribute first and falling back to a Django project setting. """ value = getattr(self, option, None) if value is not None: return value return getattr(settings, "COUNTRIES_{0}".format(option.upper())) @property @property def alt_codes(self): if not hasattr(self, "_alt_codes"): # Again, local import so data is not loaded unless it's needed. from django_countries.data import ALT_CODES self._alt_codes = ALT_CODES return self._alt_codes @countries.deleter def countries(self): """ Reset the countries cache in case for some crazy reason the settings or internal options change. But surely no one is crazy enough to do that, right? """ if hasattr(self, "_countries"): del self._countries def translate_pair(self, code): """ Force a country to the current activated translation. :returns: ``CountryTuple(code, translated_country_name)`` namedtuple """ name = self.countries[code] if code in self.OLD_NAMES: # Check if there's an older translation available if there's no # translation for the newest name. with override(None): source_name = force_text(name) name = force_text(name) if name == source_name: for old_name in self.OLD_NAMES[code]: with override(None): source_old_name = force_text(old_name) old_name = force_text(old_name) if old_name != source_old_name: name = old_name break else: name = force_text(name) return CountryTuple(code, name) def __iter__(self): """ Iterate through countries, sorted by name. Each country record consists of a namedtuple of the two letter ISO3166-1 country ``code`` and short ``name``. The sorting happens based on the thread's current translation. Countries that are in ``settings.COUNTRIES_FIRST`` will be displayed before any sorted countries (in the order provided), and are only repeated in the sorted list if ``settings.COUNTRIES_FIRST_REPEAT`` is ``True``. The first countries can be separated from the sorted list by the value provided in ``settings.COUNTRIES_FIRST_BREAK``. """ # Initializes countries_first, so needs to happen first. countries = self.countries # Yield countries that should be displayed first. countries_first = (self.translate_pair(code) for code in self.countries_first) if self.get_option("first_sort"): countries_first = sorted(countries_first, key=sort_key) for item in countries_first: yield item if self.countries_first: first_break = self.get_option("first_break") if first_break: yield ("", force_text(first_break)) # Force translation before sorting. first_repeat = self.get_option("first_repeat") countries = ( self.translate_pair(code) for code in countries if first_repeat or code not in self.countries_first ) # Return sorted country list. for item in sorted(countries, key=sort_key): yield item def alpha2(self, code): """ Return the two letter country code when passed any type of ISO 3166-1 country code. If no match is found, returns an empty string. """ code = force_text(code).upper() if code.isdigit(): lookup_code = int(code) def find(alt_codes): return alt_codes[1] == lookup_code elif len(code) == 3: lookup_code = code def find(alt_codes): return alt_codes[0] == lookup_code else: find = None if find: code = None for alpha2, alt_codes in self.alt_codes.items(): if find(alt_codes): code = alpha2 break if code in self.countries: return code return "" def name(self, code): """ Return the name of a country, based on the code. If no match is found, returns an empty string. """ code = self.alpha2(code) if code not in self.countries: return "" return self.translate_pair(code)[1] def by_name(self, country, language="en"): """ Fetch a country's ISO3166-1 two letter country code from its name. An optional language parameter is also available. Warning: This depends on the quality of the available translations. If no match is found, returns an empty string. ..warning:: Be cautious about relying on this returning a country code (especially with any hard-coded string) since the ISO names of countries may change over time. """ with override(language): for code, name in self: if name.lower() == country.lower(): return code if code in self.OLD_NAMES: for old_name in self.OLD_NAMES[code]: if old_name.lower() == country.lower(): return code return "" def alpha3(self, code): """ Return the ISO 3166-1 three letter country code matching the provided country code. If no match is found, returns an empty string. """ code = self.alpha2(code) try: return self.alt_codes[code][0] except KeyError: return "" def numeric(self, code, padded=False): """ Return the ISO 3166-1 numeric country code matching the provided country code. If no match is found, returns ``None``. :param padded: Pass ``True`` to return a 0-padded three character string, otherwise an integer will be returned. """ code = self.alpha2(code) try: num = self.alt_codes[code][1] except KeyError: return None if padded: return "%03d" % num return num def __len__(self): """ len() used by several third party applications to calculate the length of choices. This will solve a bug related to generating fixtures. """ count = len(self.countries) # Add first countries, and the break if necessary. count += len(self.countries_first) if self.countries_first and self.get_option("first_break"): count += 1 return count def __bool__(self): return bool(self.countries) __nonzero__ = __bool__ def __contains__(self, code): """ Check to see if the countries contains the given code. """ return code in self.countries def __getitem__(self, index): """ Some applications expect to be able to access members of the field choices by index. """ try: return next(islice(self.__iter__(), index, index + 1)) except TypeError: return list(islice(self.__iter__(), index.start, index.stop, index.step))
SmileyChris/django-countries
django_countries/__init__.py
Countries.translate_pair
python
def translate_pair(self, code): name = self.countries[code] if code in self.OLD_NAMES: # Check if there's an older translation available if there's no # translation for the newest name. with override(None): source_name = force_text(name) name = force_text(name) if name == source_name: for old_name in self.OLD_NAMES[code]: with override(None): source_old_name = force_text(old_name) old_name = force_text(old_name) if old_name != source_old_name: name = old_name break else: name = force_text(name) return CountryTuple(code, name)
Force a country to the current activated translation. :returns: ``CountryTuple(code, translated_country_name)`` namedtuple
train
https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/__init__.py#L137-L160
null
class Countries(CountriesBase): """ An object containing a list of ISO3166-1 countries. Iterating this object will return the countries as namedtuples (of the country ``code`` and ``name``), sorted by name. """ def get_option(self, option): """ Get a configuration option, trying the options attribute first and falling back to a Django project setting. """ value = getattr(self, option, None) if value is not None: return value return getattr(settings, "COUNTRIES_{0}".format(option.upper())) @property def countries(self): """ Return the a dictionary of countries, modified by any overriding options. The result is cached so future lookups are less work intensive. """ if not hasattr(self, "_countries"): only = self.get_option("only") if only: only_choices = True if not isinstance(only, dict): for item in only: if isinstance(item, six.string_types): only_choices = False break if only and only_choices: self._countries = dict(only) else: # Local import so that countries aren't loaded into memory # until first used. from django_countries.data import COUNTRIES self._countries = dict(COUNTRIES) if self.get_option("common_names"): self._countries.update(self.COMMON_NAMES) override = self.get_option("override") if override: self._countries.update(override) self._countries = dict( (code, name) for code, name in self._countries.items() if name is not None ) if only and not only_choices: countries = {} for item in only: if isinstance(item, six.string_types): countries[item] = self._countries[item] else: key, value = item countries[key] = value self._countries = countries self.countries_first = [] first = self.get_option("first") or [] for code in first: code = self.alpha2(code) if code in self._countries: self.countries_first.append(code) return self._countries @property def alt_codes(self): if not hasattr(self, "_alt_codes"): # Again, local import so data is not loaded unless it's needed. from django_countries.data import ALT_CODES self._alt_codes = ALT_CODES return self._alt_codes @countries.deleter def countries(self): """ Reset the countries cache in case for some crazy reason the settings or internal options change. But surely no one is crazy enough to do that, right? """ if hasattr(self, "_countries"): del self._countries def __iter__(self): """ Iterate through countries, sorted by name. Each country record consists of a namedtuple of the two letter ISO3166-1 country ``code`` and short ``name``. The sorting happens based on the thread's current translation. Countries that are in ``settings.COUNTRIES_FIRST`` will be displayed before any sorted countries (in the order provided), and are only repeated in the sorted list if ``settings.COUNTRIES_FIRST_REPEAT`` is ``True``. The first countries can be separated from the sorted list by the value provided in ``settings.COUNTRIES_FIRST_BREAK``. """ # Initializes countries_first, so needs to happen first. countries = self.countries # Yield countries that should be displayed first. countries_first = (self.translate_pair(code) for code in self.countries_first) if self.get_option("first_sort"): countries_first = sorted(countries_first, key=sort_key) for item in countries_first: yield item if self.countries_first: first_break = self.get_option("first_break") if first_break: yield ("", force_text(first_break)) # Force translation before sorting. first_repeat = self.get_option("first_repeat") countries = ( self.translate_pair(code) for code in countries if first_repeat or code not in self.countries_first ) # Return sorted country list. for item in sorted(countries, key=sort_key): yield item def alpha2(self, code): """ Return the two letter country code when passed any type of ISO 3166-1 country code. If no match is found, returns an empty string. """ code = force_text(code).upper() if code.isdigit(): lookup_code = int(code) def find(alt_codes): return alt_codes[1] == lookup_code elif len(code) == 3: lookup_code = code def find(alt_codes): return alt_codes[0] == lookup_code else: find = None if find: code = None for alpha2, alt_codes in self.alt_codes.items(): if find(alt_codes): code = alpha2 break if code in self.countries: return code return "" def name(self, code): """ Return the name of a country, based on the code. If no match is found, returns an empty string. """ code = self.alpha2(code) if code not in self.countries: return "" return self.translate_pair(code)[1] def by_name(self, country, language="en"): """ Fetch a country's ISO3166-1 two letter country code from its name. An optional language parameter is also available. Warning: This depends on the quality of the available translations. If no match is found, returns an empty string. ..warning:: Be cautious about relying on this returning a country code (especially with any hard-coded string) since the ISO names of countries may change over time. """ with override(language): for code, name in self: if name.lower() == country.lower(): return code if code in self.OLD_NAMES: for old_name in self.OLD_NAMES[code]: if old_name.lower() == country.lower(): return code return "" def alpha3(self, code): """ Return the ISO 3166-1 three letter country code matching the provided country code. If no match is found, returns an empty string. """ code = self.alpha2(code) try: return self.alt_codes[code][0] except KeyError: return "" def numeric(self, code, padded=False): """ Return the ISO 3166-1 numeric country code matching the provided country code. If no match is found, returns ``None``. :param padded: Pass ``True`` to return a 0-padded three character string, otherwise an integer will be returned. """ code = self.alpha2(code) try: num = self.alt_codes[code][1] except KeyError: return None if padded: return "%03d" % num return num def __len__(self): """ len() used by several third party applications to calculate the length of choices. This will solve a bug related to generating fixtures. """ count = len(self.countries) # Add first countries, and the break if necessary. count += len(self.countries_first) if self.countries_first and self.get_option("first_break"): count += 1 return count def __bool__(self): return bool(self.countries) __nonzero__ = __bool__ def __contains__(self, code): """ Check to see if the countries contains the given code. """ return code in self.countries def __getitem__(self, index): """ Some applications expect to be able to access members of the field choices by index. """ try: return next(islice(self.__iter__(), index, index + 1)) except TypeError: return list(islice(self.__iter__(), index.start, index.stop, index.step))
SmileyChris/django-countries
django_countries/__init__.py
Countries.alpha2
python
def alpha2(self, code): code = force_text(code).upper() if code.isdigit(): lookup_code = int(code) def find(alt_codes): return alt_codes[1] == lookup_code elif len(code) == 3: lookup_code = code def find(alt_codes): return alt_codes[0] == lookup_code else: find = None if find: code = None for alpha2, alt_codes in self.alt_codes.items(): if find(alt_codes): code = alpha2 break if code in self.countries: return code return ""
Return the two letter country code when passed any type of ISO 3166-1 country code. If no match is found, returns an empty string.
train
https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/__init__.py#L208-L238
[ "def find(alt_codes):\n return alt_codes[1] == lookup_code\n", "def find(alt_codes):\n return alt_codes[0] == lookup_code\n" ]
class Countries(CountriesBase): """ An object containing a list of ISO3166-1 countries. Iterating this object will return the countries as namedtuples (of the country ``code`` and ``name``), sorted by name. """ def get_option(self, option): """ Get a configuration option, trying the options attribute first and falling back to a Django project setting. """ value = getattr(self, option, None) if value is not None: return value return getattr(settings, "COUNTRIES_{0}".format(option.upper())) @property def countries(self): """ Return the a dictionary of countries, modified by any overriding options. The result is cached so future lookups are less work intensive. """ if not hasattr(self, "_countries"): only = self.get_option("only") if only: only_choices = True if not isinstance(only, dict): for item in only: if isinstance(item, six.string_types): only_choices = False break if only and only_choices: self._countries = dict(only) else: # Local import so that countries aren't loaded into memory # until first used. from django_countries.data import COUNTRIES self._countries = dict(COUNTRIES) if self.get_option("common_names"): self._countries.update(self.COMMON_NAMES) override = self.get_option("override") if override: self._countries.update(override) self._countries = dict( (code, name) for code, name in self._countries.items() if name is not None ) if only and not only_choices: countries = {} for item in only: if isinstance(item, six.string_types): countries[item] = self._countries[item] else: key, value = item countries[key] = value self._countries = countries self.countries_first = [] first = self.get_option("first") or [] for code in first: code = self.alpha2(code) if code in self._countries: self.countries_first.append(code) return self._countries @property def alt_codes(self): if not hasattr(self, "_alt_codes"): # Again, local import so data is not loaded unless it's needed. from django_countries.data import ALT_CODES self._alt_codes = ALT_CODES return self._alt_codes @countries.deleter def countries(self): """ Reset the countries cache in case for some crazy reason the settings or internal options change. But surely no one is crazy enough to do that, right? """ if hasattr(self, "_countries"): del self._countries def translate_pair(self, code): """ Force a country to the current activated translation. :returns: ``CountryTuple(code, translated_country_name)`` namedtuple """ name = self.countries[code] if code in self.OLD_NAMES: # Check if there's an older translation available if there's no # translation for the newest name. with override(None): source_name = force_text(name) name = force_text(name) if name == source_name: for old_name in self.OLD_NAMES[code]: with override(None): source_old_name = force_text(old_name) old_name = force_text(old_name) if old_name != source_old_name: name = old_name break else: name = force_text(name) return CountryTuple(code, name) def __iter__(self): """ Iterate through countries, sorted by name. Each country record consists of a namedtuple of the two letter ISO3166-1 country ``code`` and short ``name``. The sorting happens based on the thread's current translation. Countries that are in ``settings.COUNTRIES_FIRST`` will be displayed before any sorted countries (in the order provided), and are only repeated in the sorted list if ``settings.COUNTRIES_FIRST_REPEAT`` is ``True``. The first countries can be separated from the sorted list by the value provided in ``settings.COUNTRIES_FIRST_BREAK``. """ # Initializes countries_first, so needs to happen first. countries = self.countries # Yield countries that should be displayed first. countries_first = (self.translate_pair(code) for code in self.countries_first) if self.get_option("first_sort"): countries_first = sorted(countries_first, key=sort_key) for item in countries_first: yield item if self.countries_first: first_break = self.get_option("first_break") if first_break: yield ("", force_text(first_break)) # Force translation before sorting. first_repeat = self.get_option("first_repeat") countries = ( self.translate_pair(code) for code in countries if first_repeat or code not in self.countries_first ) # Return sorted country list. for item in sorted(countries, key=sort_key): yield item def name(self, code): """ Return the name of a country, based on the code. If no match is found, returns an empty string. """ code = self.alpha2(code) if code not in self.countries: return "" return self.translate_pair(code)[1] def by_name(self, country, language="en"): """ Fetch a country's ISO3166-1 two letter country code from its name. An optional language parameter is also available. Warning: This depends on the quality of the available translations. If no match is found, returns an empty string. ..warning:: Be cautious about relying on this returning a country code (especially with any hard-coded string) since the ISO names of countries may change over time. """ with override(language): for code, name in self: if name.lower() == country.lower(): return code if code in self.OLD_NAMES: for old_name in self.OLD_NAMES[code]: if old_name.lower() == country.lower(): return code return "" def alpha3(self, code): """ Return the ISO 3166-1 three letter country code matching the provided country code. If no match is found, returns an empty string. """ code = self.alpha2(code) try: return self.alt_codes[code][0] except KeyError: return "" def numeric(self, code, padded=False): """ Return the ISO 3166-1 numeric country code matching the provided country code. If no match is found, returns ``None``. :param padded: Pass ``True`` to return a 0-padded three character string, otherwise an integer will be returned. """ code = self.alpha2(code) try: num = self.alt_codes[code][1] except KeyError: return None if padded: return "%03d" % num return num def __len__(self): """ len() used by several third party applications to calculate the length of choices. This will solve a bug related to generating fixtures. """ count = len(self.countries) # Add first countries, and the break if necessary. count += len(self.countries_first) if self.countries_first and self.get_option("first_break"): count += 1 return count def __bool__(self): return bool(self.countries) __nonzero__ = __bool__ def __contains__(self, code): """ Check to see if the countries contains the given code. """ return code in self.countries def __getitem__(self, index): """ Some applications expect to be able to access members of the field choices by index. """ try: return next(islice(self.__iter__(), index, index + 1)) except TypeError: return list(islice(self.__iter__(), index.start, index.stop, index.step))
SmileyChris/django-countries
django_countries/__init__.py
Countries.name
python
def name(self, code): code = self.alpha2(code) if code not in self.countries: return "" return self.translate_pair(code)[1]
Return the name of a country, based on the code. If no match is found, returns an empty string.
train
https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/__init__.py#L240-L249
[ "def translate_pair(self, code):\n \"\"\"\n Force a country to the current activated translation.\n\n :returns: ``CountryTuple(code, translated_country_name)`` namedtuple\n \"\"\"\n name = self.countries[code]\n if code in self.OLD_NAMES:\n # Check if there's an older translation available if there's no\n # translation for the newest name.\n with override(None):\n source_name = force_text(name)\n name = force_text(name)\n if name == source_name:\n for old_name in self.OLD_NAMES[code]:\n with override(None):\n source_old_name = force_text(old_name)\n old_name = force_text(old_name)\n if old_name != source_old_name:\n name = old_name\n break\n else:\n name = force_text(name)\n return CountryTuple(code, name)\n", "def alpha2(self, code):\n \"\"\"\n Return the two letter country code when passed any type of ISO 3166-1\n country code.\n\n If no match is found, returns an empty string.\n \"\"\"\n code = force_text(code).upper()\n if code.isdigit():\n lookup_code = int(code)\n\n def find(alt_codes):\n return alt_codes[1] == lookup_code\n\n elif len(code) == 3:\n lookup_code = code\n\n def find(alt_codes):\n return alt_codes[0] == lookup_code\n\n else:\n find = None\n if find:\n code = None\n for alpha2, alt_codes in self.alt_codes.items():\n if find(alt_codes):\n code = alpha2\n break\n if code in self.countries:\n return code\n return \"\"\n" ]
class Countries(CountriesBase): """ An object containing a list of ISO3166-1 countries. Iterating this object will return the countries as namedtuples (of the country ``code`` and ``name``), sorted by name. """ def get_option(self, option): """ Get a configuration option, trying the options attribute first and falling back to a Django project setting. """ value = getattr(self, option, None) if value is not None: return value return getattr(settings, "COUNTRIES_{0}".format(option.upper())) @property def countries(self): """ Return the a dictionary of countries, modified by any overriding options. The result is cached so future lookups are less work intensive. """ if not hasattr(self, "_countries"): only = self.get_option("only") if only: only_choices = True if not isinstance(only, dict): for item in only: if isinstance(item, six.string_types): only_choices = False break if only and only_choices: self._countries = dict(only) else: # Local import so that countries aren't loaded into memory # until first used. from django_countries.data import COUNTRIES self._countries = dict(COUNTRIES) if self.get_option("common_names"): self._countries.update(self.COMMON_NAMES) override = self.get_option("override") if override: self._countries.update(override) self._countries = dict( (code, name) for code, name in self._countries.items() if name is not None ) if only and not only_choices: countries = {} for item in only: if isinstance(item, six.string_types): countries[item] = self._countries[item] else: key, value = item countries[key] = value self._countries = countries self.countries_first = [] first = self.get_option("first") or [] for code in first: code = self.alpha2(code) if code in self._countries: self.countries_first.append(code) return self._countries @property def alt_codes(self): if not hasattr(self, "_alt_codes"): # Again, local import so data is not loaded unless it's needed. from django_countries.data import ALT_CODES self._alt_codes = ALT_CODES return self._alt_codes @countries.deleter def countries(self): """ Reset the countries cache in case for some crazy reason the settings or internal options change. But surely no one is crazy enough to do that, right? """ if hasattr(self, "_countries"): del self._countries def translate_pair(self, code): """ Force a country to the current activated translation. :returns: ``CountryTuple(code, translated_country_name)`` namedtuple """ name = self.countries[code] if code in self.OLD_NAMES: # Check if there's an older translation available if there's no # translation for the newest name. with override(None): source_name = force_text(name) name = force_text(name) if name == source_name: for old_name in self.OLD_NAMES[code]: with override(None): source_old_name = force_text(old_name) old_name = force_text(old_name) if old_name != source_old_name: name = old_name break else: name = force_text(name) return CountryTuple(code, name) def __iter__(self): """ Iterate through countries, sorted by name. Each country record consists of a namedtuple of the two letter ISO3166-1 country ``code`` and short ``name``. The sorting happens based on the thread's current translation. Countries that are in ``settings.COUNTRIES_FIRST`` will be displayed before any sorted countries (in the order provided), and are only repeated in the sorted list if ``settings.COUNTRIES_FIRST_REPEAT`` is ``True``. The first countries can be separated from the sorted list by the value provided in ``settings.COUNTRIES_FIRST_BREAK``. """ # Initializes countries_first, so needs to happen first. countries = self.countries # Yield countries that should be displayed first. countries_first = (self.translate_pair(code) for code in self.countries_first) if self.get_option("first_sort"): countries_first = sorted(countries_first, key=sort_key) for item in countries_first: yield item if self.countries_first: first_break = self.get_option("first_break") if first_break: yield ("", force_text(first_break)) # Force translation before sorting. first_repeat = self.get_option("first_repeat") countries = ( self.translate_pair(code) for code in countries if first_repeat or code not in self.countries_first ) # Return sorted country list. for item in sorted(countries, key=sort_key): yield item def alpha2(self, code): """ Return the two letter country code when passed any type of ISO 3166-1 country code. If no match is found, returns an empty string. """ code = force_text(code).upper() if code.isdigit(): lookup_code = int(code) def find(alt_codes): return alt_codes[1] == lookup_code elif len(code) == 3: lookup_code = code def find(alt_codes): return alt_codes[0] == lookup_code else: find = None if find: code = None for alpha2, alt_codes in self.alt_codes.items(): if find(alt_codes): code = alpha2 break if code in self.countries: return code return "" def by_name(self, country, language="en"): """ Fetch a country's ISO3166-1 two letter country code from its name. An optional language parameter is also available. Warning: This depends on the quality of the available translations. If no match is found, returns an empty string. ..warning:: Be cautious about relying on this returning a country code (especially with any hard-coded string) since the ISO names of countries may change over time. """ with override(language): for code, name in self: if name.lower() == country.lower(): return code if code in self.OLD_NAMES: for old_name in self.OLD_NAMES[code]: if old_name.lower() == country.lower(): return code return "" def alpha3(self, code): """ Return the ISO 3166-1 three letter country code matching the provided country code. If no match is found, returns an empty string. """ code = self.alpha2(code) try: return self.alt_codes[code][0] except KeyError: return "" def numeric(self, code, padded=False): """ Return the ISO 3166-1 numeric country code matching the provided country code. If no match is found, returns ``None``. :param padded: Pass ``True`` to return a 0-padded three character string, otherwise an integer will be returned. """ code = self.alpha2(code) try: num = self.alt_codes[code][1] except KeyError: return None if padded: return "%03d" % num return num def __len__(self): """ len() used by several third party applications to calculate the length of choices. This will solve a bug related to generating fixtures. """ count = len(self.countries) # Add first countries, and the break if necessary. count += len(self.countries_first) if self.countries_first and self.get_option("first_break"): count += 1 return count def __bool__(self): return bool(self.countries) __nonzero__ = __bool__ def __contains__(self, code): """ Check to see if the countries contains the given code. """ return code in self.countries def __getitem__(self, index): """ Some applications expect to be able to access members of the field choices by index. """ try: return next(islice(self.__iter__(), index, index + 1)) except TypeError: return list(islice(self.__iter__(), index.start, index.stop, index.step))
SmileyChris/django-countries
django_countries/__init__.py
Countries.by_name
python
def by_name(self, country, language="en"): with override(language): for code, name in self: if name.lower() == country.lower(): return code if code in self.OLD_NAMES: for old_name in self.OLD_NAMES[code]: if old_name.lower() == country.lower(): return code return ""
Fetch a country's ISO3166-1 two letter country code from its name. An optional language parameter is also available. Warning: This depends on the quality of the available translations. If no match is found, returns an empty string. ..warning:: Be cautious about relying on this returning a country code (especially with any hard-coded string) since the ISO names of countries may change over time.
train
https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/__init__.py#L251-L272
null
class Countries(CountriesBase): """ An object containing a list of ISO3166-1 countries. Iterating this object will return the countries as namedtuples (of the country ``code`` and ``name``), sorted by name. """ def get_option(self, option): """ Get a configuration option, trying the options attribute first and falling back to a Django project setting. """ value = getattr(self, option, None) if value is not None: return value return getattr(settings, "COUNTRIES_{0}".format(option.upper())) @property def countries(self): """ Return the a dictionary of countries, modified by any overriding options. The result is cached so future lookups are less work intensive. """ if not hasattr(self, "_countries"): only = self.get_option("only") if only: only_choices = True if not isinstance(only, dict): for item in only: if isinstance(item, six.string_types): only_choices = False break if only and only_choices: self._countries = dict(only) else: # Local import so that countries aren't loaded into memory # until first used. from django_countries.data import COUNTRIES self._countries = dict(COUNTRIES) if self.get_option("common_names"): self._countries.update(self.COMMON_NAMES) override = self.get_option("override") if override: self._countries.update(override) self._countries = dict( (code, name) for code, name in self._countries.items() if name is not None ) if only and not only_choices: countries = {} for item in only: if isinstance(item, six.string_types): countries[item] = self._countries[item] else: key, value = item countries[key] = value self._countries = countries self.countries_first = [] first = self.get_option("first") or [] for code in first: code = self.alpha2(code) if code in self._countries: self.countries_first.append(code) return self._countries @property def alt_codes(self): if not hasattr(self, "_alt_codes"): # Again, local import so data is not loaded unless it's needed. from django_countries.data import ALT_CODES self._alt_codes = ALT_CODES return self._alt_codes @countries.deleter def countries(self): """ Reset the countries cache in case for some crazy reason the settings or internal options change. But surely no one is crazy enough to do that, right? """ if hasattr(self, "_countries"): del self._countries def translate_pair(self, code): """ Force a country to the current activated translation. :returns: ``CountryTuple(code, translated_country_name)`` namedtuple """ name = self.countries[code] if code in self.OLD_NAMES: # Check if there's an older translation available if there's no # translation for the newest name. with override(None): source_name = force_text(name) name = force_text(name) if name == source_name: for old_name in self.OLD_NAMES[code]: with override(None): source_old_name = force_text(old_name) old_name = force_text(old_name) if old_name != source_old_name: name = old_name break else: name = force_text(name) return CountryTuple(code, name) def __iter__(self): """ Iterate through countries, sorted by name. Each country record consists of a namedtuple of the two letter ISO3166-1 country ``code`` and short ``name``. The sorting happens based on the thread's current translation. Countries that are in ``settings.COUNTRIES_FIRST`` will be displayed before any sorted countries (in the order provided), and are only repeated in the sorted list if ``settings.COUNTRIES_FIRST_REPEAT`` is ``True``. The first countries can be separated from the sorted list by the value provided in ``settings.COUNTRIES_FIRST_BREAK``. """ # Initializes countries_first, so needs to happen first. countries = self.countries # Yield countries that should be displayed first. countries_first = (self.translate_pair(code) for code in self.countries_first) if self.get_option("first_sort"): countries_first = sorted(countries_first, key=sort_key) for item in countries_first: yield item if self.countries_first: first_break = self.get_option("first_break") if first_break: yield ("", force_text(first_break)) # Force translation before sorting. first_repeat = self.get_option("first_repeat") countries = ( self.translate_pair(code) for code in countries if first_repeat or code not in self.countries_first ) # Return sorted country list. for item in sorted(countries, key=sort_key): yield item def alpha2(self, code): """ Return the two letter country code when passed any type of ISO 3166-1 country code. If no match is found, returns an empty string. """ code = force_text(code).upper() if code.isdigit(): lookup_code = int(code) def find(alt_codes): return alt_codes[1] == lookup_code elif len(code) == 3: lookup_code = code def find(alt_codes): return alt_codes[0] == lookup_code else: find = None if find: code = None for alpha2, alt_codes in self.alt_codes.items(): if find(alt_codes): code = alpha2 break if code in self.countries: return code return "" def name(self, code): """ Return the name of a country, based on the code. If no match is found, returns an empty string. """ code = self.alpha2(code) if code not in self.countries: return "" return self.translate_pair(code)[1] def alpha3(self, code): """ Return the ISO 3166-1 three letter country code matching the provided country code. If no match is found, returns an empty string. """ code = self.alpha2(code) try: return self.alt_codes[code][0] except KeyError: return "" def numeric(self, code, padded=False): """ Return the ISO 3166-1 numeric country code matching the provided country code. If no match is found, returns ``None``. :param padded: Pass ``True`` to return a 0-padded three character string, otherwise an integer will be returned. """ code = self.alpha2(code) try: num = self.alt_codes[code][1] except KeyError: return None if padded: return "%03d" % num return num def __len__(self): """ len() used by several third party applications to calculate the length of choices. This will solve a bug related to generating fixtures. """ count = len(self.countries) # Add first countries, and the break if necessary. count += len(self.countries_first) if self.countries_first and self.get_option("first_break"): count += 1 return count def __bool__(self): return bool(self.countries) __nonzero__ = __bool__ def __contains__(self, code): """ Check to see if the countries contains the given code. """ return code in self.countries def __getitem__(self, index): """ Some applications expect to be able to access members of the field choices by index. """ try: return next(islice(self.__iter__(), index, index + 1)) except TypeError: return list(islice(self.__iter__(), index.start, index.stop, index.step))
SmileyChris/django-countries
django_countries/__init__.py
Countries.alpha3
python
def alpha3(self, code): code = self.alpha2(code) try: return self.alt_codes[code][0] except KeyError: return ""
Return the ISO 3166-1 three letter country code matching the provided country code. If no match is found, returns an empty string.
train
https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/__init__.py#L274-L285
[ "def alpha2(self, code):\n \"\"\"\n Return the two letter country code when passed any type of ISO 3166-1\n country code.\n\n If no match is found, returns an empty string.\n \"\"\"\n code = force_text(code).upper()\n if code.isdigit():\n lookup_code = int(code)\n\n def find(alt_codes):\n return alt_codes[1] == lookup_code\n\n elif len(code) == 3:\n lookup_code = code\n\n def find(alt_codes):\n return alt_codes[0] == lookup_code\n\n else:\n find = None\n if find:\n code = None\n for alpha2, alt_codes in self.alt_codes.items():\n if find(alt_codes):\n code = alpha2\n break\n if code in self.countries:\n return code\n return \"\"\n" ]
class Countries(CountriesBase): """ An object containing a list of ISO3166-1 countries. Iterating this object will return the countries as namedtuples (of the country ``code`` and ``name``), sorted by name. """ def get_option(self, option): """ Get a configuration option, trying the options attribute first and falling back to a Django project setting. """ value = getattr(self, option, None) if value is not None: return value return getattr(settings, "COUNTRIES_{0}".format(option.upper())) @property def countries(self): """ Return the a dictionary of countries, modified by any overriding options. The result is cached so future lookups are less work intensive. """ if not hasattr(self, "_countries"): only = self.get_option("only") if only: only_choices = True if not isinstance(only, dict): for item in only: if isinstance(item, six.string_types): only_choices = False break if only and only_choices: self._countries = dict(only) else: # Local import so that countries aren't loaded into memory # until first used. from django_countries.data import COUNTRIES self._countries = dict(COUNTRIES) if self.get_option("common_names"): self._countries.update(self.COMMON_NAMES) override = self.get_option("override") if override: self._countries.update(override) self._countries = dict( (code, name) for code, name in self._countries.items() if name is not None ) if only and not only_choices: countries = {} for item in only: if isinstance(item, six.string_types): countries[item] = self._countries[item] else: key, value = item countries[key] = value self._countries = countries self.countries_first = [] first = self.get_option("first") or [] for code in first: code = self.alpha2(code) if code in self._countries: self.countries_first.append(code) return self._countries @property def alt_codes(self): if not hasattr(self, "_alt_codes"): # Again, local import so data is not loaded unless it's needed. from django_countries.data import ALT_CODES self._alt_codes = ALT_CODES return self._alt_codes @countries.deleter def countries(self): """ Reset the countries cache in case for some crazy reason the settings or internal options change. But surely no one is crazy enough to do that, right? """ if hasattr(self, "_countries"): del self._countries def translate_pair(self, code): """ Force a country to the current activated translation. :returns: ``CountryTuple(code, translated_country_name)`` namedtuple """ name = self.countries[code] if code in self.OLD_NAMES: # Check if there's an older translation available if there's no # translation for the newest name. with override(None): source_name = force_text(name) name = force_text(name) if name == source_name: for old_name in self.OLD_NAMES[code]: with override(None): source_old_name = force_text(old_name) old_name = force_text(old_name) if old_name != source_old_name: name = old_name break else: name = force_text(name) return CountryTuple(code, name) def __iter__(self): """ Iterate through countries, sorted by name. Each country record consists of a namedtuple of the two letter ISO3166-1 country ``code`` and short ``name``. The sorting happens based on the thread's current translation. Countries that are in ``settings.COUNTRIES_FIRST`` will be displayed before any sorted countries (in the order provided), and are only repeated in the sorted list if ``settings.COUNTRIES_FIRST_REPEAT`` is ``True``. The first countries can be separated from the sorted list by the value provided in ``settings.COUNTRIES_FIRST_BREAK``. """ # Initializes countries_first, so needs to happen first. countries = self.countries # Yield countries that should be displayed first. countries_first = (self.translate_pair(code) for code in self.countries_first) if self.get_option("first_sort"): countries_first = sorted(countries_first, key=sort_key) for item in countries_first: yield item if self.countries_first: first_break = self.get_option("first_break") if first_break: yield ("", force_text(first_break)) # Force translation before sorting. first_repeat = self.get_option("first_repeat") countries = ( self.translate_pair(code) for code in countries if first_repeat or code not in self.countries_first ) # Return sorted country list. for item in sorted(countries, key=sort_key): yield item def alpha2(self, code): """ Return the two letter country code when passed any type of ISO 3166-1 country code. If no match is found, returns an empty string. """ code = force_text(code).upper() if code.isdigit(): lookup_code = int(code) def find(alt_codes): return alt_codes[1] == lookup_code elif len(code) == 3: lookup_code = code def find(alt_codes): return alt_codes[0] == lookup_code else: find = None if find: code = None for alpha2, alt_codes in self.alt_codes.items(): if find(alt_codes): code = alpha2 break if code in self.countries: return code return "" def name(self, code): """ Return the name of a country, based on the code. If no match is found, returns an empty string. """ code = self.alpha2(code) if code not in self.countries: return "" return self.translate_pair(code)[1] def by_name(self, country, language="en"): """ Fetch a country's ISO3166-1 two letter country code from its name. An optional language parameter is also available. Warning: This depends on the quality of the available translations. If no match is found, returns an empty string. ..warning:: Be cautious about relying on this returning a country code (especially with any hard-coded string) since the ISO names of countries may change over time. """ with override(language): for code, name in self: if name.lower() == country.lower(): return code if code in self.OLD_NAMES: for old_name in self.OLD_NAMES[code]: if old_name.lower() == country.lower(): return code return "" def numeric(self, code, padded=False): """ Return the ISO 3166-1 numeric country code matching the provided country code. If no match is found, returns ``None``. :param padded: Pass ``True`` to return a 0-padded three character string, otherwise an integer will be returned. """ code = self.alpha2(code) try: num = self.alt_codes[code][1] except KeyError: return None if padded: return "%03d" % num return num def __len__(self): """ len() used by several third party applications to calculate the length of choices. This will solve a bug related to generating fixtures. """ count = len(self.countries) # Add first countries, and the break if necessary. count += len(self.countries_first) if self.countries_first and self.get_option("first_break"): count += 1 return count def __bool__(self): return bool(self.countries) __nonzero__ = __bool__ def __contains__(self, code): """ Check to see if the countries contains the given code. """ return code in self.countries def __getitem__(self, index): """ Some applications expect to be able to access members of the field choices by index. """ try: return next(islice(self.__iter__(), index, index + 1)) except TypeError: return list(islice(self.__iter__(), index.start, index.stop, index.step))
SmileyChris/django-countries
django_countries/__init__.py
Countries.numeric
python
def numeric(self, code, padded=False): code = self.alpha2(code) try: num = self.alt_codes[code][1] except KeyError: return None if padded: return "%03d" % num return num
Return the ISO 3166-1 numeric country code matching the provided country code. If no match is found, returns ``None``. :param padded: Pass ``True`` to return a 0-padded three character string, otherwise an integer will be returned.
train
https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/__init__.py#L287-L304
[ "def alpha2(self, code):\n \"\"\"\n Return the two letter country code when passed any type of ISO 3166-1\n country code.\n\n If no match is found, returns an empty string.\n \"\"\"\n code = force_text(code).upper()\n if code.isdigit():\n lookup_code = int(code)\n\n def find(alt_codes):\n return alt_codes[1] == lookup_code\n\n elif len(code) == 3:\n lookup_code = code\n\n def find(alt_codes):\n return alt_codes[0] == lookup_code\n\n else:\n find = None\n if find:\n code = None\n for alpha2, alt_codes in self.alt_codes.items():\n if find(alt_codes):\n code = alpha2\n break\n if code in self.countries:\n return code\n return \"\"\n" ]
class Countries(CountriesBase): """ An object containing a list of ISO3166-1 countries. Iterating this object will return the countries as namedtuples (of the country ``code`` and ``name``), sorted by name. """ def get_option(self, option): """ Get a configuration option, trying the options attribute first and falling back to a Django project setting. """ value = getattr(self, option, None) if value is not None: return value return getattr(settings, "COUNTRIES_{0}".format(option.upper())) @property def countries(self): """ Return the a dictionary of countries, modified by any overriding options. The result is cached so future lookups are less work intensive. """ if not hasattr(self, "_countries"): only = self.get_option("only") if only: only_choices = True if not isinstance(only, dict): for item in only: if isinstance(item, six.string_types): only_choices = False break if only and only_choices: self._countries = dict(only) else: # Local import so that countries aren't loaded into memory # until first used. from django_countries.data import COUNTRIES self._countries = dict(COUNTRIES) if self.get_option("common_names"): self._countries.update(self.COMMON_NAMES) override = self.get_option("override") if override: self._countries.update(override) self._countries = dict( (code, name) for code, name in self._countries.items() if name is not None ) if only and not only_choices: countries = {} for item in only: if isinstance(item, six.string_types): countries[item] = self._countries[item] else: key, value = item countries[key] = value self._countries = countries self.countries_first = [] first = self.get_option("first") or [] for code in first: code = self.alpha2(code) if code in self._countries: self.countries_first.append(code) return self._countries @property def alt_codes(self): if not hasattr(self, "_alt_codes"): # Again, local import so data is not loaded unless it's needed. from django_countries.data import ALT_CODES self._alt_codes = ALT_CODES return self._alt_codes @countries.deleter def countries(self): """ Reset the countries cache in case for some crazy reason the settings or internal options change. But surely no one is crazy enough to do that, right? """ if hasattr(self, "_countries"): del self._countries def translate_pair(self, code): """ Force a country to the current activated translation. :returns: ``CountryTuple(code, translated_country_name)`` namedtuple """ name = self.countries[code] if code in self.OLD_NAMES: # Check if there's an older translation available if there's no # translation for the newest name. with override(None): source_name = force_text(name) name = force_text(name) if name == source_name: for old_name in self.OLD_NAMES[code]: with override(None): source_old_name = force_text(old_name) old_name = force_text(old_name) if old_name != source_old_name: name = old_name break else: name = force_text(name) return CountryTuple(code, name) def __iter__(self): """ Iterate through countries, sorted by name. Each country record consists of a namedtuple of the two letter ISO3166-1 country ``code`` and short ``name``. The sorting happens based on the thread's current translation. Countries that are in ``settings.COUNTRIES_FIRST`` will be displayed before any sorted countries (in the order provided), and are only repeated in the sorted list if ``settings.COUNTRIES_FIRST_REPEAT`` is ``True``. The first countries can be separated from the sorted list by the value provided in ``settings.COUNTRIES_FIRST_BREAK``. """ # Initializes countries_first, so needs to happen first. countries = self.countries # Yield countries that should be displayed first. countries_first = (self.translate_pair(code) for code in self.countries_first) if self.get_option("first_sort"): countries_first = sorted(countries_first, key=sort_key) for item in countries_first: yield item if self.countries_first: first_break = self.get_option("first_break") if first_break: yield ("", force_text(first_break)) # Force translation before sorting. first_repeat = self.get_option("first_repeat") countries = ( self.translate_pair(code) for code in countries if first_repeat or code not in self.countries_first ) # Return sorted country list. for item in sorted(countries, key=sort_key): yield item def alpha2(self, code): """ Return the two letter country code when passed any type of ISO 3166-1 country code. If no match is found, returns an empty string. """ code = force_text(code).upper() if code.isdigit(): lookup_code = int(code) def find(alt_codes): return alt_codes[1] == lookup_code elif len(code) == 3: lookup_code = code def find(alt_codes): return alt_codes[0] == lookup_code else: find = None if find: code = None for alpha2, alt_codes in self.alt_codes.items(): if find(alt_codes): code = alpha2 break if code in self.countries: return code return "" def name(self, code): """ Return the name of a country, based on the code. If no match is found, returns an empty string. """ code = self.alpha2(code) if code not in self.countries: return "" return self.translate_pair(code)[1] def by_name(self, country, language="en"): """ Fetch a country's ISO3166-1 two letter country code from its name. An optional language parameter is also available. Warning: This depends on the quality of the available translations. If no match is found, returns an empty string. ..warning:: Be cautious about relying on this returning a country code (especially with any hard-coded string) since the ISO names of countries may change over time. """ with override(language): for code, name in self: if name.lower() == country.lower(): return code if code in self.OLD_NAMES: for old_name in self.OLD_NAMES[code]: if old_name.lower() == country.lower(): return code return "" def alpha3(self, code): """ Return the ISO 3166-1 three letter country code matching the provided country code. If no match is found, returns an empty string. """ code = self.alpha2(code) try: return self.alt_codes[code][0] except KeyError: return "" def __len__(self): """ len() used by several third party applications to calculate the length of choices. This will solve a bug related to generating fixtures. """ count = len(self.countries) # Add first countries, and the break if necessary. count += len(self.countries_first) if self.countries_first and self.get_option("first_break"): count += 1 return count def __bool__(self): return bool(self.countries) __nonzero__ = __bool__ def __contains__(self, code): """ Check to see if the countries contains the given code. """ return code in self.countries def __getitem__(self, index): """ Some applications expect to be able to access members of the field choices by index. """ try: return next(islice(self.__iter__(), index, index + 1)) except TypeError: return list(islice(self.__iter__(), index.start, index.stop, index.step))
SmileyChris/django-countries
django_countries/widgets.py
LazyChoicesMixin.choices
python
def choices(self): if isinstance(self._choices, Promise): self._choices = list(self._choices) return self._choices
When it's time to get the choices, if it was a lazy then figure it out now and memoize the result.
train
https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/widgets.py#L26-L33
[ "def _set_choices(self, value):\n self._choices = value\n" ]
class LazyChoicesMixin(object): @property @choices.setter def choices(self, value): self._set_choices(value) def _set_choices(self, value): self._choices = value
SmileyChris/django-countries
django_countries/ioc_data.py
check_ioc_countries
python
def check_ioc_countries(verbosity=1): from django_countries.data import COUNTRIES if verbosity: # pragma: no cover print("Checking if all IOC codes map correctly") for key in ISO_TO_IOC: assert COUNTRIES.get(key), "No ISO code for %s" % key if verbosity: # pragma: no cover print("Finished checking IOC codes")
Check if all IOC codes map to ISO codes correctly
train
https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/ioc_data.py#L318-L329
null
IOC_TO_ISO = { "AFG": "AF", "ALB": "AL", "ALG": "DZ", "AND": "AD", "ANG": "AO", "ANT": "AG", "ARG": "AR", "ARM": "AM", "ARU": "AW", "ASA": "AS", "AUS": "AU", "AUT": "AT", "AZE": "AZ", "BAH": "BS", "BAN": "BD", "BAR": "BB", "BDI": "BI", "BEL": "BE", "BEN": "BJ", "BER": "BM", "BHU": "BT", "BIH": "BA", "BIZ": "BZ", "BLR": "BY", "BOL": "BO", "BOT": "BW", "BRA": "BR", "BRN": "BH", "BRU": "BN", "BUL": "BG", "BUR": "BF", "CAF": "CF", "CAM": "KH", "CAN": "CA", "CAY": "KY", "CGO": "CG", "CHA": "TD", "CHI": "CL", "CHN": "CN", "CIV": "CI", "CMR": "CM", "COD": "CD", "COK": "CK", "COL": "CO", "COM": "KM", "CPV": "CV", "CRC": "CR", "CRO": "HR", "CUB": "CU", "CYP": "CY", "CZE": "CZ", "DEN": "DK", "DJI": "DJ", "DMA": "DM", "DOM": "DO", "ECU": "EC", "EGY": "EG", "ERI": "ER", "ESA": "SV", "ESP": "ES", "EST": "EE", "ETH": "ET", "FIJ": "FJ", "FIN": "FI", "FRA": "FR", "FSM": "FM", "GAB": "GA", "GAM": "GM", "GBR": "GB", "GBS": "GW", "GEO": "GE", "GEQ": "GQ", "GER": "DE", "GHA": "GH", "GRE": "GR", "GRN": "GD", "GUA": "GT", "GUI": "GN", "GUM": "GU", "GUY": "GY", "HAI": "HT", "HKG": "HK", "HON": "HN", "HUN": "HU", "INA": "ID", "IND": "IN", "IRI": "IR", "IRL": "IE", "IRQ": "IQ", "ISL": "IS", "ISR": "IL", "ISV": "VI", "ITA": "IT", "IVB": "VG", "JAM": "JM", "JOR": "JO", "JPN": "JP", "KAZ": "KZ", "KEN": "KE", "KGZ": "KG", "KIR": "KI", "KOR": "KR", "KSA": "SA", "KUW": "KW", "LAO": "LA", "LAT": "LV", "LBA": "LY", "LBR": "LR", "LCA": "LC", "LES": "LS", "LBN": "LB", "LIE": "LI", "LTU": "LT", "LUX": "LU", "MAD": "MG", "MAR": "MA", "MAS": "MY", "MAW": "MW", "MDA": "MD", "MDV": "MV", "MEX": "MX", "MGL": "MN", "MHL": "MH", "MKD": "MK", "MLI": "ML", "MLT": "MT", "MNE": "ME", "MON": "MC", "MOZ": "MZ", "MRI": "MU", "MTN": "MR", "MYA": "MM", "NAM": "NA", "NCA": "NI", "NED": "NL", "NEP": "NP", "NGR": "NG", "NIG": "NE", "NOR": "NO", "NRU": "NR", "NZL": "NZ", "OMA": "OM", "PAK": "PK", "PAN": "PA", "PAR": "PY", "PER": "PE", "PHI": "PH", "PLE": "PS", "PLW": "PW", "PNG": "PG", "POL": "PL", "POR": "PT", "PRK": "KP", "PUR": "PR", "QAT": "QA", "ROU": "RO", "RSA": "ZA", "RUS": "RU", "RWA": "RW", "SAM": "WS", "SEN": "SN", "SEY": "SC", "SKN": "KN", "SLE": "SL", "SLO": "SI", "SMR": "SM", "SNG": "SG", "SOL": "SB", "SOM": "SO", "SRB": "RS", "SRI": "LK", "STP": "ST", "SUD": "SD", "SUI": "CH", "SUR": "SR", "SVK": "SK", "SWE": "SE", "SWZ": "SZ", "SYR": "SY", "TAN": "TZ", "TGA": "TO", "THA": "TH", "TJK": "TJ", "TKM": "TM", "TLS": "TL", "TOG": "TG", "TPE": "TW", "TTO": "TT", "TUN": "TN", "TUR": "TR", "TUV": "TV", "UAE": "AE", "UGA": "UG", "UKR": "UA", "URU": "UY", "USA": "US", "UZB": "UZ", "VAN": "VU", "VEN": "VE", "VIE": "VN", "VIN": "VC", "YEM": "YE", "ZAM": "ZM", "ZIM": "ZW", } IOC_HISTORICAL_TO_ISO = { "AGR": "DZ", "AGL": "DZ", "BAD": "BB", "DAY": "BJ", "DAH": "BJ", "BSH": "BA", "HBR": "BZ", "VOL": "BF", "AFC": "CF", "CAB": "KH", "KHM": "KH", "CHD": "TD", "CIL": "CL", "PRC": "CN", "IVC": "CI", "CML": "CI", "COK": "CD", "ZAI": "CD", "COS": "CR", "TCH": "CZ", "DAN": "DK", "DIN": "DK", "RAU": "EG", # Used 1960, 1968 (also used by Syria in 1960) "UAR": "EG", "SAL": "SV", "SPA": "ES", "ETI": "ET", "FIG": "FJ", "GRB": "GB", "GBI": "GB", "ALL": "DE", "ALE": "DE", "GUT": "GT", "GUA": "GY", "GUI": "GY", "HOK": "HK", "UNG": "HU", "INS": "ID", "IRN": "IR", "IRA": "IR", "IRK": "IQ", "ICE": "IS", "ISL": "IL", "GIA": "JP", "JAP": "JP", "COR": "KR", "ARS": "SA", "SAU": "SA", "LYA": "LY", "LBY": "LY", "LEB": "LB", # Used from 1960-1964 "LIB": "LB", # Used from 1964-2016 "LIC": "LI", "LIT": "LT", "MAG": "MG", "MRC": "MA", "MAL": "MY", "MLD": "MD", "MOD": "MN", "MAT": "MT", "BIR": "MM", "BUR": "MM", "NGC": "NI", "NIC": "NI", "OLA": "NL", "NET": "NL", "NLD": "NL", "HOL": "NL", "NIG": "NG", "NGA": "NG", "NGR": "NE", "NZE": "NZ", "FIL": "PH", "NGY": "PG", "NGU": "PG", "NKO": "KP", "CDN": "KP", "PRI": "PR", "PRO": "PR", "ROM": "RO", "RUM": "RO", "SAF": "ZA", "SGL": "SN", "SIN": "SG", # Used from 1959-2016 "SLA": "SL", "SMA": "SM", "CEY": "LK", "CEI": "LK", "SVI": "CH", "SVE": "SE", "SUE": "SE", "SIR": "SY", "TON": "TO", "IOA": "TL", "RCF": "TW", "TWN": "TW", "ROC": "TW", "TRT": "TT", "URG": "UY", "SUA": "US", "EUA": "US", "VET": "VN", "VNM": "VN", "NRH": "ZM", "RHO": "ZW", } ISO_TO_IOC = dict((iso, ioc) for ioc, iso in IOC_TO_ISO.items())
SmileyChris/django-countries
django_countries/data.py
self_generate
python
def self_generate(output_filename, filename="iso3166-1.csv"): # pragma: no cover import csv import re countries = [] alt_codes = [] with open(filename, "r") as csv_file: for row in csv.reader(csv_file): name = row[0].rstrip("*") name = re.sub(r"\(the\)", "", name) if name: countries.append((name, row[1])) alt_codes.append((row[1], row[2], int(row[3]))) with open(__file__, "r") as source_file: contents = source_file.read() # Write countries. bits = re.match("(.*\nCOUNTRIES = \{\n)(.*?)(\n\}.*)", contents, re.DOTALL).groups() country_list = [] for name, code in countries: name = name.replace('"', r"\"").strip() country_list.append(' "{code}": _("{name}"),'.format(name=name, code=code)) content = bits[0] content += "\n".join(country_list) # Write alt codes. alt_bits = re.match( "(.*\nALT_CODES = \{\n)(.*)(\n\}.*)", bits[2], re.DOTALL ).groups() alt_list = [] for code, code3, codenum in alt_codes: name = name.replace('"', r"\"").strip() alt_list.append( ' "{code}": ("{code3}", {codenum}),'.format( code=code, code3=code3, codenum=codenum ) ) content += alt_bits[0] content += "\n".join(alt_list) content += alt_bits[2] # Generate file. with open(output_filename, "w") as output_file: output_file.write(content) return countries
The following code can be used for self-generation of this file. It requires a UTF-8 CSV file containing the short ISO name and two letter country code as the first two columns.
train
https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/data.py#L538-L585
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This is a self-generating script that contains all of the iso3166-1 data. To regenerate, a CSV file must be created that contains the latest data. Here's how to do that: 1. Visit https://www.iso.org/obp 2. Click the "Country Codes" radio option and click the search button 3. Filter by "Officially assigned codes" 4. Change the results per page to 300 5. Copy the html table and paste into Libreoffice Calc / Excel 6. Delete the French name column 7. Save as a CSV file in django_countries/iso3166-1.csv 8. Run this script from the command line """ from __future__ import unicode_literals import glob import os from django_countries.base import CountriesBase try: from django.utils.translation import ugettext_lazy as _ except ImportError: # pragma: no cover # Allows this module to be executed without Django installed. def _(x): return x # Nicely titled (and translatable) country names. COUNTRIES = { "AF": _("Afghanistan"), "AX": _("Åland Islands"), "AL": _("Albania"), "DZ": _("Algeria"), "AS": _("American Samoa"), "AD": _("Andorra"), "AO": _("Angola"), "AI": _("Anguilla"), "AQ": _("Antarctica"), "AG": _("Antigua and Barbuda"), "AR": _("Argentina"), "AM": _("Armenia"), "AW": _("Aruba"), "AU": _("Australia"), "AT": _("Austria"), "AZ": _("Azerbaijan"), "BS": _("Bahamas"), "BH": _("Bahrain"), "BD": _("Bangladesh"), "BB": _("Barbados"), "BY": _("Belarus"), "BE": _("Belgium"), "BZ": _("Belize"), "BJ": _("Benin"), "BM": _("Bermuda"), "BT": _("Bhutan"), "BO": _("Bolivia (Plurinational State of)"), "BQ": _("Bonaire, Sint Eustatius and Saba"), "BA": _("Bosnia and Herzegovina"), "BW": _("Botswana"), "BV": _("Bouvet Island"), "BR": _("Brazil"), "IO": _("British Indian Ocean Territory"), "BN": _("Brunei Darussalam"), "BG": _("Bulgaria"), "BF": _("Burkina Faso"), "BI": _("Burundi"), "CV": _("Cabo Verde"), "KH": _("Cambodia"), "CM": _("Cameroon"), "CA": _("Canada"), "KY": _("Cayman Islands"), "CF": _("Central African Republic"), "TD": _("Chad"), "CL": _("Chile"), "CN": _("China"), "CX": _("Christmas Island"), "CC": _("Cocos (Keeling) Islands"), "CO": _("Colombia"), "KM": _("Comoros"), "CD": _("Congo (the Democratic Republic of the)"), "CG": _("Congo"), "CK": _("Cook Islands"), "CR": _("Costa Rica"), "CI": _("Côte d'Ivoire"), "HR": _("Croatia"), "CU": _("Cuba"), "CW": _("Curaçao"), "CY": _("Cyprus"), "CZ": _("Czechia"), "DK": _("Denmark"), "DJ": _("Djibouti"), "DM": _("Dominica"), "DO": _("Dominican Republic"), "EC": _("Ecuador"), "EG": _("Egypt"), "SV": _("El Salvador"), "GQ": _("Equatorial Guinea"), "ER": _("Eritrea"), "EE": _("Estonia"), "SZ": _("Eswatini"), "ET": _("Ethiopia"), "FK": _("Falkland Islands [Malvinas]"), "FO": _("Faroe Islands"), "FJ": _("Fiji"), "FI": _("Finland"), "FR": _("France"), "GF": _("French Guiana"), "PF": _("French Polynesia"), "TF": _("French Southern Territories"), "GA": _("Gabon"), "GM": _("Gambia"), "GE": _("Georgia"), "DE": _("Germany"), "GH": _("Ghana"), "GI": _("Gibraltar"), "GR": _("Greece"), "GL": _("Greenland"), "GD": _("Grenada"), "GP": _("Guadeloupe"), "GU": _("Guam"), "GT": _("Guatemala"), "GG": _("Guernsey"), "GN": _("Guinea"), "GW": _("Guinea-Bissau"), "GY": _("Guyana"), "HT": _("Haiti"), "HM": _("Heard Island and McDonald Islands"), "VA": _("Holy See"), "HN": _("Honduras"), "HK": _("Hong Kong"), "HU": _("Hungary"), "IS": _("Iceland"), "IN": _("India"), "ID": _("Indonesia"), "IR": _("Iran (Islamic Republic of)"), "IQ": _("Iraq"), "IE": _("Ireland"), "IM": _("Isle of Man"), "IL": _("Israel"), "IT": _("Italy"), "JM": _("Jamaica"), "JP": _("Japan"), "JE": _("Jersey"), "JO": _("Jordan"), "KZ": _("Kazakhstan"), "KE": _("Kenya"), "KI": _("Kiribati"), "KP": _("Korea (the Democratic People's Republic of)"), "KR": _("Korea (the Republic of)"), "KW": _("Kuwait"), "KG": _("Kyrgyzstan"), "LA": _("Lao People's Democratic Republic"), "LV": _("Latvia"), "LB": _("Lebanon"), "LS": _("Lesotho"), "LR": _("Liberia"), "LY": _("Libya"), "LI": _("Liechtenstein"), "LT": _("Lithuania"), "LU": _("Luxembourg"), "MO": _("Macao"), "MK": _("Macedonia (the former Yugoslav Republic of)"), "MG": _("Madagascar"), "MW": _("Malawi"), "MY": _("Malaysia"), "MV": _("Maldives"), "ML": _("Mali"), "MT": _("Malta"), "MH": _("Marshall Islands"), "MQ": _("Martinique"), "MR": _("Mauritania"), "MU": _("Mauritius"), "YT": _("Mayotte"), "MX": _("Mexico"), "FM": _("Micronesia (Federated States of)"), "MD": _("Moldova (the Republic of)"), "MC": _("Monaco"), "MN": _("Mongolia"), "ME": _("Montenegro"), "MS": _("Montserrat"), "MA": _("Morocco"), "MZ": _("Mozambique"), "MM": _("Myanmar"), "NA": _("Namibia"), "NR": _("Nauru"), "NP": _("Nepal"), "NL": _("Netherlands"), "NC": _("New Caledonia"), "NZ": _("New Zealand"), "NI": _("Nicaragua"), "NE": _("Niger"), "NG": _("Nigeria"), "NU": _("Niue"), "NF": _("Norfolk Island"), "MP": _("Northern Mariana Islands"), "NO": _("Norway"), "OM": _("Oman"), "PK": _("Pakistan"), "PW": _("Palau"), "PS": _("Palestine, State of"), "PA": _("Panama"), "PG": _("Papua New Guinea"), "PY": _("Paraguay"), "PE": _("Peru"), "PH": _("Philippines"), "PN": _("Pitcairn"), "PL": _("Poland"), "PT": _("Portugal"), "PR": _("Puerto Rico"), "QA": _("Qatar"), "RE": _("Réunion"), "RO": _("Romania"), "RU": _("Russian Federation"), "RW": _("Rwanda"), "BL": _("Saint Barthélemy"), "SH": _("Saint Helena, Ascension and Tristan da Cunha"), "KN": _("Saint Kitts and Nevis"), "LC": _("Saint Lucia"), "MF": _("Saint Martin (French part)"), "PM": _("Saint Pierre and Miquelon"), "VC": _("Saint Vincent and the Grenadines"), "WS": _("Samoa"), "SM": _("San Marino"), "ST": _("Sao Tome and Principe"), "SA": _("Saudi Arabia"), "SN": _("Senegal"), "RS": _("Serbia"), "SC": _("Seychelles"), "SL": _("Sierra Leone"), "SG": _("Singapore"), "SX": _("Sint Maarten (Dutch part)"), "SK": _("Slovakia"), "SI": _("Slovenia"), "SB": _("Solomon Islands"), "SO": _("Somalia"), "ZA": _("South Africa"), "GS": _("South Georgia and the South Sandwich Islands"), "SS": _("South Sudan"), "ES": _("Spain"), "LK": _("Sri Lanka"), "SD": _("Sudan"), "SR": _("Suriname"), "SJ": _("Svalbard and Jan Mayen"), "SE": _("Sweden"), "CH": _("Switzerland"), "SY": _("Syrian Arab Republic"), "TW": _("Taiwan (Province of China)"), "TJ": _("Tajikistan"), "TZ": _("Tanzania, United Republic of"), "TH": _("Thailand"), "TL": _("Timor-Leste"), "TG": _("Togo"), "TK": _("Tokelau"), "TO": _("Tonga"), "TT": _("Trinidad and Tobago"), "TN": _("Tunisia"), "TR": _("Turkey"), "TM": _("Turkmenistan"), "TC": _("Turks and Caicos Islands"), "TV": _("Tuvalu"), "UG": _("Uganda"), "UA": _("Ukraine"), "AE": _("United Arab Emirates"), "GB": _("United Kingdom of Great Britain and Northern Ireland"), "UM": _("United States Minor Outlying Islands"), "US": _("United States of America"), "UY": _("Uruguay"), "UZ": _("Uzbekistan"), "VU": _("Vanuatu"), "VE": _("Venezuela (Bolivarian Republic of)"), "VN": _("Viet Nam"), "VG": _("Virgin Islands (British)"), "VI": _("Virgin Islands (U.S.)"), "WF": _("Wallis and Futuna"), "EH": _("Western Sahara"), "YE": _("Yemen"), "ZM": _("Zambia"), "ZW": _("Zimbabwe"), } ALT_CODES = { "AF": ("AFG", 4), "AX": ("ALA", 248), "AL": ("ALB", 8), "DZ": ("DZA", 12), "AS": ("ASM", 16), "AD": ("AND", 20), "AO": ("AGO", 24), "AI": ("AIA", 660), "AQ": ("ATA", 10), "AG": ("ATG", 28), "AR": ("ARG", 32), "AM": ("ARM", 51), "AW": ("ABW", 533), "AU": ("AUS", 36), "AT": ("AUT", 40), "AZ": ("AZE", 31), "BS": ("BHS", 44), "BH": ("BHR", 48), "BD": ("BGD", 50), "BB": ("BRB", 52), "BY": ("BLR", 112), "BE": ("BEL", 56), "BZ": ("BLZ", 84), "BJ": ("BEN", 204), "BM": ("BMU", 60), "BT": ("BTN", 64), "BO": ("BOL", 68), "BQ": ("BES", 535), "BA": ("BIH", 70), "BW": ("BWA", 72), "BV": ("BVT", 74), "BR": ("BRA", 76), "IO": ("IOT", 86), "BN": ("BRN", 96), "BG": ("BGR", 100), "BF": ("BFA", 854), "BI": ("BDI", 108), "CV": ("CPV", 132), "KH": ("KHM", 116), "CM": ("CMR", 120), "CA": ("CAN", 124), "KY": ("CYM", 136), "CF": ("CAF", 140), "TD": ("TCD", 148), "CL": ("CHL", 152), "CN": ("CHN", 156), "CX": ("CXR", 162), "CC": ("CCK", 166), "CO": ("COL", 170), "KM": ("COM", 174), "CD": ("COD", 180), "CG": ("COG", 178), "CK": ("COK", 184), "CR": ("CRI", 188), "CI": ("CIV", 384), "HR": ("HRV", 191), "CU": ("CUB", 192), "CW": ("CUW", 531), "CY": ("CYP", 196), "CZ": ("CZE", 203), "DK": ("DNK", 208), "DJ": ("DJI", 262), "DM": ("DMA", 212), "DO": ("DOM", 214), "EC": ("ECU", 218), "EG": ("EGY", 818), "SV": ("SLV", 222), "GQ": ("GNQ", 226), "ER": ("ERI", 232), "EE": ("EST", 233), "SZ": ("SWZ", 748), "ET": ("ETH", 231), "FK": ("FLK", 238), "FO": ("FRO", 234), "FJ": ("FJI", 242), "FI": ("FIN", 246), "FR": ("FRA", 250), "GF": ("GUF", 254), "PF": ("PYF", 258), "TF": ("ATF", 260), "GA": ("GAB", 266), "GM": ("GMB", 270), "GE": ("GEO", 268), "DE": ("DEU", 276), "GH": ("GHA", 288), "GI": ("GIB", 292), "GR": ("GRC", 300), "GL": ("GRL", 304), "GD": ("GRD", 308), "GP": ("GLP", 312), "GU": ("GUM", 316), "GT": ("GTM", 320), "GG": ("GGY", 831), "GN": ("GIN", 324), "GW": ("GNB", 624), "GY": ("GUY", 328), "HT": ("HTI", 332), "HM": ("HMD", 334), "VA": ("VAT", 336), "HN": ("HND", 340), "HK": ("HKG", 344), "HU": ("HUN", 348), "IS": ("ISL", 352), "IN": ("IND", 356), "ID": ("IDN", 360), "IR": ("IRN", 364), "IQ": ("IRQ", 368), "IE": ("IRL", 372), "IM": ("IMN", 833), "IL": ("ISR", 376), "IT": ("ITA", 380), "JM": ("JAM", 388), "JP": ("JPN", 392), "JE": ("JEY", 832), "JO": ("JOR", 400), "KZ": ("KAZ", 398), "KE": ("KEN", 404), "KI": ("KIR", 296), "KP": ("PRK", 408), "KR": ("KOR", 410), "KW": ("KWT", 414), "KG": ("KGZ", 417), "LA": ("LAO", 418), "LV": ("LVA", 428), "LB": ("LBN", 422), "LS": ("LSO", 426), "LR": ("LBR", 430), "LY": ("LBY", 434), "LI": ("LIE", 438), "LT": ("LTU", 440), "LU": ("LUX", 442), "MO": ("MAC", 446), "MK": ("MKD", 807), "MG": ("MDG", 450), "MW": ("MWI", 454), "MY": ("MYS", 458), "MV": ("MDV", 462), "ML": ("MLI", 466), "MT": ("MLT", 470), "MH": ("MHL", 584), "MQ": ("MTQ", 474), "MR": ("MRT", 478), "MU": ("MUS", 480), "YT": ("MYT", 175), "MX": ("MEX", 484), "FM": ("FSM", 583), "MD": ("MDA", 498), "MC": ("MCO", 492), "MN": ("MNG", 496), "ME": ("MNE", 499), "MS": ("MSR", 500), "MA": ("MAR", 504), "MZ": ("MOZ", 508), "MM": ("MMR", 104), "NA": ("NAM", 516), "NR": ("NRU", 520), "NP": ("NPL", 524), "NL": ("NLD", 528), "NC": ("NCL", 540), "NZ": ("NZL", 554), "NI": ("NIC", 558), "NE": ("NER", 562), "NG": ("NGA", 566), "NU": ("NIU", 570), "NF": ("NFK", 574), "MP": ("MNP", 580), "NO": ("NOR", 578), "OM": ("OMN", 512), "PK": ("PAK", 586), "PW": ("PLW", 585), "PS": ("PSE", 275), "PA": ("PAN", 591), "PG": ("PNG", 598), "PY": ("PRY", 600), "PE": ("PER", 604), "PH": ("PHL", 608), "PN": ("PCN", 612), "PL": ("POL", 616), "PT": ("PRT", 620), "PR": ("PRI", 630), "QA": ("QAT", 634), "RE": ("REU", 638), "RO": ("ROU", 642), "RU": ("RUS", 643), "RW": ("RWA", 646), "BL": ("BLM", 652), "SH": ("SHN", 654), "KN": ("KNA", 659), "LC": ("LCA", 662), "MF": ("MAF", 663), "PM": ("SPM", 666), "VC": ("VCT", 670), "WS": ("WSM", 882), "SM": ("SMR", 674), "ST": ("STP", 678), "SA": ("SAU", 682), "SN": ("SEN", 686), "RS": ("SRB", 688), "SC": ("SYC", 690), "SL": ("SLE", 694), "SG": ("SGP", 702), "SX": ("SXM", 534), "SK": ("SVK", 703), "SI": ("SVN", 705), "SB": ("SLB", 90), "SO": ("SOM", 706), "ZA": ("ZAF", 710), "GS": ("SGS", 239), "SS": ("SSD", 728), "ES": ("ESP", 724), "LK": ("LKA", 144), "SD": ("SDN", 729), "SR": ("SUR", 740), "SJ": ("SJM", 744), "SE": ("SWE", 752), "CH": ("CHE", 756), "SY": ("SYR", 760), "TW": ("TWN", 158), "TJ": ("TJK", 762), "TZ": ("TZA", 834), "TH": ("THA", 764), "TL": ("TLS", 626), "TG": ("TGO", 768), "TK": ("TKL", 772), "TO": ("TON", 776), "TT": ("TTO", 780), "TN": ("TUN", 788), "TR": ("TUR", 792), "TM": ("TKM", 795), "TC": ("TCA", 796), "TV": ("TUV", 798), "UG": ("UGA", 800), "UA": ("UKR", 804), "AE": ("ARE", 784), "GB": ("GBR", 826), "UM": ("UMI", 581), "US": ("USA", 840), "UY": ("URY", 858), "UZ": ("UZB", 860), "VU": ("VUT", 548), "VE": ("VEN", 862), "VN": ("VNM", 704), "VG": ("VGB", 92), "VI": ("VIR", 850), "WF": ("WLF", 876), "EH": ("ESH", 732), "YE": ("YEM", 887), "ZM": ("ZMB", 894), "ZW": ("ZWE", 716), } def check_flags(verbosity=1): files = {} this_dir = os.path.dirname(__file__) for path in glob.glob(os.path.join(this_dir, "static", "flags", "*.gif")): files[os.path.basename(os.path.splitext(path)[0]).upper()] = path flags_missing = set(COUNTRIES) - set(files) if flags_missing: # pragma: no cover print("The following country codes are missing a flag:") for code in sorted(flags_missing): print(" {0} ({1})".format(code, COUNTRIES[code])) elif verbosity: # pragma: no cover print("All country codes have flags. :)") code_missing = set(files) - set(COUNTRIES) # Special-case EU and __ for special_code in ("EU", "__"): code_missing.discard(special_code) if code_missing: # pragma: no cover print("") print("The following flags don't have a matching country code:") for path in sorted(code_missing): print(" {0}".format(path)) def check_common_names(): common_names_missing = set(CountriesBase.COMMON_NAMES) - set(COUNTRIES) if common_names_missing: # pragma: no cover print("") print("The following common names do not match an official country code:") for code in sorted(common_names_missing): print(" {0}".format(code)) if __name__ == "__main__": # pragma: no cover countries = self_generate(__file__) print("Wrote {0} countries.".format(len(countries))) print("") check_flags() check_common_names()
SmileyChris/django-countries
django_countries/fields.py
LazyChoicesMixin._set_choices
python
def _set_choices(self, value): super(LazyChoicesMixin, self)._set_choices(value) self.widget.choices = value
Also update the widget's choices.
train
https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/fields.py#L235-L240
null
class LazyChoicesMixin(widgets.LazyChoicesMixin):
SmileyChris/django-countries
django_countries/fields.py
CountryField.pre_save
python
def pre_save(self, *args, **kwargs): "Returns field's value just before saving." value = super(CharField, self).pre_save(*args, **kwargs) return self.get_prep_value(value)
Returns field's value just before saving.
train
https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/fields.py#L310-L313
null
class CountryField(CharField): """ A country field for Django models that provides all ISO 3166-1 countries as choices. """ descriptor_class = CountryDescriptor def __init__(self, *args, **kwargs): countries_class = kwargs.pop("countries", None) self.countries = countries_class() if countries_class else countries self.countries_flag_url = kwargs.pop("countries_flag_url", None) self.blank_label = kwargs.pop("blank_label", None) self.multiple = kwargs.pop("multiple", None) kwargs["choices"] = self.countries if self.multiple: kwargs["max_length"] = len(self.countries) * 3 - 1 else: kwargs["max_length"] = 2 super(CharField, self).__init__(*args, **kwargs) def check(self, **kwargs): errors = super(CountryField, self).check(**kwargs) errors.extend(self._check_multiple()) return errors def _check_multiple(self): if not self.multiple or not self.null: return [] hint = "Remove null=True argument on the field" if not self.blank: hint += " (just add blank=True if you want to allow no selection)" hint += "." return [ checks.Error( "Field specifies multiple=True, so should not be null.", obj=self, id="django_countries.E100", hint=hint, ) ] def get_internal_type(self): return "CharField" def contribute_to_class(self, cls, name): super(CountryField, self).contribute_to_class(cls, name) setattr(cls, self.name, self.descriptor_class(self)) def get_prep_value(self, value): "Returns field's value prepared for saving into a database." value = self.get_clean_value(value) if self.multiple: if value: value = ",".join(value) else: value = "" return super(CharField, self).get_prep_value(value) def get_clean_value(self, value): if value is None: return None if not self.multiple: return country_to_text(value) if isinstance(value, (basestring, Country)): if isinstance(value, basestring) and "," in value: value = value.split(",") else: value = [value] return list(filter(None, [country_to_text(c) for c in value])) def deconstruct(self): """ Remove choices from deconstructed field, as this is the country list and not user editable. Not including the ``blank_label`` property, as this isn't database related. """ name, path, args, kwargs = super(CountryField, self).deconstruct() kwargs.pop("choices") if self.multiple: # multiple determines the length of the field kwargs["multiple"] = self.multiple if self.countries is not countries: # Include the countries class if it's not the default countries # instance. kwargs["countries"] = self.countries.__class__ return name, path, args, kwargs def get_choices(self, include_blank=True, blank_choice=None, *args, **kwargs): if blank_choice is None: if self.blank_label is None: blank_choice = BLANK_CHOICE_DASH else: blank_choice = [("", self.blank_label)] if self.multiple: include_blank = False return super(CountryField, self).get_choices( include_blank=include_blank, blank_choice=blank_choice, *args, **kwargs ) get_choices = lazy(get_choices, list) def formfield(self, **kwargs): kwargs.setdefault( "choices_form_class", LazyTypedMultipleChoiceField if self.multiple else LazyTypedChoiceField, ) if "coerce" not in kwargs: kwargs["coerce"] = super(CountryField, self).to_python field = super(CharField, self).formfield(**kwargs) return field def to_python(self, value): if not self.multiple: return super(CountryField, self).to_python(value) if not value: return value if isinstance(value, basestring): value = value.split(",") output = [] for item in value: output.append(super(CountryField, self).to_python(item)) return output def validate(self, value, model_instance): """ Use custom validation for when using a multiple countries field. """ if not self.multiple: return super(CountryField, self).validate(value, model_instance) if not self.editable: # Skip validation for non-editable fields. return if value: choices = [option_key for option_key, option_value in self.choices] for single_value in value: if single_value not in choices: raise exceptions.ValidationError( self.error_messages["invalid_choice"], code="invalid_choice", params={"value": single_value}, ) if not self.blank and value in self.empty_values: raise exceptions.ValidationError(self.error_messages["blank"], code="blank") def value_to_string(self, obj): """ Ensure data is serialized correctly. """ value = self.value_from_object(obj) return self.get_prep_value(value)
SmileyChris/django-countries
django_countries/fields.py
CountryField.get_prep_value
python
def get_prep_value(self, value): "Returns field's value prepared for saving into a database." value = self.get_clean_value(value) if self.multiple: if value: value = ",".join(value) else: value = "" return super(CharField, self).get_prep_value(value)
Returns field's value prepared for saving into a database.
train
https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/fields.py#L315-L323
null
class CountryField(CharField): """ A country field for Django models that provides all ISO 3166-1 countries as choices. """ descriptor_class = CountryDescriptor def __init__(self, *args, **kwargs): countries_class = kwargs.pop("countries", None) self.countries = countries_class() if countries_class else countries self.countries_flag_url = kwargs.pop("countries_flag_url", None) self.blank_label = kwargs.pop("blank_label", None) self.multiple = kwargs.pop("multiple", None) kwargs["choices"] = self.countries if self.multiple: kwargs["max_length"] = len(self.countries) * 3 - 1 else: kwargs["max_length"] = 2 super(CharField, self).__init__(*args, **kwargs) def check(self, **kwargs): errors = super(CountryField, self).check(**kwargs) errors.extend(self._check_multiple()) return errors def _check_multiple(self): if not self.multiple or not self.null: return [] hint = "Remove null=True argument on the field" if not self.blank: hint += " (just add blank=True if you want to allow no selection)" hint += "." return [ checks.Error( "Field specifies multiple=True, so should not be null.", obj=self, id="django_countries.E100", hint=hint, ) ] def get_internal_type(self): return "CharField" def contribute_to_class(self, cls, name): super(CountryField, self).contribute_to_class(cls, name) setattr(cls, self.name, self.descriptor_class(self)) def pre_save(self, *args, **kwargs): "Returns field's value just before saving." value = super(CharField, self).pre_save(*args, **kwargs) return self.get_prep_value(value) def get_clean_value(self, value): if value is None: return None if not self.multiple: return country_to_text(value) if isinstance(value, (basestring, Country)): if isinstance(value, basestring) and "," in value: value = value.split(",") else: value = [value] return list(filter(None, [country_to_text(c) for c in value])) def deconstruct(self): """ Remove choices from deconstructed field, as this is the country list and not user editable. Not including the ``blank_label`` property, as this isn't database related. """ name, path, args, kwargs = super(CountryField, self).deconstruct() kwargs.pop("choices") if self.multiple: # multiple determines the length of the field kwargs["multiple"] = self.multiple if self.countries is not countries: # Include the countries class if it's not the default countries # instance. kwargs["countries"] = self.countries.__class__ return name, path, args, kwargs def get_choices(self, include_blank=True, blank_choice=None, *args, **kwargs): if blank_choice is None: if self.blank_label is None: blank_choice = BLANK_CHOICE_DASH else: blank_choice = [("", self.blank_label)] if self.multiple: include_blank = False return super(CountryField, self).get_choices( include_blank=include_blank, blank_choice=blank_choice, *args, **kwargs ) get_choices = lazy(get_choices, list) def formfield(self, **kwargs): kwargs.setdefault( "choices_form_class", LazyTypedMultipleChoiceField if self.multiple else LazyTypedChoiceField, ) if "coerce" not in kwargs: kwargs["coerce"] = super(CountryField, self).to_python field = super(CharField, self).formfield(**kwargs) return field def to_python(self, value): if not self.multiple: return super(CountryField, self).to_python(value) if not value: return value if isinstance(value, basestring): value = value.split(",") output = [] for item in value: output.append(super(CountryField, self).to_python(item)) return output def validate(self, value, model_instance): """ Use custom validation for when using a multiple countries field. """ if not self.multiple: return super(CountryField, self).validate(value, model_instance) if not self.editable: # Skip validation for non-editable fields. return if value: choices = [option_key for option_key, option_value in self.choices] for single_value in value: if single_value not in choices: raise exceptions.ValidationError( self.error_messages["invalid_choice"], code="invalid_choice", params={"value": single_value}, ) if not self.blank and value in self.empty_values: raise exceptions.ValidationError(self.error_messages["blank"], code="blank") def value_to_string(self, obj): """ Ensure data is serialized correctly. """ value = self.value_from_object(obj) return self.get_prep_value(value)
SmileyChris/django-countries
django_countries/fields.py
CountryField.deconstruct
python
def deconstruct(self): name, path, args, kwargs = super(CountryField, self).deconstruct() kwargs.pop("choices") if self.multiple: # multiple determines the length of the field kwargs["multiple"] = self.multiple if self.countries is not countries: # Include the countries class if it's not the default countries # instance. kwargs["countries"] = self.countries.__class__ return name, path, args, kwargs
Remove choices from deconstructed field, as this is the country list and not user editable. Not including the ``blank_label`` property, as this isn't database related.
train
https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/fields.py#L337-L353
null
class CountryField(CharField): """ A country field for Django models that provides all ISO 3166-1 countries as choices. """ descriptor_class = CountryDescriptor def __init__(self, *args, **kwargs): countries_class = kwargs.pop("countries", None) self.countries = countries_class() if countries_class else countries self.countries_flag_url = kwargs.pop("countries_flag_url", None) self.blank_label = kwargs.pop("blank_label", None) self.multiple = kwargs.pop("multiple", None) kwargs["choices"] = self.countries if self.multiple: kwargs["max_length"] = len(self.countries) * 3 - 1 else: kwargs["max_length"] = 2 super(CharField, self).__init__(*args, **kwargs) def check(self, **kwargs): errors = super(CountryField, self).check(**kwargs) errors.extend(self._check_multiple()) return errors def _check_multiple(self): if not self.multiple or not self.null: return [] hint = "Remove null=True argument on the field" if not self.blank: hint += " (just add blank=True if you want to allow no selection)" hint += "." return [ checks.Error( "Field specifies multiple=True, so should not be null.", obj=self, id="django_countries.E100", hint=hint, ) ] def get_internal_type(self): return "CharField" def contribute_to_class(self, cls, name): super(CountryField, self).contribute_to_class(cls, name) setattr(cls, self.name, self.descriptor_class(self)) def pre_save(self, *args, **kwargs): "Returns field's value just before saving." value = super(CharField, self).pre_save(*args, **kwargs) return self.get_prep_value(value) def get_prep_value(self, value): "Returns field's value prepared for saving into a database." value = self.get_clean_value(value) if self.multiple: if value: value = ",".join(value) else: value = "" return super(CharField, self).get_prep_value(value) def get_clean_value(self, value): if value is None: return None if not self.multiple: return country_to_text(value) if isinstance(value, (basestring, Country)): if isinstance(value, basestring) and "," in value: value = value.split(",") else: value = [value] return list(filter(None, [country_to_text(c) for c in value])) def get_choices(self, include_blank=True, blank_choice=None, *args, **kwargs): if blank_choice is None: if self.blank_label is None: blank_choice = BLANK_CHOICE_DASH else: blank_choice = [("", self.blank_label)] if self.multiple: include_blank = False return super(CountryField, self).get_choices( include_blank=include_blank, blank_choice=blank_choice, *args, **kwargs ) get_choices = lazy(get_choices, list) def formfield(self, **kwargs): kwargs.setdefault( "choices_form_class", LazyTypedMultipleChoiceField if self.multiple else LazyTypedChoiceField, ) if "coerce" not in kwargs: kwargs["coerce"] = super(CountryField, self).to_python field = super(CharField, self).formfield(**kwargs) return field def to_python(self, value): if not self.multiple: return super(CountryField, self).to_python(value) if not value: return value if isinstance(value, basestring): value = value.split(",") output = [] for item in value: output.append(super(CountryField, self).to_python(item)) return output def validate(self, value, model_instance): """ Use custom validation for when using a multiple countries field. """ if not self.multiple: return super(CountryField, self).validate(value, model_instance) if not self.editable: # Skip validation for non-editable fields. return if value: choices = [option_key for option_key, option_value in self.choices] for single_value in value: if single_value not in choices: raise exceptions.ValidationError( self.error_messages["invalid_choice"], code="invalid_choice", params={"value": single_value}, ) if not self.blank and value in self.empty_values: raise exceptions.ValidationError(self.error_messages["blank"], code="blank") def value_to_string(self, obj): """ Ensure data is serialized correctly. """ value = self.value_from_object(obj) return self.get_prep_value(value)
SmileyChris/django-countries
django_countries/fields.py
CountryField.validate
python
def validate(self, value, model_instance): if not self.multiple: return super(CountryField, self).validate(value, model_instance) if not self.editable: # Skip validation for non-editable fields. return if value: choices = [option_key for option_key, option_value in self.choices] for single_value in value: if single_value not in choices: raise exceptions.ValidationError( self.error_messages["invalid_choice"], code="invalid_choice", params={"value": single_value}, ) if not self.blank and value in self.empty_values: raise exceptions.ValidationError(self.error_messages["blank"], code="blank")
Use custom validation for when using a multiple countries field.
train
https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/fields.py#L391-L413
null
class CountryField(CharField): """ A country field for Django models that provides all ISO 3166-1 countries as choices. """ descriptor_class = CountryDescriptor def __init__(self, *args, **kwargs): countries_class = kwargs.pop("countries", None) self.countries = countries_class() if countries_class else countries self.countries_flag_url = kwargs.pop("countries_flag_url", None) self.blank_label = kwargs.pop("blank_label", None) self.multiple = kwargs.pop("multiple", None) kwargs["choices"] = self.countries if self.multiple: kwargs["max_length"] = len(self.countries) * 3 - 1 else: kwargs["max_length"] = 2 super(CharField, self).__init__(*args, **kwargs) def check(self, **kwargs): errors = super(CountryField, self).check(**kwargs) errors.extend(self._check_multiple()) return errors def _check_multiple(self): if not self.multiple or not self.null: return [] hint = "Remove null=True argument on the field" if not self.blank: hint += " (just add blank=True if you want to allow no selection)" hint += "." return [ checks.Error( "Field specifies multiple=True, so should not be null.", obj=self, id="django_countries.E100", hint=hint, ) ] def get_internal_type(self): return "CharField" def contribute_to_class(self, cls, name): super(CountryField, self).contribute_to_class(cls, name) setattr(cls, self.name, self.descriptor_class(self)) def pre_save(self, *args, **kwargs): "Returns field's value just before saving." value = super(CharField, self).pre_save(*args, **kwargs) return self.get_prep_value(value) def get_prep_value(self, value): "Returns field's value prepared for saving into a database." value = self.get_clean_value(value) if self.multiple: if value: value = ",".join(value) else: value = "" return super(CharField, self).get_prep_value(value) def get_clean_value(self, value): if value is None: return None if not self.multiple: return country_to_text(value) if isinstance(value, (basestring, Country)): if isinstance(value, basestring) and "," in value: value = value.split(",") else: value = [value] return list(filter(None, [country_to_text(c) for c in value])) def deconstruct(self): """ Remove choices from deconstructed field, as this is the country list and not user editable. Not including the ``blank_label`` property, as this isn't database related. """ name, path, args, kwargs = super(CountryField, self).deconstruct() kwargs.pop("choices") if self.multiple: # multiple determines the length of the field kwargs["multiple"] = self.multiple if self.countries is not countries: # Include the countries class if it's not the default countries # instance. kwargs["countries"] = self.countries.__class__ return name, path, args, kwargs def get_choices(self, include_blank=True, blank_choice=None, *args, **kwargs): if blank_choice is None: if self.blank_label is None: blank_choice = BLANK_CHOICE_DASH else: blank_choice = [("", self.blank_label)] if self.multiple: include_blank = False return super(CountryField, self).get_choices( include_blank=include_blank, blank_choice=blank_choice, *args, **kwargs ) get_choices = lazy(get_choices, list) def formfield(self, **kwargs): kwargs.setdefault( "choices_form_class", LazyTypedMultipleChoiceField if self.multiple else LazyTypedChoiceField, ) if "coerce" not in kwargs: kwargs["coerce"] = super(CountryField, self).to_python field = super(CharField, self).formfield(**kwargs) return field def to_python(self, value): if not self.multiple: return super(CountryField, self).to_python(value) if not value: return value if isinstance(value, basestring): value = value.split(",") output = [] for item in value: output.append(super(CountryField, self).to_python(item)) return output def value_to_string(self, obj): """ Ensure data is serialized correctly. """ value = self.value_from_object(obj) return self.get_prep_value(value)
SmileyChris/django-countries
django_countries/fields.py
CountryField.value_to_string
python
def value_to_string(self, obj): value = self.value_from_object(obj) return self.get_prep_value(value)
Ensure data is serialized correctly.
train
https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/fields.py#L415-L420
null
class CountryField(CharField): """ A country field for Django models that provides all ISO 3166-1 countries as choices. """ descriptor_class = CountryDescriptor def __init__(self, *args, **kwargs): countries_class = kwargs.pop("countries", None) self.countries = countries_class() if countries_class else countries self.countries_flag_url = kwargs.pop("countries_flag_url", None) self.blank_label = kwargs.pop("blank_label", None) self.multiple = kwargs.pop("multiple", None) kwargs["choices"] = self.countries if self.multiple: kwargs["max_length"] = len(self.countries) * 3 - 1 else: kwargs["max_length"] = 2 super(CharField, self).__init__(*args, **kwargs) def check(self, **kwargs): errors = super(CountryField, self).check(**kwargs) errors.extend(self._check_multiple()) return errors def _check_multiple(self): if not self.multiple or not self.null: return [] hint = "Remove null=True argument on the field" if not self.blank: hint += " (just add blank=True if you want to allow no selection)" hint += "." return [ checks.Error( "Field specifies multiple=True, so should not be null.", obj=self, id="django_countries.E100", hint=hint, ) ] def get_internal_type(self): return "CharField" def contribute_to_class(self, cls, name): super(CountryField, self).contribute_to_class(cls, name) setattr(cls, self.name, self.descriptor_class(self)) def pre_save(self, *args, **kwargs): "Returns field's value just before saving." value = super(CharField, self).pre_save(*args, **kwargs) return self.get_prep_value(value) def get_prep_value(self, value): "Returns field's value prepared for saving into a database." value = self.get_clean_value(value) if self.multiple: if value: value = ",".join(value) else: value = "" return super(CharField, self).get_prep_value(value) def get_clean_value(self, value): if value is None: return None if not self.multiple: return country_to_text(value) if isinstance(value, (basestring, Country)): if isinstance(value, basestring) and "," in value: value = value.split(",") else: value = [value] return list(filter(None, [country_to_text(c) for c in value])) def deconstruct(self): """ Remove choices from deconstructed field, as this is the country list and not user editable. Not including the ``blank_label`` property, as this isn't database related. """ name, path, args, kwargs = super(CountryField, self).deconstruct() kwargs.pop("choices") if self.multiple: # multiple determines the length of the field kwargs["multiple"] = self.multiple if self.countries is not countries: # Include the countries class if it's not the default countries # instance. kwargs["countries"] = self.countries.__class__ return name, path, args, kwargs def get_choices(self, include_blank=True, blank_choice=None, *args, **kwargs): if blank_choice is None: if self.blank_label is None: blank_choice = BLANK_CHOICE_DASH else: blank_choice = [("", self.blank_label)] if self.multiple: include_blank = False return super(CountryField, self).get_choices( include_blank=include_blank, blank_choice=blank_choice, *args, **kwargs ) get_choices = lazy(get_choices, list) def formfield(self, **kwargs): kwargs.setdefault( "choices_form_class", LazyTypedMultipleChoiceField if self.multiple else LazyTypedChoiceField, ) if "coerce" not in kwargs: kwargs["coerce"] = super(CountryField, self).to_python field = super(CharField, self).formfield(**kwargs) return field def to_python(self, value): if not self.multiple: return super(CountryField, self).to_python(value) if not value: return value if isinstance(value, basestring): value = value.split(",") output = [] for item in value: output.append(super(CountryField, self).to_python(item)) return output def validate(self, value, model_instance): """ Use custom validation for when using a multiple countries field. """ if not self.multiple: return super(CountryField, self).validate(value, model_instance) if not self.editable: # Skip validation for non-editable fields. return if value: choices = [option_key for option_key, option_value in self.choices] for single_value in value: if single_value not in choices: raise exceptions.ValidationError( self.error_messages["invalid_choice"], code="invalid_choice", params={"value": single_value}, ) if not self.blank and value in self.empty_values: raise exceptions.ValidationError(self.error_messages["blank"], code="blank")
haifengat/hf_ctp_py_proxy
generate/generate_enum_cs.py
Generate.process_line
python
def process_line(self, idx, line): if '///' in line: # 注释 py_line = '#' + line[3:] # /// [T去掉ftdc前的内容,方便后面比对]FtdcInvestorRangeType是一个投资者范围类型 ==> # /// <summary> # /// 投资者范围类型 # /// </summary>""" if py_line.find('是一个') > 0: self.enum_comment[py_line[py_line.find('Ftdc'):py_line.find('是一个')]] = '/// <summary>\n/// %s\n///</summary>' % py_line[py_line.find('是一个') + 3:-1] else: self.tmp_comment = '/// <summary>\n\t/// {0}\n\t///</summary>\n\t'.format(line[3:-1]) # -1去掉尾换行 elif '#define' in line: # 定义常量 # define THOST_FTDC_IR_All '1' ==> defineDict["THOST_FTDC_IR_All"] = '1' content = line.split(' ') constant = content[1] if len(content) > 2: value = content[-1][:-1] # value带行尾的\n py_line = 'defineDict["%s"] = %s\n' % (constant, value) else: py_line = '' # enum relate define if py_line: # 命名保持一致,不再精简 if len(value) > 3: # 处理理'x' x长度>1的情况,如102001 self.define.append("{2}{0} = {1},".format(constant, value[1:-1], self.tmp_comment)) else: self.define.append("{2}{0} = (byte){1},".format(constant, value, self.tmp_comment)) elif 'typedef' in line: # 类型申明 # typedef char TThostFtdcInvestorRangeType; ==> typedefDict["TThostFtdcInvestorRangeType"] = "c_char" py_line = self.process_typedef(line) # public enum TThostFtdcInvestorRangeType : byte # { # /// <summary> # ///所有 # /// </summary> # THOST_FTDC_IR_All = (byte)'1', # /// <summary> # ///投资者组 # /// </summary> # THOST_FTDC_IR_Group = (byte)'2', # /// <summary> # ///单一投资者 # /// </summary> # THOST_FTDC_IR_Single = (byte)'3' # } if line.find(' char ') > 0 and line.find('[') < 0: key = line.split(' ')[2][6:-2] # TThostFtdcInvestorRangeType=>FtdcInvestorRangeType(去掉首个T) enum_line = self.enum_comment[key] enum_line += '\npublic enum TThost%s : byte\n{\n' % key for l in self.define: enum_line += '\t%s\n' % l enum_line += '}\n\n' # 处理形如 102001此类值 if enum_line.find("(byte)") < 0: enum_line = enum_line.replace(': byte', ': int') self.fenum.write(enum_line) self.define.clear() elif line == '\n': # 空行 py_line = line else: py_line = '' return py_line
处理每行
train
https://github.com/haifengat/hf_ctp_py_proxy/blob/c2dc6dbde45aa6b097f75380474e91510d3f5d12/generate/generate_enum_cs.py#L56-L125
[ "def process_typedef(self, line):\n \"\"\"处理类型申明\"\"\"\n content = line.split(' ')\n type_ = self.type_dict[content[1]]\n\n if type_ == 'c_char' and '[' in line:\n # type_ = 'string'\n type_ = '%s*%s' % (type_, line[line.index('[') + 1:line.index(']')])\n\n keyword = content[2]\n if '[' in keyword:\n i = keyword.index('[')\n keyword = keyword[:i]\n else:\n keyword = keyword.replace(';\\n', '') # 删除行末分号\n\n py_line = 'typedefDict[\"%s\"] = \"%s\"\\n' % (keyword, type_)\n\n return py_line\n" ]
class Generate(): def __init__(self, dir, out_path): self.ctp_dir = dir # C++和python类型的映射字典 self.type_dict = {'int': 'c_int32', 'char': 'c_char', 'double': 'c_double', 'short': 'c_short', 'string': 'c_char_p'} self.define = [] self.fenum = open(os.path.join(out_path, 'ctp_enum.cs'), 'w', encoding='utf-8') # 增加utf-8解决乱码问题 self.f_data_type = open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'ctp_data_type.py'), 'w', encoding='utf-8') # 增加utf-8解决乱码问题 self.enum_comment = {} self.tmp_comment = '' self.fenum.write(""" public enum THOST_TE_RESUME_TYPE { THOST_TERT_RESTART = 0, THOST_TERT_RESUME, THOST_TERT_QUICK } """) self.f_data_type.write("""#!/usr/bin/env python # coding:utf-8 \"\"\" Author: HaiFeng Purpose: Created: 2016/7/5 \"\"\" typedefDict = {} defineDict = {} """) def process_typedef(self, line): """处理类型申明""" content = line.split(' ') type_ = self.type_dict[content[1]] if type_ == 'c_char' and '[' in line: # type_ = 'string' type_ = '%s*%s' % (type_, line[line.index('[') + 1:line.index(']')]) keyword = content[2] if '[' in keyword: i = keyword.index('[') keyword = keyword[:i] else: keyword = keyword.replace(';\n', '') # 删除行末分号 py_line = 'typedefDict["%s"] = "%s"\n' % (keyword, type_) return py_line def run(self): """主函数""" # try: self.fenum.write('\n') self.fcpp = open(os.path.join(os.path.abspath(self.ctp_dir), 'ThostFtdcUserApiDataType.h'), 'r') for idx, line in enumerate(self.fcpp): l = self.process_line(idx, line) self.f_data_type.write(l) self.fcpp.close() self.f_data_type.close() self.fenum.close() print('ctp_data_type.py生成过程完成')
haifengat/hf_ctp_py_proxy
generate/generate_enum_cs.py
Generate.process_typedef
python
def process_typedef(self, line): content = line.split(' ') type_ = self.type_dict[content[1]] if type_ == 'c_char' and '[' in line: # type_ = 'string' type_ = '%s*%s' % (type_, line[line.index('[') + 1:line.index(']')]) keyword = content[2] if '[' in keyword: i = keyword.index('[') keyword = keyword[:i] else: keyword = keyword.replace(';\n', '') # 删除行末分号 py_line = 'typedefDict["%s"] = "%s"\n' % (keyword, type_) return py_line
处理类型申明
train
https://github.com/haifengat/hf_ctp_py_proxy/blob/c2dc6dbde45aa6b097f75380474e91510d3f5d12/generate/generate_enum_cs.py#L127-L145
null
class Generate(): def __init__(self, dir, out_path): self.ctp_dir = dir # C++和python类型的映射字典 self.type_dict = {'int': 'c_int32', 'char': 'c_char', 'double': 'c_double', 'short': 'c_short', 'string': 'c_char_p'} self.define = [] self.fenum = open(os.path.join(out_path, 'ctp_enum.cs'), 'w', encoding='utf-8') # 增加utf-8解决乱码问题 self.f_data_type = open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'ctp_data_type.py'), 'w', encoding='utf-8') # 增加utf-8解决乱码问题 self.enum_comment = {} self.tmp_comment = '' self.fenum.write(""" public enum THOST_TE_RESUME_TYPE { THOST_TERT_RESTART = 0, THOST_TERT_RESUME, THOST_TERT_QUICK } """) self.f_data_type.write("""#!/usr/bin/env python # coding:utf-8 \"\"\" Author: HaiFeng Purpose: Created: 2016/7/5 \"\"\" typedefDict = {} defineDict = {} """) def process_line(self, idx, line): """处理每行""" if '///' in line: # 注释 py_line = '#' + line[3:] # /// [T去掉ftdc前的内容,方便后面比对]FtdcInvestorRangeType是一个投资者范围类型 ==> # /// <summary> # /// 投资者范围类型 # /// </summary>""" if py_line.find('是一个') > 0: self.enum_comment[py_line[py_line.find('Ftdc'):py_line.find('是一个')]] = '/// <summary>\n/// %s\n///</summary>' % py_line[py_line.find('是一个') + 3:-1] else: self.tmp_comment = '/// <summary>\n\t/// {0}\n\t///</summary>\n\t'.format(line[3:-1]) # -1去掉尾换行 elif '#define' in line: # 定义常量 # define THOST_FTDC_IR_All '1' ==> defineDict["THOST_FTDC_IR_All"] = '1' content = line.split(' ') constant = content[1] if len(content) > 2: value = content[-1][:-1] # value带行尾的\n py_line = 'defineDict["%s"] = %s\n' % (constant, value) else: py_line = '' # enum relate define if py_line: # 命名保持一致,不再精简 if len(value) > 3: # 处理理'x' x长度>1的情况,如102001 self.define.append("{2}{0} = {1},".format(constant, value[1:-1], self.tmp_comment)) else: self.define.append("{2}{0} = (byte){1},".format(constant, value, self.tmp_comment)) elif 'typedef' in line: # 类型申明 # typedef char TThostFtdcInvestorRangeType; ==> typedefDict["TThostFtdcInvestorRangeType"] = "c_char" py_line = self.process_typedef(line) # public enum TThostFtdcInvestorRangeType : byte # { # /// <summary> # ///所有 # /// </summary> # THOST_FTDC_IR_All = (byte)'1', # /// <summary> # ///投资者组 # /// </summary> # THOST_FTDC_IR_Group = (byte)'2', # /// <summary> # ///单一投资者 # /// </summary> # THOST_FTDC_IR_Single = (byte)'3' # } if line.find(' char ') > 0 and line.find('[') < 0: key = line.split(' ')[2][6:-2] # TThostFtdcInvestorRangeType=>FtdcInvestorRangeType(去掉首个T) enum_line = self.enum_comment[key] enum_line += '\npublic enum TThost%s : byte\n{\n' % key for l in self.define: enum_line += '\t%s\n' % l enum_line += '}\n\n' # 处理形如 102001此类值 if enum_line.find("(byte)") < 0: enum_line = enum_line.replace(': byte', ': int') self.fenum.write(enum_line) self.define.clear() elif line == '\n': # 空行 py_line = line else: py_line = '' return py_line def run(self): """主函数""" # try: self.fenum.write('\n') self.fcpp = open(os.path.join(os.path.abspath(self.ctp_dir), 'ThostFtdcUserApiDataType.h'), 'r') for idx, line in enumerate(self.fcpp): l = self.process_line(idx, line) self.f_data_type.write(l) self.fcpp.close() self.f_data_type.close() self.fenum.close() print('ctp_data_type.py生成过程完成')
haifengat/hf_ctp_py_proxy
generate/generate_enum_cs.py
Generate.run
python
def run(self): # try: self.fenum.write('\n') self.fcpp = open(os.path.join(os.path.abspath(self.ctp_dir), 'ThostFtdcUserApiDataType.h'), 'r') for idx, line in enumerate(self.fcpp): l = self.process_line(idx, line) self.f_data_type.write(l) self.fcpp.close() self.f_data_type.close() self.fenum.close() print('ctp_data_type.py生成过程完成')
主函数
train
https://github.com/haifengat/hf_ctp_py_proxy/blob/c2dc6dbde45aa6b097f75380474e91510d3f5d12/generate/generate_enum_cs.py#L147-L161
[ "def process_line(self, idx, line):\n \"\"\"处理每行\"\"\"\n if '///' in line: # 注释\n py_line = '#' + line[3:]\n\n # /// [T去掉ftdc前的内容,方便后面比对]FtdcInvestorRangeType是一个投资者范围类型 ==>\n # /// <summary>\n # /// 投资者范围类型\n # /// </summary>\"\"\"\n if py_line.find('是一个') > 0:\n self.enum_comment[py_line[py_line.find('Ftdc'):py_line.find('是一个')]] = '/// <summary>\\n/// %s\\n///</summary>' % py_line[py_line.find('是一个') + 3:-1]\n else:\n self.tmp_comment = '/// <summary>\\n\\t/// {0}\\n\\t///</summary>\\n\\t'.format(line[3:-1]) # -1去掉尾换行\n\n elif '#define' in line: # 定义常量\n # define THOST_FTDC_IR_All '1' ==> defineDict[\"THOST_FTDC_IR_All\"] = '1'\n content = line.split(' ')\n constant = content[1]\n if len(content) > 2:\n value = content[-1][:-1] # value带行尾的\\n\n py_line = 'defineDict[\"%s\"] = %s\\n' % (constant, value)\n else:\n py_line = ''\n\n # enum relate define\n if py_line: # 命名保持一致,不再精简\n if len(value) > 3: # 处理理'x' x长度>1的情况,如102001\n self.define.append(\"{2}{0} = {1},\".format(constant, value[1:-1], self.tmp_comment))\n else:\n self.define.append(\"{2}{0} = (byte){1},\".format(constant, value, self.tmp_comment))\n\n elif 'typedef' in line: # 类型申明\n # typedef char TThostFtdcInvestorRangeType; ==> typedefDict[\"TThostFtdcInvestorRangeType\"] = \"c_char\"\n py_line = self.process_typedef(line)\n # public enum TThostFtdcInvestorRangeType : byte\n # {\n # \t/// <summary>\n # \t///所有\n # \t/// </summary>\n # \tTHOST_FTDC_IR_All = (byte)'1',\n # \t/// <summary>\n # \t///投资者组\n # \t/// </summary>\n # \tTHOST_FTDC_IR_Group = (byte)'2',\n # \t/// <summary>\n # \t///单一投资者\n # \t/// </summary>\n # \tTHOST_FTDC_IR_Single = (byte)'3'\n # }\n\n if line.find(' char ') > 0 and line.find('[') < 0:\n key = line.split(' ')[2][6:-2] # TThostFtdcInvestorRangeType=>FtdcInvestorRangeType(去掉首个T)\n enum_line = self.enum_comment[key]\n enum_line += '\\npublic enum TThost%s : byte\\n{\\n' % key\n for l in self.define:\n enum_line += '\\t%s\\n' % l\n enum_line += '}\\n\\n'\n # 处理形如 102001此类值\n if enum_line.find(\"(byte)\") < 0:\n enum_line = enum_line.replace(': byte', ': int')\n\n self.fenum.write(enum_line)\n self.define.clear()\n\n elif line == '\\n': # 空行\n py_line = line\n else:\n py_line = ''\n\n return py_line\n" ]
class Generate(): def __init__(self, dir, out_path): self.ctp_dir = dir # C++和python类型的映射字典 self.type_dict = {'int': 'c_int32', 'char': 'c_char', 'double': 'c_double', 'short': 'c_short', 'string': 'c_char_p'} self.define = [] self.fenum = open(os.path.join(out_path, 'ctp_enum.cs'), 'w', encoding='utf-8') # 增加utf-8解决乱码问题 self.f_data_type = open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'ctp_data_type.py'), 'w', encoding='utf-8') # 增加utf-8解决乱码问题 self.enum_comment = {} self.tmp_comment = '' self.fenum.write(""" public enum THOST_TE_RESUME_TYPE { THOST_TERT_RESTART = 0, THOST_TERT_RESUME, THOST_TERT_QUICK } """) self.f_data_type.write("""#!/usr/bin/env python # coding:utf-8 \"\"\" Author: HaiFeng Purpose: Created: 2016/7/5 \"\"\" typedefDict = {} defineDict = {} """) def process_line(self, idx, line): """处理每行""" if '///' in line: # 注释 py_line = '#' + line[3:] # /// [T去掉ftdc前的内容,方便后面比对]FtdcInvestorRangeType是一个投资者范围类型 ==> # /// <summary> # /// 投资者范围类型 # /// </summary>""" if py_line.find('是一个') > 0: self.enum_comment[py_line[py_line.find('Ftdc'):py_line.find('是一个')]] = '/// <summary>\n/// %s\n///</summary>' % py_line[py_line.find('是一个') + 3:-1] else: self.tmp_comment = '/// <summary>\n\t/// {0}\n\t///</summary>\n\t'.format(line[3:-1]) # -1去掉尾换行 elif '#define' in line: # 定义常量 # define THOST_FTDC_IR_All '1' ==> defineDict["THOST_FTDC_IR_All"] = '1' content = line.split(' ') constant = content[1] if len(content) > 2: value = content[-1][:-1] # value带行尾的\n py_line = 'defineDict["%s"] = %s\n' % (constant, value) else: py_line = '' # enum relate define if py_line: # 命名保持一致,不再精简 if len(value) > 3: # 处理理'x' x长度>1的情况,如102001 self.define.append("{2}{0} = {1},".format(constant, value[1:-1], self.tmp_comment)) else: self.define.append("{2}{0} = (byte){1},".format(constant, value, self.tmp_comment)) elif 'typedef' in line: # 类型申明 # typedef char TThostFtdcInvestorRangeType; ==> typedefDict["TThostFtdcInvestorRangeType"] = "c_char" py_line = self.process_typedef(line) # public enum TThostFtdcInvestorRangeType : byte # { # /// <summary> # ///所有 # /// </summary> # THOST_FTDC_IR_All = (byte)'1', # /// <summary> # ///投资者组 # /// </summary> # THOST_FTDC_IR_Group = (byte)'2', # /// <summary> # ///单一投资者 # /// </summary> # THOST_FTDC_IR_Single = (byte)'3' # } if line.find(' char ') > 0 and line.find('[') < 0: key = line.split(' ')[2][6:-2] # TThostFtdcInvestorRangeType=>FtdcInvestorRangeType(去掉首个T) enum_line = self.enum_comment[key] enum_line += '\npublic enum TThost%s : byte\n{\n' % key for l in self.define: enum_line += '\t%s\n' % l enum_line += '}\n\n' # 处理形如 102001此类值 if enum_line.find("(byte)") < 0: enum_line = enum_line.replace(': byte', ': int') self.fenum.write(enum_line) self.define.clear() elif line == '\n': # 空行 py_line = line else: py_line = '' return py_line def process_typedef(self, line): """处理类型申明""" content = line.split(' ') type_ = self.type_dict[content[1]] if type_ == 'c_char' and '[' in line: # type_ = 'string' type_ = '%s*%s' % (type_, line[line.index('[') + 1:line.index(']')]) keyword = content[2] if '[' in keyword: i = keyword.index('[') keyword = keyword[:i] else: keyword = keyword.replace(';\n', '') # 删除行末分号 py_line = 'typedefDict["%s"] = "%s"\n' % (keyword, type_) return py_line
haifengat/hf_ctp_py_proxy
generate/generate_struct_cs.py
Generate.run
python
def run(self): fcpp = open(os.path.join(os.path.abspath(self.ctp_dir), 'ThostFtdcUserApiStruct.h'), 'r') fpy = open(os.path.join(self.out_path, 'ctp_struct.cs'), 'w', encoding='utf-8') fpy.write('\n') fpy.write('using System.Runtime.InteropServices;\n') fpy.write('\n') py_str = '' py_str_idx = 0 py_str_format = '' for no, line in enumerate(fcpp): # 结构体申明注释 if '///' in line and '\t' not in line: remark = line[3:-1] continue # 结构体变量注释 elif '\t///' in line: remark = line[4:-1] continue # 结构体申明 elif 'struct ' in line: content = line.split(' ') name = content[1].replace('\n', '') # struct begin py_line = """ /// <summary> /// {1} /// </summary> [StructLayout(LayoutKind.Sequential)] public struct {0} {{""".format(name, remark) # 结构体变量 elif '\t' in line and '///' not in line: content = line.split('\t') if line.find('short') >= 0: content = content typedef = content[1] type_ = typedefDict[typedef] variable = content[2].replace(';\n', "") # fields py_line = """ /// <summary> /// {0} /// </summary>""".format(remark) if type_ == 'c_int32': py_line += '\n\tpublic int {0};'.format(variable) elif type_ == 'c_double': py_line += '\n\tpublic double {0};'.format(variable) elif type_.find('short') >= 0: py_line += '\n\tpublic short {0};'.format(variable) elif type_.find('c_char*') >= 0: py_line += """ [MarshalAs(UnmanagedType.ByValTStr, SizeConst={1})] public string {0};""".format(variable, type_.split('*')[1]) elif type_.find('c_char') >= 0: py_line += '\n\tpublic {0} {1};'.format(typedef, variable) else: py_str_format += "self.{0}, ".format(variable) py_str += "{0}={{{1}}}, ".format(variable, py_str_idx) py_str_idx += 1 # py_str += '{0}={{self.{0}}}, '.format(variable) # 结构体结束 elif '}' in line: # struct end py_line = '\n}\n\n' # 结构体开始 elif '{' in line: py_line = '' py_str = '' py_str_idx = 0 py_str_format = '' # 其他 else: py_line = '\n' continue fpy.write(py_line)
主函数
train
https://github.com/haifengat/hf_ctp_py_proxy/blob/c2dc6dbde45aa6b097f75380474e91510d3f5d12/generate/generate_struct_cs.py#L47-L135
null
class Generate: def __init__(self, dir, out_path): self.ctp_dir = dir self.out_path = out_path
haifengat/hf_ctp_py_proxy
py_ctp/trade.py
CtpTrade._qry
python
def _qry(self): # restart 模式, 待rtnorder 处理完毕后再进行查询,否则会造成position混乱 ord_cnt = 0 trd_cnt = 0 while True: time.sleep(0.5) if len(self.orders) == ord_cnt and len(self.trades) == trd_cnt: break ord_cnt = len(self.orders) trd_cnt = len(self.trades) self.t.ReqQryInstrument() time.sleep(1.1) self.t.ReqQryInvestorPosition(self.broker, self.investor) time.sleep(1.1) self.t.ReqQryTradingAccount(self.broker, self.investor) time.sleep(1.1) self.logined = True info = InfoField() info.ErrorID = 0 info.ErrorMsg = '正确' threading.Thread(target=self.OnUserLogin, args=(self, info)).start() # 调用Release后程序异常退出,但不报错误:接口断开了仍然调用了查询指令 while self.logined: """查询持仓与权益""" self.t.ReqQryInvestorPosition(self.broker, self.investor) time.sleep(1.1) if not self.logined: return self.t.ReqQryTradingAccount(self.broker, self.investor) time.sleep(1.1)
查询帐号相关信息
train
https://github.com/haifengat/hf_ctp_py_proxy/blob/c2dc6dbde45aa6b097f75380474e91510d3f5d12/py_ctp/trade.py#L103-L134
null
class CtpTrade(): """""" def __init__(self): self.front_address = '' self.investor = '' self.password = '' self.broker = '' self.logined = False self.tradingday = '' self.instruments = {} self.orders = {} self.trades = {} self.account: TradingAccount = None self.positions = {} self.instrument_status = {} self._req = 0 self._session = '' self._orderid_sysid = {} self._posi = [] self.t = Trade() def _OnFrontConnected(self): threading.Thread(target=self.OnConnected, args=(self,)).start() def _OnFrontDisconnected(self, nReason): self.logined = False print(nReason) # 下午收盘后会不停断开再连接 4097错误 if nReason == 4097 or nReason == 4098: threading.Thread(target=self._reconnect).start() else: threading.Thread(target=self.OnDisConnected, args=(self, nReason)).start() def _reconnect(self): if sum([1 if stat == 'Continous' else 0 for exc, stat in self.instrument_status.items()]) == 0: print(time.strftime('%Y%m%d %H:%M:%S', time.localtime())) self.t.Release() time.sleep(600) self.ReqConnect(self.front_address) # def _OnRspUserLogout(self, pUserLogout: CThostFtdcUserLogoutField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): # pass def _OnRspUserLogin(self, pRspUserLogin: CThostFtdcRspUserLoginField(), pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" if pRspInfo.getErrorID() == 0: self.session = pRspUserLogin.getSessionID() self.tradingday = pRspUserLogin.getTradingDay() self.t.ReqSettlementInfoConfirm(self.broker, self.investor) elif self.logined: threading.Thread(target=self._relogin).start() else: info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() threading.Thread(target=self.OnUserLogin, args=(self, info)).start() def _relogin(self): # 隔夜重连=>处理'初始化'错误 time.sleep(60 * 10) self.t.ReqUserLogin( BrokerID=self.broker, UserID=self.investor, Password=self.password, UserProductInfo='@haifeng') def _OnRspSettlementInfoConfirm( self, pSettlementInfoConfirm: CThostFtdcSettlementInfoConfirmField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): if not self.logined: time.sleep(0.5) """查询合约/持仓/权益""" threading.Thread(target=self._qry).start() # 开启查询 def _OnRtnInstrumentStatus(self, pInstrumentStatus: CThostFtdcInstrumentStatusField): if pInstrumentStatus.getInstrumentID() == '': return status = InstrumentStatus.Continous if pInstrumentStatus.getInstrumentStatus() == TThostFtdcInstrumentStatusType.THOST_FTDC_IS_Continous: status = InstrumentStatus.Continous elif pInstrumentStatus.getInstrumentStatus() == TThostFtdcInstrumentStatusType.THOST_FTDC_IS_Closed: status = InstrumentStatus.Closed elif str(pInstrumentStatus.getInstrumentStatus()).startswith('Auction'): status = InstrumentStatus.Auction else: status = InstrumentStatus.NoTrading self.instrument_status[pInstrumentStatus.getInstrumentID()] = status self.OnInstrumentStatus(self, pInstrumentStatus.getInstrumentID(), status) def _OnRspQryInstrument(self, pInstrument: CThostFtdcInstrumentField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" inst = InstrumentField() inst.InstrumentID = pInstrument.getInstrumentID() inst.ProductID = pInstrument.getProductID() inst.ExchangeID = pInstrument.getExchangeID() inst.VolumeMultiple = pInstrument.getVolumeMultiple() inst.PriceTick = pInstrument.getPriceTick() inst.MaxOrderVolume = pInstrument.getMaxLimitOrderVolume() inst.ProductType = pInstrument.getProductClass().name # ProductClassType.Futures -> Futures self.instruments[inst.InstrumentID] = inst def _OnRspQryPosition(self, pInvestorPosition: CThostFtdcInvestorPositionField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" if pInvestorPosition.getInstrumentID() != '': # 偶尔出现NULL的数据导致数据转换错误 self._posi.append(pInvestorPosition) # Struct(**f.__dict__)) #dict -> object if bIsLast: # 先排序再group才有效 self._posi = sorted(self._posi, key=lambda c: '{0}_{1}'.format(c.getInstrumentID(), DirectType.Buy if c.getPosiDirection() == TThostFtdcPosiDirectionType.THOST_FTDC_PD_Long else DirectType.Sell)) # direction需从posidiction转换为dictiontype for key, group in itertools.groupby(self._posi, lambda c: '{0}_{1}'.format(c.getInstrumentID(), 'Buy' if c.getPosiDirection() == TThostFtdcPosiDirectionType.THOST_FTDC_PD_Long else 'Sell')): pf = self.positions.get(key) if not pf: pf = PositionField() self.positions[key] = pf pf.Position = 0 pf.TdPosition = 0 pf.YdPosition = 0 pf.CloseProfit = 0 pf.PositionProfit = 0 pf.Commission = 0 pf.Margin = 0 pf.Price = 0 cost = 0.0 for g in group: if not pf.InstrumentID: pf.InstrumentID = g.getInstrumentID() pf.Direction = DirectType.Buy if g.getPosiDirection() == TThostFtdcPosiDirectionType.THOST_FTDC_PD_Long else DirectType.Sell pf.Position += g.getPosition() pf.TdPosition += g.getTodayPosition() pf.YdPosition = pf.Position - pf.TdPosition pf.CloseProfit += g.getCloseProfit() pf.PositionProfit += g.getPositionProfit() pf.Commission += g.getCommission() pf.Margin += g.getUseMargin() cost += g.OpenCost # pf.Position <= 0 ? 0 : (g.Sum(n => n.PositionCost) / DicInstrumentField[pf.InstrumentID].VolumeMultiple / pf.Position); vm = self.instruments[pf.InstrumentID].VolumeMultiple pf.Price = 0 if pf.Position <= 0 else cost / vm / pf.Position self._posi.clear() def _OnRspQryPositionDetail(self, pInvestorPositionDetail: CThostFtdcInvestorPositionDetailField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """持仓明细""" if pInvestorPositionDetail.getInstrumentID() == '': return detail = PositionDetail() detail.Instrument = pInvestorPositionDetail.getInstrumentID() detail.CloseProfit = pInvestorPositionDetail.getCloseProfitByTrade() detail.Direction = DirectType.Buy if pInvestorPositionDetail.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell detail.HedgeFlag = HedgeType(list(TThostFtdcHedgeFlagType).index(pInvestorPositionDetail.getHedgeFlag())) detail.OpenDate = pInvestorPositionDetail.getOpenDate() detail.PositionProfit = pInvestorPositionDetail.getPositionProfitByTrade() detail.OpenPrice = pInvestorPositionDetail.getOpenPrice() detail.TradeType = TradeTypeType(list(TThostFtdcTradeTypeType).index(pInvestorPositionDetail.getTradeType())) detail.Volume = pInvestorPositionDetail.getVolume() self.position_details[pInvestorPositionDetail.getTradeID()] = detail def _OnRspQryAccount(self, pTradingAccount: CThostFtdcTradingAccountField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" if not self.account: self.account = TradingAccount() self.account.Available = pTradingAccount.getAvailable() self.account.CloseProfit = pTradingAccount.getCloseProfit() self.account.Commission = pTradingAccount.getCommission() self.account.CurrMargin = pTradingAccount.getCurrMargin() self.account.FrozenCash = pTradingAccount.getFrozenCash() self.account.PositionProfit = pTradingAccount.getPositionProfit() self.account.PreBalance = pTradingAccount.getPreBalance() + pTradingAccount.getDeposit() + pTradingAccount.getWithdraw() self.account.Fund = self.account.PreBalance + pTradingAccount.getCloseProfit() + pTradingAccount.getPositionProfit() - pTradingAccount.getCommission() self.account.Risk = 0 if self.account.Fund == 0 else self.account.CurrMargin / self.account.Fund def _OnRtnOrder(self, pOrder: CThostFtdcOrderField): """""" id = '{0}|{1}|{2}'.format(pOrder.getSessionID(), pOrder.getFrontID(), pOrder.getOrderRef()) of = self.orders.get(id) if not of: of = OrderField() if pOrder.getOrderRef().isdigit(): of.Custom = int(pOrder.getOrderRef()) % 1000000 of.InstrumentID = pOrder.getInstrumentID() of.InsertTime = pOrder.getInsertTime() of.Direction = DirectType.Buy if pOrder.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell ot = TThostFtdcOffsetFlagType(ord(pOrder.getCombOffsetFlag()[0])) of.Offset = OffsetType.Open if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open else OffsetType.CloseToday if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_CloseToday else OffsetType.Close of.Status = OrderStatus.Normal of.StatusMsg = pOrder.getStatusMsg() of.IsLocal = pOrder.getSessionID() == self.session of.LimitPrice = pOrder.getLimitPrice() of.OrderID = id of.Volume = pOrder.getVolumeTotalOriginal() of.VolumeLeft = of.Volume self.orders[id] = of threading.Thread(target=self.OnOrder, args=(self, of)).start() elif pOrder.getOrderStatus() == TThostFtdcOrderStatusType.THOST_FTDC_OST_Canceled: of.Status = OrderStatus.Canceled of.StatusMsg = pOrder.getStatusMsg() if of.StatusMsg.find('被拒绝') >= 0: info = InfoField() info.ErrorID = -1 info.ErrorMsg = of.StatusMsg threading.Thread(target=self.OnErrOrder, args=(self, of, info)).start() else: threading.Thread(target=self.OnCancel, args=(self, of)).start() else: if pOrder.getOrderSysID(): of.SysID = pOrder.getOrderSysID() self._orderid_sysid[pOrder.getOrderSysID()] = id # 记录sysid与orderid关联,方便Trade时查找处理 def _OnRtnTrade(self, f): """""" tf = TradeField() tf.Direction = DirectType.Buy if f.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell tf.ExchangeID = f.getExchangeID() tf.InstrumentID = f.getInstrumentID() tf.Offset = OffsetType.Open if f.getOffsetFlag() == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open else OffsetType.Close if f.getOffsetFlag() == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Close else OffsetType.CloseToday tf.Price = f.getPrice() tf.SysID = f.getOrderSysID() tf.TradeID = f.getTradeID() tf.TradeTime = f.getTradeTime() tf.TradingDay = f.getTradingDay() tf.Volume = f.getVolume() self.trades[tf.TradeID] = tf id = self._orderid_sysid[tf.SysID] of = self.orders[id] tf.OrderID = id # tradeid 与 orderid 关联 of.TradeTime = tf.TradeTime of.AvgPrice = (of.AvgPrice * (of.Volume - of.VolumeLeft) + tf.Price * tf.Volume) / (of.Volume - of.VolumeLeft + tf.Volume) of.TradeVolume = tf.Volume of.VolumeLeft -= tf.Volume if of.VolumeLeft == 0: of.Status = OrderStatus.Filled of.StatusMsg = '全部成交' else: of.Status = OrderStatus.Partial of.StatusMsg = '部分成交' # 更新持仓 ***** if tf.Offset == OffsetType.Open: key = '{0}_{1}'.format(tf.InstrumentID, 'Buy' if tf.Direction == DirectType.Buy else 'Sell') pf = self.positions.get(key) if not pf: pf = PositionField() self.positions[key] = pf pf.InstrumentID = tf.InstrumentID pf.Direction = tf.Direction pf.Price = (pf.Price * pf.Position + tf.Price * tf.Volume) / (pf.Position + tf.Volume) pf.TdPosition += tf.Volume pf.Position += tf.Volume else: key = '{0}_{1}'.format(tf.InstrumentID, DirectType.Sell if tf.Direction == DirectType.Buy else DirectType.Buy) pf = self.positions.get(key) if pf: # 有可能出现无持仓的情况 if tf.Offset == OffsetType.CloseToday: pf.TdPosition -= tf.Volume else: tdclose = min(pf.TdPosition, tf.Volume) if pf.TdPosition > 0: pf.TdPosition -= tdclose pf.YdPosition -= max(0, tf.Volume - tdclose) pf.Position -= tf.Volume threading.Thread(target=self._onRtn, args=(of, tf)).start() def _onRtn(self, of, tf): self.OnOrder(self, of) self.OnTrade(self, tf) def _OnRspOrder(self, pInputOrder: CThostFtdcInputOrderField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() id = '{0}|{1}|{2}'.format(self.session, '0', pInputOrder.getOrderRef()) of = self.orders.get(id) if not of: of = OrderField() l = int(pInputOrder.getOrderRef()) of.Custom = l % 1000000 of.InstrumentID = pInputOrder.getInstrumentID() of.InsertTime = time.strftime('%H:%M:%S', time.localtime()) # 对direction需特别处理(具体见ctp_struct) of.Direction = DirectType.Buy if pInputOrder.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell ot = TThostFtdcOffsetFlagType(ord(pInputOrder.getCombOffsetFlag()[0])) of.Offset = OffsetType.Open if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open else OffsetType.CloseToday if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_CloseToday else OffsetType.Close # of.Status = OrderStatus.Normal # of.StatusMsg = f.getStatusMsg() of.IsLocal = True of.LimitPrice = pInputOrder.getLimitPrice() of.OrderID = id of.Volume = pInputOrder.getVolumeTotalOriginal() of.VolumeLeft = of.Volume self.orders[id] = of of.Status = OrderStatus.Error of.StatusMsg = '{0}:{1}'.format(info.ErrorID, info.ErrorMsg) threading.Thread(target=self.OnErrOrder, args=(self, of, info)).start() def _OnErrOrder(self, pInputOrder: CThostFtdcInputOrderField, pRspInfo: CThostFtdcRspInfoField): """""" id = '{0}|{1}|{2}'.format(self.session, '0', pInputOrder.getOrderRef()) of = self.orders.get(id) info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() if of and of.IsLocal: of.Status = OrderStatus.Error of.StatusMsg = '{0}:{1}'.format(pRspInfo.getErrorID(), pRspInfo.getErrorMsg()) threading.Thread(target=self.OnErrOrder, args=(self, of, info)).start() def _OnRspOrderAction(self, pInputOrderAction: CThostFtdcInputOrderActionField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): id = "{0}|{1}|{2}".format(pInputOrderAction.getSessionID(), pInputOrderAction.getFrontID(), pInputOrderAction.getOrderRef()) if self.logined and id in self.orders: info = InfoField() info.ErrorID = pRspInfo.ErrorID info.ErrorMsg = pRspInfo.ErrorMsg threading.Thread(target=self.OnErrCancel, args=(self, self.orders[id], info)).start() def _OnRtnNotice(self, pTradingNoticeInfo: CThostFtdcTradingNoticeInfoField): '''交易提醒''' msg = pTradingNoticeInfo.getFieldContent() if len(msg) > 0: threading.Thread(target=self.OnRtnNotice, args=(self, pTradingNoticeInfo.getSendTime(), msg)).start() def _OnRtnQuote(self, pQuote: CThostFtdcQuoteField): threading.Thread(target=self.OnRtnQuote, args=(self, pQuote)).start() def _OnErrRtnQuote(self, pInputQuote: CThostFtdcInputQuoteField, pRspInfo: CThostFtdcRspInfoField): info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() threading.Thread(target=self.OnErrRtnQuote, args=(self, pInputQuote, info)).start() def _OnErrForQuoteInsert(self, pInputForQuote: CThostFtdcInputForQuoteField, pRspInfo: CThostFtdcRspInfoField): info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() threading.Thread(target=self.OnErrRtnForQuoteInsert, args=(self, pInputForQuote, info)).start() def ReqConnect(self, front: str): """连接交易前置 :param front: """ self.t.CreateApi() spi = self.t.CreateSpi() self.t.RegisterSpi(spi) self.t.OnFrontConnected = self._OnFrontConnected self.t.OnRspUserLogin = self._OnRspUserLogin self.t.OnFrontDisconnected = self._OnFrontDisconnected # self.t.OnRspUserLogout = self._OnRspUserLogout self.t.OnRspSettlementInfoConfirm = self._OnRspSettlementInfoConfirm self.t.OnRtnOrder = self._OnRtnOrder self.t.OnRtnTrade = self._OnRtnTrade self.t.OnRspOrderInsert = self._OnRspOrder self.t.OnErrRtnOrderInsert = self._OnErrOrder self.t.OnRspOrderAction = self._OnRspOrderAction self.t.OnRtnInstrumentStatus = self._OnRtnInstrumentStatus self.t.OnRspQryInstrument = self._OnRspQryInstrument self.t.OnRspQryTradingAccount = self._OnRspQryAccount self.t.OnRspQryInvestorPosition = self._OnRspQryPosition self.t.OnRspQryInvestorPositionDetail = self._OnRspQryPositionDetail self.t.OnRtnTradingNotice = self._OnRtnNotice self.t.OnRtnQuote = self._OnRtnQuote self.t.OnErrRtnQuoteInsert = self._OnErrRtnQuote self.t.OnErrRtnForQuoteInsert = self._OnErrForQuoteInsert self.front_address = front self.t.RegCB() self.t.RegisterFront(front) self.t.SubscribePrivateTopic(0) # restart 同步处理order trade self.t.SubscribePublicTopic(0) self.t.Init() # self.t.Join() def ReqUserLogin(self, user: str, pwd: str, broker: str): """登录 :param user: :param pwd: :param broker: """ self.broker = broker self.investor = user self.password = pwd self.t.ReqUserLogin(BrokerID=broker, UserID=user, Password=pwd) def ReqOrderInsert(self, pInstrument: str, pDirection: DirectType, pOffset: OffsetType, pPrice: float = 0.0, pVolume: int = 1, pType: OrderType = OrderType.Limit, pCustom: int = 0): """委托 :param pInstrument: :param pDirection: :param pOffset: :param pPrice: :param pVolume: :param pType: :param pCustom: :return: """ OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_AnyPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = 0.0 VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV if pType == OrderType.Market: # 市价 OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_AnyPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = 0.0 VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV elif pType == OrderType.Limit: # 限价 OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LimitPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_GFD LimitPrice = pPrice VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV elif pType == OrderType.FAK: # FAK OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LimitPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = pPrice VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV elif pType == OrderType.FOK: # FOK OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LimitPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = pPrice VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_CV # 全部数量 self._req += 1 self.t.ReqOrderInsert( BrokerID=self.broker, InvestorID=self.investor, InstrumentID=pInstrument, OrderRef="%06d%06d" % (self._req, pCustom % 1000000), UserID=self.investor, # 此处ctp_enum与at_struct名称冲突 Direction=TThostFtdcDirectionType.THOST_FTDC_D_Buy if pDirection == DirectType.Buy else TThostFtdcDirectionType.THOST_FTDC_D_Sell, CombOffsetFlag=chr(TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open.value if pOffset == OffsetType.Open else TThostFtdcOffsetFlagType.THOST_FTDC_OF_CloseToday.value if pOffset == OffsetType.CloseToday else TThostFtdcOffsetFlagType.THOST_FTDC_OF_Close.value), CombHedgeFlag=chr(TThostFtdcHedgeFlagType.THOST_FTDC_HF_Speculation.value), IsAutoSuspend=0, ForceCloseReason=TThostFtdcForceCloseReasonType.THOST_FTDC_FCC_NotForceClose, IsSwapOrder=0, ContingentCondition=TThostFtdcContingentConditionType.THOST_FTDC_CC_Immediately, VolumeCondition=VolumeCondition, MinVolume=1, VolumeTotalOriginal=pVolume, OrderPriceType=OrderPriceType, TimeCondition=TimeCondition, LimitPrice=LimitPrice, ) def ReqOrderAction(self, OrderID: str): """撤单 :param OrderID: """ of = self.orders[OrderID] if not of: return -1 else: pOrderId = of.OrderID return self.t.ReqOrderAction( self.broker, self.investor, OrderRef=pOrderId.split('|')[2], FrontID=int(pOrderId.split('|')[1]), SessionID=int(pOrderId.split('|')[0]), InstrumentID=of.InstrumentID, ActionFlag=TThostFtdcActionFlagType.THOST_FTDC_AF_Delete) def ReqUserLogout(self): """退出接口""" self.logined = False time.sleep(3) self.t.ReqUserLogout(BrokerID=self.broker, UserID=self.investor) self.t.RegisterSpi(None) self.t.Release() threading.Thread(target=self.OnDisConnected, args=(self, 0)).start() def OnConnected(self, obj): """接口连接 :param obj: """ print('=== [TRADE] OnConnected ==='.format('')) def OnDisConnected(self, obj, reason: int): """接口断开 :param obj: :param reason: """ print('=== [TRADE] OnDisConnected === \nreason: {0}'.format(reason)) def OnUserLogin(self, obj, info: InfoField): """登录响应 :param obj: :param info: """ print('=== [TRADE] OnUserLogin === \n{0}'.format(info)) def OnOrder(self, obj, f: OrderField): """委托响应 :param obj: :param f: """ print('=== [TRADE] OnOrder === \n{0}'.format(f.__dict__)) def OnTrade(self, obj, f: TradeField): """成交响应 :param obj: :param f: """ print('=== [TRADE] OnTrade === \n{0}'.format(f.__dict__)) def OnCancel(self, obj, f: OrderField): """ 撤单响应 :param self: :param obj: :param f:OrderField: """ print('=== [TRADE] OnCancel === \n{0}'.format(f.__dict__)) def OnErrCancel(self, obj, f: OrderField, info: InfoField): """ 撤单失败 :param self: :param obj: :param f:OrderField: :param info:InfoField: """ print('=== [TRADE] OnErrCancel ===\n{0}'.format(f.__dict__)) print(info) def OnErrOrder(self, obj, f: OrderField, info: InfoField): """ 委托错误 :param self: :param obj: :param f:OrderField: :param info:InfoField: """ print('=== [TRADE] OnErrOrder ===\n{0}'.format(f.__dict__)) print(info) def OnInstrumentStatus(self, obj, inst: str, status: InstrumentStatus): """ 交易状态 :param self: :param obj: :param inst:str: :param status:InstrumentStatus: """ print('{}:{}'.format(inst, str(status).strip().split('.')[-1])) def OnRtnNotice(self, obj, time: str, msg: str): """交易提醒 :param obj: :param time: :param msg: :return: """ print(f'=== OnRtnNotice===\n {time}:{msg}') def OnRtnQuote(self, obj, quote: CThostFtdcQuoteField): """报价通知 :param obj: :param quote: :return: """ print('=== [TRADE] OnRtnQuote ===\n{0}'.format(quote.__dict__)) def OnErrRtnQuote(self, obj, quote: CThostFtdcInputQuoteField, info: InfoField): """ :param obj: :param quote: :return: """ print('=== [TRADE] OnErrRtnQuote ===\n{0}'.format(quote.__dict__)) print(info) def OnErrRtnForQuoteInsert(self, obj, quote: CThostFtdcInputQuoteField, info: InfoField): """询价录入错误回报 :param obj: :param quote: :return: """ print('=== [TRADE] OnErrRtnForQuoteInsert ===\n{0}'.format(quote.__dict__)) print(info)
haifengat/hf_ctp_py_proxy
py_ctp/trade.py
CtpTrade._OnRspQryPositionDetail
python
def _OnRspQryPositionDetail(self, pInvestorPositionDetail: CThostFtdcInvestorPositionDetailField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): if pInvestorPositionDetail.getInstrumentID() == '': return detail = PositionDetail() detail.Instrument = pInvestorPositionDetail.getInstrumentID() detail.CloseProfit = pInvestorPositionDetail.getCloseProfitByTrade() detail.Direction = DirectType.Buy if pInvestorPositionDetail.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell detail.HedgeFlag = HedgeType(list(TThostFtdcHedgeFlagType).index(pInvestorPositionDetail.getHedgeFlag())) detail.OpenDate = pInvestorPositionDetail.getOpenDate() detail.PositionProfit = pInvestorPositionDetail.getPositionProfitByTrade() detail.OpenPrice = pInvestorPositionDetail.getOpenPrice() detail.TradeType = TradeTypeType(list(TThostFtdcTradeTypeType).index(pInvestorPositionDetail.getTradeType())) detail.Volume = pInvestorPositionDetail.getVolume() self.position_details[pInvestorPositionDetail.getTradeID()] = detail
持仓明细
train
https://github.com/haifengat/hf_ctp_py_proxy/blob/c2dc6dbde45aa6b097f75380474e91510d3f5d12/py_ctp/trade.py#L203-L217
null
class CtpTrade(): """""" def __init__(self): self.front_address = '' self.investor = '' self.password = '' self.broker = '' self.logined = False self.tradingday = '' self.instruments = {} self.orders = {} self.trades = {} self.account: TradingAccount = None self.positions = {} self.instrument_status = {} self._req = 0 self._session = '' self._orderid_sysid = {} self._posi = [] self.t = Trade() def _OnFrontConnected(self): threading.Thread(target=self.OnConnected, args=(self,)).start() def _OnFrontDisconnected(self, nReason): self.logined = False print(nReason) # 下午收盘后会不停断开再连接 4097错误 if nReason == 4097 or nReason == 4098: threading.Thread(target=self._reconnect).start() else: threading.Thread(target=self.OnDisConnected, args=(self, nReason)).start() def _reconnect(self): if sum([1 if stat == 'Continous' else 0 for exc, stat in self.instrument_status.items()]) == 0: print(time.strftime('%Y%m%d %H:%M:%S', time.localtime())) self.t.Release() time.sleep(600) self.ReqConnect(self.front_address) # def _OnRspUserLogout(self, pUserLogout: CThostFtdcUserLogoutField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): # pass def _OnRspUserLogin(self, pRspUserLogin: CThostFtdcRspUserLoginField(), pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" if pRspInfo.getErrorID() == 0: self.session = pRspUserLogin.getSessionID() self.tradingday = pRspUserLogin.getTradingDay() self.t.ReqSettlementInfoConfirm(self.broker, self.investor) elif self.logined: threading.Thread(target=self._relogin).start() else: info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() threading.Thread(target=self.OnUserLogin, args=(self, info)).start() def _relogin(self): # 隔夜重连=>处理'初始化'错误 time.sleep(60 * 10) self.t.ReqUserLogin( BrokerID=self.broker, UserID=self.investor, Password=self.password, UserProductInfo='@haifeng') def _OnRspSettlementInfoConfirm( self, pSettlementInfoConfirm: CThostFtdcSettlementInfoConfirmField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): if not self.logined: time.sleep(0.5) """查询合约/持仓/权益""" threading.Thread(target=self._qry).start() # 开启查询 def _qry(self): """查询帐号相关信息""" # restart 模式, 待rtnorder 处理完毕后再进行查询,否则会造成position混乱 ord_cnt = 0 trd_cnt = 0 while True: time.sleep(0.5) if len(self.orders) == ord_cnt and len(self.trades) == trd_cnt: break ord_cnt = len(self.orders) trd_cnt = len(self.trades) self.t.ReqQryInstrument() time.sleep(1.1) self.t.ReqQryInvestorPosition(self.broker, self.investor) time.sleep(1.1) self.t.ReqQryTradingAccount(self.broker, self.investor) time.sleep(1.1) self.logined = True info = InfoField() info.ErrorID = 0 info.ErrorMsg = '正确' threading.Thread(target=self.OnUserLogin, args=(self, info)).start() # 调用Release后程序异常退出,但不报错误:接口断开了仍然调用了查询指令 while self.logined: """查询持仓与权益""" self.t.ReqQryInvestorPosition(self.broker, self.investor) time.sleep(1.1) if not self.logined: return self.t.ReqQryTradingAccount(self.broker, self.investor) time.sleep(1.1) def _OnRtnInstrumentStatus(self, pInstrumentStatus: CThostFtdcInstrumentStatusField): if pInstrumentStatus.getInstrumentID() == '': return status = InstrumentStatus.Continous if pInstrumentStatus.getInstrumentStatus() == TThostFtdcInstrumentStatusType.THOST_FTDC_IS_Continous: status = InstrumentStatus.Continous elif pInstrumentStatus.getInstrumentStatus() == TThostFtdcInstrumentStatusType.THOST_FTDC_IS_Closed: status = InstrumentStatus.Closed elif str(pInstrumentStatus.getInstrumentStatus()).startswith('Auction'): status = InstrumentStatus.Auction else: status = InstrumentStatus.NoTrading self.instrument_status[pInstrumentStatus.getInstrumentID()] = status self.OnInstrumentStatus(self, pInstrumentStatus.getInstrumentID(), status) def _OnRspQryInstrument(self, pInstrument: CThostFtdcInstrumentField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" inst = InstrumentField() inst.InstrumentID = pInstrument.getInstrumentID() inst.ProductID = pInstrument.getProductID() inst.ExchangeID = pInstrument.getExchangeID() inst.VolumeMultiple = pInstrument.getVolumeMultiple() inst.PriceTick = pInstrument.getPriceTick() inst.MaxOrderVolume = pInstrument.getMaxLimitOrderVolume() inst.ProductType = pInstrument.getProductClass().name # ProductClassType.Futures -> Futures self.instruments[inst.InstrumentID] = inst def _OnRspQryPosition(self, pInvestorPosition: CThostFtdcInvestorPositionField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" if pInvestorPosition.getInstrumentID() != '': # 偶尔出现NULL的数据导致数据转换错误 self._posi.append(pInvestorPosition) # Struct(**f.__dict__)) #dict -> object if bIsLast: # 先排序再group才有效 self._posi = sorted(self._posi, key=lambda c: '{0}_{1}'.format(c.getInstrumentID(), DirectType.Buy if c.getPosiDirection() == TThostFtdcPosiDirectionType.THOST_FTDC_PD_Long else DirectType.Sell)) # direction需从posidiction转换为dictiontype for key, group in itertools.groupby(self._posi, lambda c: '{0}_{1}'.format(c.getInstrumentID(), 'Buy' if c.getPosiDirection() == TThostFtdcPosiDirectionType.THOST_FTDC_PD_Long else 'Sell')): pf = self.positions.get(key) if not pf: pf = PositionField() self.positions[key] = pf pf.Position = 0 pf.TdPosition = 0 pf.YdPosition = 0 pf.CloseProfit = 0 pf.PositionProfit = 0 pf.Commission = 0 pf.Margin = 0 pf.Price = 0 cost = 0.0 for g in group: if not pf.InstrumentID: pf.InstrumentID = g.getInstrumentID() pf.Direction = DirectType.Buy if g.getPosiDirection() == TThostFtdcPosiDirectionType.THOST_FTDC_PD_Long else DirectType.Sell pf.Position += g.getPosition() pf.TdPosition += g.getTodayPosition() pf.YdPosition = pf.Position - pf.TdPosition pf.CloseProfit += g.getCloseProfit() pf.PositionProfit += g.getPositionProfit() pf.Commission += g.getCommission() pf.Margin += g.getUseMargin() cost += g.OpenCost # pf.Position <= 0 ? 0 : (g.Sum(n => n.PositionCost) / DicInstrumentField[pf.InstrumentID].VolumeMultiple / pf.Position); vm = self.instruments[pf.InstrumentID].VolumeMultiple pf.Price = 0 if pf.Position <= 0 else cost / vm / pf.Position self._posi.clear() def _OnRspQryAccount(self, pTradingAccount: CThostFtdcTradingAccountField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" if not self.account: self.account = TradingAccount() self.account.Available = pTradingAccount.getAvailable() self.account.CloseProfit = pTradingAccount.getCloseProfit() self.account.Commission = pTradingAccount.getCommission() self.account.CurrMargin = pTradingAccount.getCurrMargin() self.account.FrozenCash = pTradingAccount.getFrozenCash() self.account.PositionProfit = pTradingAccount.getPositionProfit() self.account.PreBalance = pTradingAccount.getPreBalance() + pTradingAccount.getDeposit() + pTradingAccount.getWithdraw() self.account.Fund = self.account.PreBalance + pTradingAccount.getCloseProfit() + pTradingAccount.getPositionProfit() - pTradingAccount.getCommission() self.account.Risk = 0 if self.account.Fund == 0 else self.account.CurrMargin / self.account.Fund def _OnRtnOrder(self, pOrder: CThostFtdcOrderField): """""" id = '{0}|{1}|{2}'.format(pOrder.getSessionID(), pOrder.getFrontID(), pOrder.getOrderRef()) of = self.orders.get(id) if not of: of = OrderField() if pOrder.getOrderRef().isdigit(): of.Custom = int(pOrder.getOrderRef()) % 1000000 of.InstrumentID = pOrder.getInstrumentID() of.InsertTime = pOrder.getInsertTime() of.Direction = DirectType.Buy if pOrder.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell ot = TThostFtdcOffsetFlagType(ord(pOrder.getCombOffsetFlag()[0])) of.Offset = OffsetType.Open if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open else OffsetType.CloseToday if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_CloseToday else OffsetType.Close of.Status = OrderStatus.Normal of.StatusMsg = pOrder.getStatusMsg() of.IsLocal = pOrder.getSessionID() == self.session of.LimitPrice = pOrder.getLimitPrice() of.OrderID = id of.Volume = pOrder.getVolumeTotalOriginal() of.VolumeLeft = of.Volume self.orders[id] = of threading.Thread(target=self.OnOrder, args=(self, of)).start() elif pOrder.getOrderStatus() == TThostFtdcOrderStatusType.THOST_FTDC_OST_Canceled: of.Status = OrderStatus.Canceled of.StatusMsg = pOrder.getStatusMsg() if of.StatusMsg.find('被拒绝') >= 0: info = InfoField() info.ErrorID = -1 info.ErrorMsg = of.StatusMsg threading.Thread(target=self.OnErrOrder, args=(self, of, info)).start() else: threading.Thread(target=self.OnCancel, args=(self, of)).start() else: if pOrder.getOrderSysID(): of.SysID = pOrder.getOrderSysID() self._orderid_sysid[pOrder.getOrderSysID()] = id # 记录sysid与orderid关联,方便Trade时查找处理 def _OnRtnTrade(self, f): """""" tf = TradeField() tf.Direction = DirectType.Buy if f.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell tf.ExchangeID = f.getExchangeID() tf.InstrumentID = f.getInstrumentID() tf.Offset = OffsetType.Open if f.getOffsetFlag() == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open else OffsetType.Close if f.getOffsetFlag() == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Close else OffsetType.CloseToday tf.Price = f.getPrice() tf.SysID = f.getOrderSysID() tf.TradeID = f.getTradeID() tf.TradeTime = f.getTradeTime() tf.TradingDay = f.getTradingDay() tf.Volume = f.getVolume() self.trades[tf.TradeID] = tf id = self._orderid_sysid[tf.SysID] of = self.orders[id] tf.OrderID = id # tradeid 与 orderid 关联 of.TradeTime = tf.TradeTime of.AvgPrice = (of.AvgPrice * (of.Volume - of.VolumeLeft) + tf.Price * tf.Volume) / (of.Volume - of.VolumeLeft + tf.Volume) of.TradeVolume = tf.Volume of.VolumeLeft -= tf.Volume if of.VolumeLeft == 0: of.Status = OrderStatus.Filled of.StatusMsg = '全部成交' else: of.Status = OrderStatus.Partial of.StatusMsg = '部分成交' # 更新持仓 ***** if tf.Offset == OffsetType.Open: key = '{0}_{1}'.format(tf.InstrumentID, 'Buy' if tf.Direction == DirectType.Buy else 'Sell') pf = self.positions.get(key) if not pf: pf = PositionField() self.positions[key] = pf pf.InstrumentID = tf.InstrumentID pf.Direction = tf.Direction pf.Price = (pf.Price * pf.Position + tf.Price * tf.Volume) / (pf.Position + tf.Volume) pf.TdPosition += tf.Volume pf.Position += tf.Volume else: key = '{0}_{1}'.format(tf.InstrumentID, DirectType.Sell if tf.Direction == DirectType.Buy else DirectType.Buy) pf = self.positions.get(key) if pf: # 有可能出现无持仓的情况 if tf.Offset == OffsetType.CloseToday: pf.TdPosition -= tf.Volume else: tdclose = min(pf.TdPosition, tf.Volume) if pf.TdPosition > 0: pf.TdPosition -= tdclose pf.YdPosition -= max(0, tf.Volume - tdclose) pf.Position -= tf.Volume threading.Thread(target=self._onRtn, args=(of, tf)).start() def _onRtn(self, of, tf): self.OnOrder(self, of) self.OnTrade(self, tf) def _OnRspOrder(self, pInputOrder: CThostFtdcInputOrderField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() id = '{0}|{1}|{2}'.format(self.session, '0', pInputOrder.getOrderRef()) of = self.orders.get(id) if not of: of = OrderField() l = int(pInputOrder.getOrderRef()) of.Custom = l % 1000000 of.InstrumentID = pInputOrder.getInstrumentID() of.InsertTime = time.strftime('%H:%M:%S', time.localtime()) # 对direction需特别处理(具体见ctp_struct) of.Direction = DirectType.Buy if pInputOrder.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell ot = TThostFtdcOffsetFlagType(ord(pInputOrder.getCombOffsetFlag()[0])) of.Offset = OffsetType.Open if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open else OffsetType.CloseToday if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_CloseToday else OffsetType.Close # of.Status = OrderStatus.Normal # of.StatusMsg = f.getStatusMsg() of.IsLocal = True of.LimitPrice = pInputOrder.getLimitPrice() of.OrderID = id of.Volume = pInputOrder.getVolumeTotalOriginal() of.VolumeLeft = of.Volume self.orders[id] = of of.Status = OrderStatus.Error of.StatusMsg = '{0}:{1}'.format(info.ErrorID, info.ErrorMsg) threading.Thread(target=self.OnErrOrder, args=(self, of, info)).start() def _OnErrOrder(self, pInputOrder: CThostFtdcInputOrderField, pRspInfo: CThostFtdcRspInfoField): """""" id = '{0}|{1}|{2}'.format(self.session, '0', pInputOrder.getOrderRef()) of = self.orders.get(id) info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() if of and of.IsLocal: of.Status = OrderStatus.Error of.StatusMsg = '{0}:{1}'.format(pRspInfo.getErrorID(), pRspInfo.getErrorMsg()) threading.Thread(target=self.OnErrOrder, args=(self, of, info)).start() def _OnRspOrderAction(self, pInputOrderAction: CThostFtdcInputOrderActionField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): id = "{0}|{1}|{2}".format(pInputOrderAction.getSessionID(), pInputOrderAction.getFrontID(), pInputOrderAction.getOrderRef()) if self.logined and id in self.orders: info = InfoField() info.ErrorID = pRspInfo.ErrorID info.ErrorMsg = pRspInfo.ErrorMsg threading.Thread(target=self.OnErrCancel, args=(self, self.orders[id], info)).start() def _OnRtnNotice(self, pTradingNoticeInfo: CThostFtdcTradingNoticeInfoField): '''交易提醒''' msg = pTradingNoticeInfo.getFieldContent() if len(msg) > 0: threading.Thread(target=self.OnRtnNotice, args=(self, pTradingNoticeInfo.getSendTime(), msg)).start() def _OnRtnQuote(self, pQuote: CThostFtdcQuoteField): threading.Thread(target=self.OnRtnQuote, args=(self, pQuote)).start() def _OnErrRtnQuote(self, pInputQuote: CThostFtdcInputQuoteField, pRspInfo: CThostFtdcRspInfoField): info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() threading.Thread(target=self.OnErrRtnQuote, args=(self, pInputQuote, info)).start() def _OnErrForQuoteInsert(self, pInputForQuote: CThostFtdcInputForQuoteField, pRspInfo: CThostFtdcRspInfoField): info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() threading.Thread(target=self.OnErrRtnForQuoteInsert, args=(self, pInputForQuote, info)).start() def ReqConnect(self, front: str): """连接交易前置 :param front: """ self.t.CreateApi() spi = self.t.CreateSpi() self.t.RegisterSpi(spi) self.t.OnFrontConnected = self._OnFrontConnected self.t.OnRspUserLogin = self._OnRspUserLogin self.t.OnFrontDisconnected = self._OnFrontDisconnected # self.t.OnRspUserLogout = self._OnRspUserLogout self.t.OnRspSettlementInfoConfirm = self._OnRspSettlementInfoConfirm self.t.OnRtnOrder = self._OnRtnOrder self.t.OnRtnTrade = self._OnRtnTrade self.t.OnRspOrderInsert = self._OnRspOrder self.t.OnErrRtnOrderInsert = self._OnErrOrder self.t.OnRspOrderAction = self._OnRspOrderAction self.t.OnRtnInstrumentStatus = self._OnRtnInstrumentStatus self.t.OnRspQryInstrument = self._OnRspQryInstrument self.t.OnRspQryTradingAccount = self._OnRspQryAccount self.t.OnRspQryInvestorPosition = self._OnRspQryPosition self.t.OnRspQryInvestorPositionDetail = self._OnRspQryPositionDetail self.t.OnRtnTradingNotice = self._OnRtnNotice self.t.OnRtnQuote = self._OnRtnQuote self.t.OnErrRtnQuoteInsert = self._OnErrRtnQuote self.t.OnErrRtnForQuoteInsert = self._OnErrForQuoteInsert self.front_address = front self.t.RegCB() self.t.RegisterFront(front) self.t.SubscribePrivateTopic(0) # restart 同步处理order trade self.t.SubscribePublicTopic(0) self.t.Init() # self.t.Join() def ReqUserLogin(self, user: str, pwd: str, broker: str): """登录 :param user: :param pwd: :param broker: """ self.broker = broker self.investor = user self.password = pwd self.t.ReqUserLogin(BrokerID=broker, UserID=user, Password=pwd) def ReqOrderInsert(self, pInstrument: str, pDirection: DirectType, pOffset: OffsetType, pPrice: float = 0.0, pVolume: int = 1, pType: OrderType = OrderType.Limit, pCustom: int = 0): """委托 :param pInstrument: :param pDirection: :param pOffset: :param pPrice: :param pVolume: :param pType: :param pCustom: :return: """ OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_AnyPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = 0.0 VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV if pType == OrderType.Market: # 市价 OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_AnyPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = 0.0 VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV elif pType == OrderType.Limit: # 限价 OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LimitPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_GFD LimitPrice = pPrice VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV elif pType == OrderType.FAK: # FAK OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LimitPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = pPrice VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV elif pType == OrderType.FOK: # FOK OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LimitPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = pPrice VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_CV # 全部数量 self._req += 1 self.t.ReqOrderInsert( BrokerID=self.broker, InvestorID=self.investor, InstrumentID=pInstrument, OrderRef="%06d%06d" % (self._req, pCustom % 1000000), UserID=self.investor, # 此处ctp_enum与at_struct名称冲突 Direction=TThostFtdcDirectionType.THOST_FTDC_D_Buy if pDirection == DirectType.Buy else TThostFtdcDirectionType.THOST_FTDC_D_Sell, CombOffsetFlag=chr(TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open.value if pOffset == OffsetType.Open else TThostFtdcOffsetFlagType.THOST_FTDC_OF_CloseToday.value if pOffset == OffsetType.CloseToday else TThostFtdcOffsetFlagType.THOST_FTDC_OF_Close.value), CombHedgeFlag=chr(TThostFtdcHedgeFlagType.THOST_FTDC_HF_Speculation.value), IsAutoSuspend=0, ForceCloseReason=TThostFtdcForceCloseReasonType.THOST_FTDC_FCC_NotForceClose, IsSwapOrder=0, ContingentCondition=TThostFtdcContingentConditionType.THOST_FTDC_CC_Immediately, VolumeCondition=VolumeCondition, MinVolume=1, VolumeTotalOriginal=pVolume, OrderPriceType=OrderPriceType, TimeCondition=TimeCondition, LimitPrice=LimitPrice, ) def ReqOrderAction(self, OrderID: str): """撤单 :param OrderID: """ of = self.orders[OrderID] if not of: return -1 else: pOrderId = of.OrderID return self.t.ReqOrderAction( self.broker, self.investor, OrderRef=pOrderId.split('|')[2], FrontID=int(pOrderId.split('|')[1]), SessionID=int(pOrderId.split('|')[0]), InstrumentID=of.InstrumentID, ActionFlag=TThostFtdcActionFlagType.THOST_FTDC_AF_Delete) def ReqUserLogout(self): """退出接口""" self.logined = False time.sleep(3) self.t.ReqUserLogout(BrokerID=self.broker, UserID=self.investor) self.t.RegisterSpi(None) self.t.Release() threading.Thread(target=self.OnDisConnected, args=(self, 0)).start() def OnConnected(self, obj): """接口连接 :param obj: """ print('=== [TRADE] OnConnected ==='.format('')) def OnDisConnected(self, obj, reason: int): """接口断开 :param obj: :param reason: """ print('=== [TRADE] OnDisConnected === \nreason: {0}'.format(reason)) def OnUserLogin(self, obj, info: InfoField): """登录响应 :param obj: :param info: """ print('=== [TRADE] OnUserLogin === \n{0}'.format(info)) def OnOrder(self, obj, f: OrderField): """委托响应 :param obj: :param f: """ print('=== [TRADE] OnOrder === \n{0}'.format(f.__dict__)) def OnTrade(self, obj, f: TradeField): """成交响应 :param obj: :param f: """ print('=== [TRADE] OnTrade === \n{0}'.format(f.__dict__)) def OnCancel(self, obj, f: OrderField): """ 撤单响应 :param self: :param obj: :param f:OrderField: """ print('=== [TRADE] OnCancel === \n{0}'.format(f.__dict__)) def OnErrCancel(self, obj, f: OrderField, info: InfoField): """ 撤单失败 :param self: :param obj: :param f:OrderField: :param info:InfoField: """ print('=== [TRADE] OnErrCancel ===\n{0}'.format(f.__dict__)) print(info) def OnErrOrder(self, obj, f: OrderField, info: InfoField): """ 委托错误 :param self: :param obj: :param f:OrderField: :param info:InfoField: """ print('=== [TRADE] OnErrOrder ===\n{0}'.format(f.__dict__)) print(info) def OnInstrumentStatus(self, obj, inst: str, status: InstrumentStatus): """ 交易状态 :param self: :param obj: :param inst:str: :param status:InstrumentStatus: """ print('{}:{}'.format(inst, str(status).strip().split('.')[-1])) def OnRtnNotice(self, obj, time: str, msg: str): """交易提醒 :param obj: :param time: :param msg: :return: """ print(f'=== OnRtnNotice===\n {time}:{msg}') def OnRtnQuote(self, obj, quote: CThostFtdcQuoteField): """报价通知 :param obj: :param quote: :return: """ print('=== [TRADE] OnRtnQuote ===\n{0}'.format(quote.__dict__)) def OnErrRtnQuote(self, obj, quote: CThostFtdcInputQuoteField, info: InfoField): """ :param obj: :param quote: :return: """ print('=== [TRADE] OnErrRtnQuote ===\n{0}'.format(quote.__dict__)) print(info) def OnErrRtnForQuoteInsert(self, obj, quote: CThostFtdcInputQuoteField, info: InfoField): """询价录入错误回报 :param obj: :param quote: :return: """ print('=== [TRADE] OnErrRtnForQuoteInsert ===\n{0}'.format(quote.__dict__)) print(info)
haifengat/hf_ctp_py_proxy
py_ctp/trade.py
CtpTrade._OnRtnNotice
python
def _OnRtnNotice(self, pTradingNoticeInfo: CThostFtdcTradingNoticeInfoField): '''交易提醒''' msg = pTradingNoticeInfo.getFieldContent() if len(msg) > 0: threading.Thread(target=self.OnRtnNotice, args=(self, pTradingNoticeInfo.getSendTime(), msg)).start()
交易提醒
train
https://github.com/haifengat/hf_ctp_py_proxy/blob/c2dc6dbde45aa6b097f75380474e91510d3f5d12/py_ctp/trade.py#L384-L388
null
class CtpTrade(): """""" def __init__(self): self.front_address = '' self.investor = '' self.password = '' self.broker = '' self.logined = False self.tradingday = '' self.instruments = {} self.orders = {} self.trades = {} self.account: TradingAccount = None self.positions = {} self.instrument_status = {} self._req = 0 self._session = '' self._orderid_sysid = {} self._posi = [] self.t = Trade() def _OnFrontConnected(self): threading.Thread(target=self.OnConnected, args=(self,)).start() def _OnFrontDisconnected(self, nReason): self.logined = False print(nReason) # 下午收盘后会不停断开再连接 4097错误 if nReason == 4097 or nReason == 4098: threading.Thread(target=self._reconnect).start() else: threading.Thread(target=self.OnDisConnected, args=(self, nReason)).start() def _reconnect(self): if sum([1 if stat == 'Continous' else 0 for exc, stat in self.instrument_status.items()]) == 0: print(time.strftime('%Y%m%d %H:%M:%S', time.localtime())) self.t.Release() time.sleep(600) self.ReqConnect(self.front_address) # def _OnRspUserLogout(self, pUserLogout: CThostFtdcUserLogoutField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): # pass def _OnRspUserLogin(self, pRspUserLogin: CThostFtdcRspUserLoginField(), pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" if pRspInfo.getErrorID() == 0: self.session = pRspUserLogin.getSessionID() self.tradingday = pRspUserLogin.getTradingDay() self.t.ReqSettlementInfoConfirm(self.broker, self.investor) elif self.logined: threading.Thread(target=self._relogin).start() else: info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() threading.Thread(target=self.OnUserLogin, args=(self, info)).start() def _relogin(self): # 隔夜重连=>处理'初始化'错误 time.sleep(60 * 10) self.t.ReqUserLogin( BrokerID=self.broker, UserID=self.investor, Password=self.password, UserProductInfo='@haifeng') def _OnRspSettlementInfoConfirm( self, pSettlementInfoConfirm: CThostFtdcSettlementInfoConfirmField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): if not self.logined: time.sleep(0.5) """查询合约/持仓/权益""" threading.Thread(target=self._qry).start() # 开启查询 def _qry(self): """查询帐号相关信息""" # restart 模式, 待rtnorder 处理完毕后再进行查询,否则会造成position混乱 ord_cnt = 0 trd_cnt = 0 while True: time.sleep(0.5) if len(self.orders) == ord_cnt and len(self.trades) == trd_cnt: break ord_cnt = len(self.orders) trd_cnt = len(self.trades) self.t.ReqQryInstrument() time.sleep(1.1) self.t.ReqQryInvestorPosition(self.broker, self.investor) time.sleep(1.1) self.t.ReqQryTradingAccount(self.broker, self.investor) time.sleep(1.1) self.logined = True info = InfoField() info.ErrorID = 0 info.ErrorMsg = '正确' threading.Thread(target=self.OnUserLogin, args=(self, info)).start() # 调用Release后程序异常退出,但不报错误:接口断开了仍然调用了查询指令 while self.logined: """查询持仓与权益""" self.t.ReqQryInvestorPosition(self.broker, self.investor) time.sleep(1.1) if not self.logined: return self.t.ReqQryTradingAccount(self.broker, self.investor) time.sleep(1.1) def _OnRtnInstrumentStatus(self, pInstrumentStatus: CThostFtdcInstrumentStatusField): if pInstrumentStatus.getInstrumentID() == '': return status = InstrumentStatus.Continous if pInstrumentStatus.getInstrumentStatus() == TThostFtdcInstrumentStatusType.THOST_FTDC_IS_Continous: status = InstrumentStatus.Continous elif pInstrumentStatus.getInstrumentStatus() == TThostFtdcInstrumentStatusType.THOST_FTDC_IS_Closed: status = InstrumentStatus.Closed elif str(pInstrumentStatus.getInstrumentStatus()).startswith('Auction'): status = InstrumentStatus.Auction else: status = InstrumentStatus.NoTrading self.instrument_status[pInstrumentStatus.getInstrumentID()] = status self.OnInstrumentStatus(self, pInstrumentStatus.getInstrumentID(), status) def _OnRspQryInstrument(self, pInstrument: CThostFtdcInstrumentField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" inst = InstrumentField() inst.InstrumentID = pInstrument.getInstrumentID() inst.ProductID = pInstrument.getProductID() inst.ExchangeID = pInstrument.getExchangeID() inst.VolumeMultiple = pInstrument.getVolumeMultiple() inst.PriceTick = pInstrument.getPriceTick() inst.MaxOrderVolume = pInstrument.getMaxLimitOrderVolume() inst.ProductType = pInstrument.getProductClass().name # ProductClassType.Futures -> Futures self.instruments[inst.InstrumentID] = inst def _OnRspQryPosition(self, pInvestorPosition: CThostFtdcInvestorPositionField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" if pInvestorPosition.getInstrumentID() != '': # 偶尔出现NULL的数据导致数据转换错误 self._posi.append(pInvestorPosition) # Struct(**f.__dict__)) #dict -> object if bIsLast: # 先排序再group才有效 self._posi = sorted(self._posi, key=lambda c: '{0}_{1}'.format(c.getInstrumentID(), DirectType.Buy if c.getPosiDirection() == TThostFtdcPosiDirectionType.THOST_FTDC_PD_Long else DirectType.Sell)) # direction需从posidiction转换为dictiontype for key, group in itertools.groupby(self._posi, lambda c: '{0}_{1}'.format(c.getInstrumentID(), 'Buy' if c.getPosiDirection() == TThostFtdcPosiDirectionType.THOST_FTDC_PD_Long else 'Sell')): pf = self.positions.get(key) if not pf: pf = PositionField() self.positions[key] = pf pf.Position = 0 pf.TdPosition = 0 pf.YdPosition = 0 pf.CloseProfit = 0 pf.PositionProfit = 0 pf.Commission = 0 pf.Margin = 0 pf.Price = 0 cost = 0.0 for g in group: if not pf.InstrumentID: pf.InstrumentID = g.getInstrumentID() pf.Direction = DirectType.Buy if g.getPosiDirection() == TThostFtdcPosiDirectionType.THOST_FTDC_PD_Long else DirectType.Sell pf.Position += g.getPosition() pf.TdPosition += g.getTodayPosition() pf.YdPosition = pf.Position - pf.TdPosition pf.CloseProfit += g.getCloseProfit() pf.PositionProfit += g.getPositionProfit() pf.Commission += g.getCommission() pf.Margin += g.getUseMargin() cost += g.OpenCost # pf.Position <= 0 ? 0 : (g.Sum(n => n.PositionCost) / DicInstrumentField[pf.InstrumentID].VolumeMultiple / pf.Position); vm = self.instruments[pf.InstrumentID].VolumeMultiple pf.Price = 0 if pf.Position <= 0 else cost / vm / pf.Position self._posi.clear() def _OnRspQryPositionDetail(self, pInvestorPositionDetail: CThostFtdcInvestorPositionDetailField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """持仓明细""" if pInvestorPositionDetail.getInstrumentID() == '': return detail = PositionDetail() detail.Instrument = pInvestorPositionDetail.getInstrumentID() detail.CloseProfit = pInvestorPositionDetail.getCloseProfitByTrade() detail.Direction = DirectType.Buy if pInvestorPositionDetail.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell detail.HedgeFlag = HedgeType(list(TThostFtdcHedgeFlagType).index(pInvestorPositionDetail.getHedgeFlag())) detail.OpenDate = pInvestorPositionDetail.getOpenDate() detail.PositionProfit = pInvestorPositionDetail.getPositionProfitByTrade() detail.OpenPrice = pInvestorPositionDetail.getOpenPrice() detail.TradeType = TradeTypeType(list(TThostFtdcTradeTypeType).index(pInvestorPositionDetail.getTradeType())) detail.Volume = pInvestorPositionDetail.getVolume() self.position_details[pInvestorPositionDetail.getTradeID()] = detail def _OnRspQryAccount(self, pTradingAccount: CThostFtdcTradingAccountField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" if not self.account: self.account = TradingAccount() self.account.Available = pTradingAccount.getAvailable() self.account.CloseProfit = pTradingAccount.getCloseProfit() self.account.Commission = pTradingAccount.getCommission() self.account.CurrMargin = pTradingAccount.getCurrMargin() self.account.FrozenCash = pTradingAccount.getFrozenCash() self.account.PositionProfit = pTradingAccount.getPositionProfit() self.account.PreBalance = pTradingAccount.getPreBalance() + pTradingAccount.getDeposit() + pTradingAccount.getWithdraw() self.account.Fund = self.account.PreBalance + pTradingAccount.getCloseProfit() + pTradingAccount.getPositionProfit() - pTradingAccount.getCommission() self.account.Risk = 0 if self.account.Fund == 0 else self.account.CurrMargin / self.account.Fund def _OnRtnOrder(self, pOrder: CThostFtdcOrderField): """""" id = '{0}|{1}|{2}'.format(pOrder.getSessionID(), pOrder.getFrontID(), pOrder.getOrderRef()) of = self.orders.get(id) if not of: of = OrderField() if pOrder.getOrderRef().isdigit(): of.Custom = int(pOrder.getOrderRef()) % 1000000 of.InstrumentID = pOrder.getInstrumentID() of.InsertTime = pOrder.getInsertTime() of.Direction = DirectType.Buy if pOrder.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell ot = TThostFtdcOffsetFlagType(ord(pOrder.getCombOffsetFlag()[0])) of.Offset = OffsetType.Open if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open else OffsetType.CloseToday if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_CloseToday else OffsetType.Close of.Status = OrderStatus.Normal of.StatusMsg = pOrder.getStatusMsg() of.IsLocal = pOrder.getSessionID() == self.session of.LimitPrice = pOrder.getLimitPrice() of.OrderID = id of.Volume = pOrder.getVolumeTotalOriginal() of.VolumeLeft = of.Volume self.orders[id] = of threading.Thread(target=self.OnOrder, args=(self, of)).start() elif pOrder.getOrderStatus() == TThostFtdcOrderStatusType.THOST_FTDC_OST_Canceled: of.Status = OrderStatus.Canceled of.StatusMsg = pOrder.getStatusMsg() if of.StatusMsg.find('被拒绝') >= 0: info = InfoField() info.ErrorID = -1 info.ErrorMsg = of.StatusMsg threading.Thread(target=self.OnErrOrder, args=(self, of, info)).start() else: threading.Thread(target=self.OnCancel, args=(self, of)).start() else: if pOrder.getOrderSysID(): of.SysID = pOrder.getOrderSysID() self._orderid_sysid[pOrder.getOrderSysID()] = id # 记录sysid与orderid关联,方便Trade时查找处理 def _OnRtnTrade(self, f): """""" tf = TradeField() tf.Direction = DirectType.Buy if f.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell tf.ExchangeID = f.getExchangeID() tf.InstrumentID = f.getInstrumentID() tf.Offset = OffsetType.Open if f.getOffsetFlag() == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open else OffsetType.Close if f.getOffsetFlag() == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Close else OffsetType.CloseToday tf.Price = f.getPrice() tf.SysID = f.getOrderSysID() tf.TradeID = f.getTradeID() tf.TradeTime = f.getTradeTime() tf.TradingDay = f.getTradingDay() tf.Volume = f.getVolume() self.trades[tf.TradeID] = tf id = self._orderid_sysid[tf.SysID] of = self.orders[id] tf.OrderID = id # tradeid 与 orderid 关联 of.TradeTime = tf.TradeTime of.AvgPrice = (of.AvgPrice * (of.Volume - of.VolumeLeft) + tf.Price * tf.Volume) / (of.Volume - of.VolumeLeft + tf.Volume) of.TradeVolume = tf.Volume of.VolumeLeft -= tf.Volume if of.VolumeLeft == 0: of.Status = OrderStatus.Filled of.StatusMsg = '全部成交' else: of.Status = OrderStatus.Partial of.StatusMsg = '部分成交' # 更新持仓 ***** if tf.Offset == OffsetType.Open: key = '{0}_{1}'.format(tf.InstrumentID, 'Buy' if tf.Direction == DirectType.Buy else 'Sell') pf = self.positions.get(key) if not pf: pf = PositionField() self.positions[key] = pf pf.InstrumentID = tf.InstrumentID pf.Direction = tf.Direction pf.Price = (pf.Price * pf.Position + tf.Price * tf.Volume) / (pf.Position + tf.Volume) pf.TdPosition += tf.Volume pf.Position += tf.Volume else: key = '{0}_{1}'.format(tf.InstrumentID, DirectType.Sell if tf.Direction == DirectType.Buy else DirectType.Buy) pf = self.positions.get(key) if pf: # 有可能出现无持仓的情况 if tf.Offset == OffsetType.CloseToday: pf.TdPosition -= tf.Volume else: tdclose = min(pf.TdPosition, tf.Volume) if pf.TdPosition > 0: pf.TdPosition -= tdclose pf.YdPosition -= max(0, tf.Volume - tdclose) pf.Position -= tf.Volume threading.Thread(target=self._onRtn, args=(of, tf)).start() def _onRtn(self, of, tf): self.OnOrder(self, of) self.OnTrade(self, tf) def _OnRspOrder(self, pInputOrder: CThostFtdcInputOrderField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() id = '{0}|{1}|{2}'.format(self.session, '0', pInputOrder.getOrderRef()) of = self.orders.get(id) if not of: of = OrderField() l = int(pInputOrder.getOrderRef()) of.Custom = l % 1000000 of.InstrumentID = pInputOrder.getInstrumentID() of.InsertTime = time.strftime('%H:%M:%S', time.localtime()) # 对direction需特别处理(具体见ctp_struct) of.Direction = DirectType.Buy if pInputOrder.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell ot = TThostFtdcOffsetFlagType(ord(pInputOrder.getCombOffsetFlag()[0])) of.Offset = OffsetType.Open if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open else OffsetType.CloseToday if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_CloseToday else OffsetType.Close # of.Status = OrderStatus.Normal # of.StatusMsg = f.getStatusMsg() of.IsLocal = True of.LimitPrice = pInputOrder.getLimitPrice() of.OrderID = id of.Volume = pInputOrder.getVolumeTotalOriginal() of.VolumeLeft = of.Volume self.orders[id] = of of.Status = OrderStatus.Error of.StatusMsg = '{0}:{1}'.format(info.ErrorID, info.ErrorMsg) threading.Thread(target=self.OnErrOrder, args=(self, of, info)).start() def _OnErrOrder(self, pInputOrder: CThostFtdcInputOrderField, pRspInfo: CThostFtdcRspInfoField): """""" id = '{0}|{1}|{2}'.format(self.session, '0', pInputOrder.getOrderRef()) of = self.orders.get(id) info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() if of and of.IsLocal: of.Status = OrderStatus.Error of.StatusMsg = '{0}:{1}'.format(pRspInfo.getErrorID(), pRspInfo.getErrorMsg()) threading.Thread(target=self.OnErrOrder, args=(self, of, info)).start() def _OnRspOrderAction(self, pInputOrderAction: CThostFtdcInputOrderActionField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): id = "{0}|{1}|{2}".format(pInputOrderAction.getSessionID(), pInputOrderAction.getFrontID(), pInputOrderAction.getOrderRef()) if self.logined and id in self.orders: info = InfoField() info.ErrorID = pRspInfo.ErrorID info.ErrorMsg = pRspInfo.ErrorMsg threading.Thread(target=self.OnErrCancel, args=(self, self.orders[id], info)).start() def _OnRtnQuote(self, pQuote: CThostFtdcQuoteField): threading.Thread(target=self.OnRtnQuote, args=(self, pQuote)).start() def _OnErrRtnQuote(self, pInputQuote: CThostFtdcInputQuoteField, pRspInfo: CThostFtdcRspInfoField): info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() threading.Thread(target=self.OnErrRtnQuote, args=(self, pInputQuote, info)).start() def _OnErrForQuoteInsert(self, pInputForQuote: CThostFtdcInputForQuoteField, pRspInfo: CThostFtdcRspInfoField): info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() threading.Thread(target=self.OnErrRtnForQuoteInsert, args=(self, pInputForQuote, info)).start() def ReqConnect(self, front: str): """连接交易前置 :param front: """ self.t.CreateApi() spi = self.t.CreateSpi() self.t.RegisterSpi(spi) self.t.OnFrontConnected = self._OnFrontConnected self.t.OnRspUserLogin = self._OnRspUserLogin self.t.OnFrontDisconnected = self._OnFrontDisconnected # self.t.OnRspUserLogout = self._OnRspUserLogout self.t.OnRspSettlementInfoConfirm = self._OnRspSettlementInfoConfirm self.t.OnRtnOrder = self._OnRtnOrder self.t.OnRtnTrade = self._OnRtnTrade self.t.OnRspOrderInsert = self._OnRspOrder self.t.OnErrRtnOrderInsert = self._OnErrOrder self.t.OnRspOrderAction = self._OnRspOrderAction self.t.OnRtnInstrumentStatus = self._OnRtnInstrumentStatus self.t.OnRspQryInstrument = self._OnRspQryInstrument self.t.OnRspQryTradingAccount = self._OnRspQryAccount self.t.OnRspQryInvestorPosition = self._OnRspQryPosition self.t.OnRspQryInvestorPositionDetail = self._OnRspQryPositionDetail self.t.OnRtnTradingNotice = self._OnRtnNotice self.t.OnRtnQuote = self._OnRtnQuote self.t.OnErrRtnQuoteInsert = self._OnErrRtnQuote self.t.OnErrRtnForQuoteInsert = self._OnErrForQuoteInsert self.front_address = front self.t.RegCB() self.t.RegisterFront(front) self.t.SubscribePrivateTopic(0) # restart 同步处理order trade self.t.SubscribePublicTopic(0) self.t.Init() # self.t.Join() def ReqUserLogin(self, user: str, pwd: str, broker: str): """登录 :param user: :param pwd: :param broker: """ self.broker = broker self.investor = user self.password = pwd self.t.ReqUserLogin(BrokerID=broker, UserID=user, Password=pwd) def ReqOrderInsert(self, pInstrument: str, pDirection: DirectType, pOffset: OffsetType, pPrice: float = 0.0, pVolume: int = 1, pType: OrderType = OrderType.Limit, pCustom: int = 0): """委托 :param pInstrument: :param pDirection: :param pOffset: :param pPrice: :param pVolume: :param pType: :param pCustom: :return: """ OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_AnyPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = 0.0 VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV if pType == OrderType.Market: # 市价 OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_AnyPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = 0.0 VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV elif pType == OrderType.Limit: # 限价 OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LimitPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_GFD LimitPrice = pPrice VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV elif pType == OrderType.FAK: # FAK OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LimitPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = pPrice VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV elif pType == OrderType.FOK: # FOK OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LimitPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = pPrice VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_CV # 全部数量 self._req += 1 self.t.ReqOrderInsert( BrokerID=self.broker, InvestorID=self.investor, InstrumentID=pInstrument, OrderRef="%06d%06d" % (self._req, pCustom % 1000000), UserID=self.investor, # 此处ctp_enum与at_struct名称冲突 Direction=TThostFtdcDirectionType.THOST_FTDC_D_Buy if pDirection == DirectType.Buy else TThostFtdcDirectionType.THOST_FTDC_D_Sell, CombOffsetFlag=chr(TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open.value if pOffset == OffsetType.Open else TThostFtdcOffsetFlagType.THOST_FTDC_OF_CloseToday.value if pOffset == OffsetType.CloseToday else TThostFtdcOffsetFlagType.THOST_FTDC_OF_Close.value), CombHedgeFlag=chr(TThostFtdcHedgeFlagType.THOST_FTDC_HF_Speculation.value), IsAutoSuspend=0, ForceCloseReason=TThostFtdcForceCloseReasonType.THOST_FTDC_FCC_NotForceClose, IsSwapOrder=0, ContingentCondition=TThostFtdcContingentConditionType.THOST_FTDC_CC_Immediately, VolumeCondition=VolumeCondition, MinVolume=1, VolumeTotalOriginal=pVolume, OrderPriceType=OrderPriceType, TimeCondition=TimeCondition, LimitPrice=LimitPrice, ) def ReqOrderAction(self, OrderID: str): """撤单 :param OrderID: """ of = self.orders[OrderID] if not of: return -1 else: pOrderId = of.OrderID return self.t.ReqOrderAction( self.broker, self.investor, OrderRef=pOrderId.split('|')[2], FrontID=int(pOrderId.split('|')[1]), SessionID=int(pOrderId.split('|')[0]), InstrumentID=of.InstrumentID, ActionFlag=TThostFtdcActionFlagType.THOST_FTDC_AF_Delete) def ReqUserLogout(self): """退出接口""" self.logined = False time.sleep(3) self.t.ReqUserLogout(BrokerID=self.broker, UserID=self.investor) self.t.RegisterSpi(None) self.t.Release() threading.Thread(target=self.OnDisConnected, args=(self, 0)).start() def OnConnected(self, obj): """接口连接 :param obj: """ print('=== [TRADE] OnConnected ==='.format('')) def OnDisConnected(self, obj, reason: int): """接口断开 :param obj: :param reason: """ print('=== [TRADE] OnDisConnected === \nreason: {0}'.format(reason)) def OnUserLogin(self, obj, info: InfoField): """登录响应 :param obj: :param info: """ print('=== [TRADE] OnUserLogin === \n{0}'.format(info)) def OnOrder(self, obj, f: OrderField): """委托响应 :param obj: :param f: """ print('=== [TRADE] OnOrder === \n{0}'.format(f.__dict__)) def OnTrade(self, obj, f: TradeField): """成交响应 :param obj: :param f: """ print('=== [TRADE] OnTrade === \n{0}'.format(f.__dict__)) def OnCancel(self, obj, f: OrderField): """ 撤单响应 :param self: :param obj: :param f:OrderField: """ print('=== [TRADE] OnCancel === \n{0}'.format(f.__dict__)) def OnErrCancel(self, obj, f: OrderField, info: InfoField): """ 撤单失败 :param self: :param obj: :param f:OrderField: :param info:InfoField: """ print('=== [TRADE] OnErrCancel ===\n{0}'.format(f.__dict__)) print(info) def OnErrOrder(self, obj, f: OrderField, info: InfoField): """ 委托错误 :param self: :param obj: :param f:OrderField: :param info:InfoField: """ print('=== [TRADE] OnErrOrder ===\n{0}'.format(f.__dict__)) print(info) def OnInstrumentStatus(self, obj, inst: str, status: InstrumentStatus): """ 交易状态 :param self: :param obj: :param inst:str: :param status:InstrumentStatus: """ print('{}:{}'.format(inst, str(status).strip().split('.')[-1])) def OnRtnNotice(self, obj, time: str, msg: str): """交易提醒 :param obj: :param time: :param msg: :return: """ print(f'=== OnRtnNotice===\n {time}:{msg}') def OnRtnQuote(self, obj, quote: CThostFtdcQuoteField): """报价通知 :param obj: :param quote: :return: """ print('=== [TRADE] OnRtnQuote ===\n{0}'.format(quote.__dict__)) def OnErrRtnQuote(self, obj, quote: CThostFtdcInputQuoteField, info: InfoField): """ :param obj: :param quote: :return: """ print('=== [TRADE] OnErrRtnQuote ===\n{0}'.format(quote.__dict__)) print(info) def OnErrRtnForQuoteInsert(self, obj, quote: CThostFtdcInputQuoteField, info: InfoField): """询价录入错误回报 :param obj: :param quote: :return: """ print('=== [TRADE] OnErrRtnForQuoteInsert ===\n{0}'.format(quote.__dict__)) print(info)
haifengat/hf_ctp_py_proxy
py_ctp/trade.py
CtpTrade.ReqConnect
python
def ReqConnect(self, front: str): self.t.CreateApi() spi = self.t.CreateSpi() self.t.RegisterSpi(spi) self.t.OnFrontConnected = self._OnFrontConnected self.t.OnRspUserLogin = self._OnRspUserLogin self.t.OnFrontDisconnected = self._OnFrontDisconnected # self.t.OnRspUserLogout = self._OnRspUserLogout self.t.OnRspSettlementInfoConfirm = self._OnRspSettlementInfoConfirm self.t.OnRtnOrder = self._OnRtnOrder self.t.OnRtnTrade = self._OnRtnTrade self.t.OnRspOrderInsert = self._OnRspOrder self.t.OnErrRtnOrderInsert = self._OnErrOrder self.t.OnRspOrderAction = self._OnRspOrderAction self.t.OnRtnInstrumentStatus = self._OnRtnInstrumentStatus self.t.OnRspQryInstrument = self._OnRspQryInstrument self.t.OnRspQryTradingAccount = self._OnRspQryAccount self.t.OnRspQryInvestorPosition = self._OnRspQryPosition self.t.OnRspQryInvestorPositionDetail = self._OnRspQryPositionDetail self.t.OnRtnTradingNotice = self._OnRtnNotice self.t.OnRtnQuote = self._OnRtnQuote self.t.OnErrRtnQuoteInsert = self._OnErrRtnQuote self.t.OnErrRtnForQuoteInsert = self._OnErrForQuoteInsert self.front_address = front self.t.RegCB() self.t.RegisterFront(front) self.t.SubscribePrivateTopic(0) # restart 同步处理order trade self.t.SubscribePublicTopic(0) self.t.Init()
连接交易前置 :param front:
train
https://github.com/haifengat/hf_ctp_py_proxy/blob/c2dc6dbde45aa6b097f75380474e91510d3f5d12/py_ctp/trade.py#L405-L439
null
class CtpTrade(): """""" def __init__(self): self.front_address = '' self.investor = '' self.password = '' self.broker = '' self.logined = False self.tradingday = '' self.instruments = {} self.orders = {} self.trades = {} self.account: TradingAccount = None self.positions = {} self.instrument_status = {} self._req = 0 self._session = '' self._orderid_sysid = {} self._posi = [] self.t = Trade() def _OnFrontConnected(self): threading.Thread(target=self.OnConnected, args=(self,)).start() def _OnFrontDisconnected(self, nReason): self.logined = False print(nReason) # 下午收盘后会不停断开再连接 4097错误 if nReason == 4097 or nReason == 4098: threading.Thread(target=self._reconnect).start() else: threading.Thread(target=self.OnDisConnected, args=(self, nReason)).start() def _reconnect(self): if sum([1 if stat == 'Continous' else 0 for exc, stat in self.instrument_status.items()]) == 0: print(time.strftime('%Y%m%d %H:%M:%S', time.localtime())) self.t.Release() time.sleep(600) self.ReqConnect(self.front_address) # def _OnRspUserLogout(self, pUserLogout: CThostFtdcUserLogoutField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): # pass def _OnRspUserLogin(self, pRspUserLogin: CThostFtdcRspUserLoginField(), pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" if pRspInfo.getErrorID() == 0: self.session = pRspUserLogin.getSessionID() self.tradingday = pRspUserLogin.getTradingDay() self.t.ReqSettlementInfoConfirm(self.broker, self.investor) elif self.logined: threading.Thread(target=self._relogin).start() else: info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() threading.Thread(target=self.OnUserLogin, args=(self, info)).start() def _relogin(self): # 隔夜重连=>处理'初始化'错误 time.sleep(60 * 10) self.t.ReqUserLogin( BrokerID=self.broker, UserID=self.investor, Password=self.password, UserProductInfo='@haifeng') def _OnRspSettlementInfoConfirm( self, pSettlementInfoConfirm: CThostFtdcSettlementInfoConfirmField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): if not self.logined: time.sleep(0.5) """查询合约/持仓/权益""" threading.Thread(target=self._qry).start() # 开启查询 def _qry(self): """查询帐号相关信息""" # restart 模式, 待rtnorder 处理完毕后再进行查询,否则会造成position混乱 ord_cnt = 0 trd_cnt = 0 while True: time.sleep(0.5) if len(self.orders) == ord_cnt and len(self.trades) == trd_cnt: break ord_cnt = len(self.orders) trd_cnt = len(self.trades) self.t.ReqQryInstrument() time.sleep(1.1) self.t.ReqQryInvestorPosition(self.broker, self.investor) time.sleep(1.1) self.t.ReqQryTradingAccount(self.broker, self.investor) time.sleep(1.1) self.logined = True info = InfoField() info.ErrorID = 0 info.ErrorMsg = '正确' threading.Thread(target=self.OnUserLogin, args=(self, info)).start() # 调用Release后程序异常退出,但不报错误:接口断开了仍然调用了查询指令 while self.logined: """查询持仓与权益""" self.t.ReqQryInvestorPosition(self.broker, self.investor) time.sleep(1.1) if not self.logined: return self.t.ReqQryTradingAccount(self.broker, self.investor) time.sleep(1.1) def _OnRtnInstrumentStatus(self, pInstrumentStatus: CThostFtdcInstrumentStatusField): if pInstrumentStatus.getInstrumentID() == '': return status = InstrumentStatus.Continous if pInstrumentStatus.getInstrumentStatus() == TThostFtdcInstrumentStatusType.THOST_FTDC_IS_Continous: status = InstrumentStatus.Continous elif pInstrumentStatus.getInstrumentStatus() == TThostFtdcInstrumentStatusType.THOST_FTDC_IS_Closed: status = InstrumentStatus.Closed elif str(pInstrumentStatus.getInstrumentStatus()).startswith('Auction'): status = InstrumentStatus.Auction else: status = InstrumentStatus.NoTrading self.instrument_status[pInstrumentStatus.getInstrumentID()] = status self.OnInstrumentStatus(self, pInstrumentStatus.getInstrumentID(), status) def _OnRspQryInstrument(self, pInstrument: CThostFtdcInstrumentField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" inst = InstrumentField() inst.InstrumentID = pInstrument.getInstrumentID() inst.ProductID = pInstrument.getProductID() inst.ExchangeID = pInstrument.getExchangeID() inst.VolumeMultiple = pInstrument.getVolumeMultiple() inst.PriceTick = pInstrument.getPriceTick() inst.MaxOrderVolume = pInstrument.getMaxLimitOrderVolume() inst.ProductType = pInstrument.getProductClass().name # ProductClassType.Futures -> Futures self.instruments[inst.InstrumentID] = inst def _OnRspQryPosition(self, pInvestorPosition: CThostFtdcInvestorPositionField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" if pInvestorPosition.getInstrumentID() != '': # 偶尔出现NULL的数据导致数据转换错误 self._posi.append(pInvestorPosition) # Struct(**f.__dict__)) #dict -> object if bIsLast: # 先排序再group才有效 self._posi = sorted(self._posi, key=lambda c: '{0}_{1}'.format(c.getInstrumentID(), DirectType.Buy if c.getPosiDirection() == TThostFtdcPosiDirectionType.THOST_FTDC_PD_Long else DirectType.Sell)) # direction需从posidiction转换为dictiontype for key, group in itertools.groupby(self._posi, lambda c: '{0}_{1}'.format(c.getInstrumentID(), 'Buy' if c.getPosiDirection() == TThostFtdcPosiDirectionType.THOST_FTDC_PD_Long else 'Sell')): pf = self.positions.get(key) if not pf: pf = PositionField() self.positions[key] = pf pf.Position = 0 pf.TdPosition = 0 pf.YdPosition = 0 pf.CloseProfit = 0 pf.PositionProfit = 0 pf.Commission = 0 pf.Margin = 0 pf.Price = 0 cost = 0.0 for g in group: if not pf.InstrumentID: pf.InstrumentID = g.getInstrumentID() pf.Direction = DirectType.Buy if g.getPosiDirection() == TThostFtdcPosiDirectionType.THOST_FTDC_PD_Long else DirectType.Sell pf.Position += g.getPosition() pf.TdPosition += g.getTodayPosition() pf.YdPosition = pf.Position - pf.TdPosition pf.CloseProfit += g.getCloseProfit() pf.PositionProfit += g.getPositionProfit() pf.Commission += g.getCommission() pf.Margin += g.getUseMargin() cost += g.OpenCost # pf.Position <= 0 ? 0 : (g.Sum(n => n.PositionCost) / DicInstrumentField[pf.InstrumentID].VolumeMultiple / pf.Position); vm = self.instruments[pf.InstrumentID].VolumeMultiple pf.Price = 0 if pf.Position <= 0 else cost / vm / pf.Position self._posi.clear() def _OnRspQryPositionDetail(self, pInvestorPositionDetail: CThostFtdcInvestorPositionDetailField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """持仓明细""" if pInvestorPositionDetail.getInstrumentID() == '': return detail = PositionDetail() detail.Instrument = pInvestorPositionDetail.getInstrumentID() detail.CloseProfit = pInvestorPositionDetail.getCloseProfitByTrade() detail.Direction = DirectType.Buy if pInvestorPositionDetail.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell detail.HedgeFlag = HedgeType(list(TThostFtdcHedgeFlagType).index(pInvestorPositionDetail.getHedgeFlag())) detail.OpenDate = pInvestorPositionDetail.getOpenDate() detail.PositionProfit = pInvestorPositionDetail.getPositionProfitByTrade() detail.OpenPrice = pInvestorPositionDetail.getOpenPrice() detail.TradeType = TradeTypeType(list(TThostFtdcTradeTypeType).index(pInvestorPositionDetail.getTradeType())) detail.Volume = pInvestorPositionDetail.getVolume() self.position_details[pInvestorPositionDetail.getTradeID()] = detail def _OnRspQryAccount(self, pTradingAccount: CThostFtdcTradingAccountField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" if not self.account: self.account = TradingAccount() self.account.Available = pTradingAccount.getAvailable() self.account.CloseProfit = pTradingAccount.getCloseProfit() self.account.Commission = pTradingAccount.getCommission() self.account.CurrMargin = pTradingAccount.getCurrMargin() self.account.FrozenCash = pTradingAccount.getFrozenCash() self.account.PositionProfit = pTradingAccount.getPositionProfit() self.account.PreBalance = pTradingAccount.getPreBalance() + pTradingAccount.getDeposit() + pTradingAccount.getWithdraw() self.account.Fund = self.account.PreBalance + pTradingAccount.getCloseProfit() + pTradingAccount.getPositionProfit() - pTradingAccount.getCommission() self.account.Risk = 0 if self.account.Fund == 0 else self.account.CurrMargin / self.account.Fund def _OnRtnOrder(self, pOrder: CThostFtdcOrderField): """""" id = '{0}|{1}|{2}'.format(pOrder.getSessionID(), pOrder.getFrontID(), pOrder.getOrderRef()) of = self.orders.get(id) if not of: of = OrderField() if pOrder.getOrderRef().isdigit(): of.Custom = int(pOrder.getOrderRef()) % 1000000 of.InstrumentID = pOrder.getInstrumentID() of.InsertTime = pOrder.getInsertTime() of.Direction = DirectType.Buy if pOrder.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell ot = TThostFtdcOffsetFlagType(ord(pOrder.getCombOffsetFlag()[0])) of.Offset = OffsetType.Open if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open else OffsetType.CloseToday if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_CloseToday else OffsetType.Close of.Status = OrderStatus.Normal of.StatusMsg = pOrder.getStatusMsg() of.IsLocal = pOrder.getSessionID() == self.session of.LimitPrice = pOrder.getLimitPrice() of.OrderID = id of.Volume = pOrder.getVolumeTotalOriginal() of.VolumeLeft = of.Volume self.orders[id] = of threading.Thread(target=self.OnOrder, args=(self, of)).start() elif pOrder.getOrderStatus() == TThostFtdcOrderStatusType.THOST_FTDC_OST_Canceled: of.Status = OrderStatus.Canceled of.StatusMsg = pOrder.getStatusMsg() if of.StatusMsg.find('被拒绝') >= 0: info = InfoField() info.ErrorID = -1 info.ErrorMsg = of.StatusMsg threading.Thread(target=self.OnErrOrder, args=(self, of, info)).start() else: threading.Thread(target=self.OnCancel, args=(self, of)).start() else: if pOrder.getOrderSysID(): of.SysID = pOrder.getOrderSysID() self._orderid_sysid[pOrder.getOrderSysID()] = id # 记录sysid与orderid关联,方便Trade时查找处理 def _OnRtnTrade(self, f): """""" tf = TradeField() tf.Direction = DirectType.Buy if f.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell tf.ExchangeID = f.getExchangeID() tf.InstrumentID = f.getInstrumentID() tf.Offset = OffsetType.Open if f.getOffsetFlag() == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open else OffsetType.Close if f.getOffsetFlag() == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Close else OffsetType.CloseToday tf.Price = f.getPrice() tf.SysID = f.getOrderSysID() tf.TradeID = f.getTradeID() tf.TradeTime = f.getTradeTime() tf.TradingDay = f.getTradingDay() tf.Volume = f.getVolume() self.trades[tf.TradeID] = tf id = self._orderid_sysid[tf.SysID] of = self.orders[id] tf.OrderID = id # tradeid 与 orderid 关联 of.TradeTime = tf.TradeTime of.AvgPrice = (of.AvgPrice * (of.Volume - of.VolumeLeft) + tf.Price * tf.Volume) / (of.Volume - of.VolumeLeft + tf.Volume) of.TradeVolume = tf.Volume of.VolumeLeft -= tf.Volume if of.VolumeLeft == 0: of.Status = OrderStatus.Filled of.StatusMsg = '全部成交' else: of.Status = OrderStatus.Partial of.StatusMsg = '部分成交' # 更新持仓 ***** if tf.Offset == OffsetType.Open: key = '{0}_{1}'.format(tf.InstrumentID, 'Buy' if tf.Direction == DirectType.Buy else 'Sell') pf = self.positions.get(key) if not pf: pf = PositionField() self.positions[key] = pf pf.InstrumentID = tf.InstrumentID pf.Direction = tf.Direction pf.Price = (pf.Price * pf.Position + tf.Price * tf.Volume) / (pf.Position + tf.Volume) pf.TdPosition += tf.Volume pf.Position += tf.Volume else: key = '{0}_{1}'.format(tf.InstrumentID, DirectType.Sell if tf.Direction == DirectType.Buy else DirectType.Buy) pf = self.positions.get(key) if pf: # 有可能出现无持仓的情况 if tf.Offset == OffsetType.CloseToday: pf.TdPosition -= tf.Volume else: tdclose = min(pf.TdPosition, tf.Volume) if pf.TdPosition > 0: pf.TdPosition -= tdclose pf.YdPosition -= max(0, tf.Volume - tdclose) pf.Position -= tf.Volume threading.Thread(target=self._onRtn, args=(of, tf)).start() def _onRtn(self, of, tf): self.OnOrder(self, of) self.OnTrade(self, tf) def _OnRspOrder(self, pInputOrder: CThostFtdcInputOrderField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() id = '{0}|{1}|{2}'.format(self.session, '0', pInputOrder.getOrderRef()) of = self.orders.get(id) if not of: of = OrderField() l = int(pInputOrder.getOrderRef()) of.Custom = l % 1000000 of.InstrumentID = pInputOrder.getInstrumentID() of.InsertTime = time.strftime('%H:%M:%S', time.localtime()) # 对direction需特别处理(具体见ctp_struct) of.Direction = DirectType.Buy if pInputOrder.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell ot = TThostFtdcOffsetFlagType(ord(pInputOrder.getCombOffsetFlag()[0])) of.Offset = OffsetType.Open if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open else OffsetType.CloseToday if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_CloseToday else OffsetType.Close # of.Status = OrderStatus.Normal # of.StatusMsg = f.getStatusMsg() of.IsLocal = True of.LimitPrice = pInputOrder.getLimitPrice() of.OrderID = id of.Volume = pInputOrder.getVolumeTotalOriginal() of.VolumeLeft = of.Volume self.orders[id] = of of.Status = OrderStatus.Error of.StatusMsg = '{0}:{1}'.format(info.ErrorID, info.ErrorMsg) threading.Thread(target=self.OnErrOrder, args=(self, of, info)).start() def _OnErrOrder(self, pInputOrder: CThostFtdcInputOrderField, pRspInfo: CThostFtdcRspInfoField): """""" id = '{0}|{1}|{2}'.format(self.session, '0', pInputOrder.getOrderRef()) of = self.orders.get(id) info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() if of and of.IsLocal: of.Status = OrderStatus.Error of.StatusMsg = '{0}:{1}'.format(pRspInfo.getErrorID(), pRspInfo.getErrorMsg()) threading.Thread(target=self.OnErrOrder, args=(self, of, info)).start() def _OnRspOrderAction(self, pInputOrderAction: CThostFtdcInputOrderActionField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): id = "{0}|{1}|{2}".format(pInputOrderAction.getSessionID(), pInputOrderAction.getFrontID(), pInputOrderAction.getOrderRef()) if self.logined and id in self.orders: info = InfoField() info.ErrorID = pRspInfo.ErrorID info.ErrorMsg = pRspInfo.ErrorMsg threading.Thread(target=self.OnErrCancel, args=(self, self.orders[id], info)).start() def _OnRtnNotice(self, pTradingNoticeInfo: CThostFtdcTradingNoticeInfoField): '''交易提醒''' msg = pTradingNoticeInfo.getFieldContent() if len(msg) > 0: threading.Thread(target=self.OnRtnNotice, args=(self, pTradingNoticeInfo.getSendTime(), msg)).start() def _OnRtnQuote(self, pQuote: CThostFtdcQuoteField): threading.Thread(target=self.OnRtnQuote, args=(self, pQuote)).start() def _OnErrRtnQuote(self, pInputQuote: CThostFtdcInputQuoteField, pRspInfo: CThostFtdcRspInfoField): info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() threading.Thread(target=self.OnErrRtnQuote, args=(self, pInputQuote, info)).start() def _OnErrForQuoteInsert(self, pInputForQuote: CThostFtdcInputForQuoteField, pRspInfo: CThostFtdcRspInfoField): info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() threading.Thread(target=self.OnErrRtnForQuoteInsert, args=(self, pInputForQuote, info)).start() # self.t.Join() def ReqUserLogin(self, user: str, pwd: str, broker: str): """登录 :param user: :param pwd: :param broker: """ self.broker = broker self.investor = user self.password = pwd self.t.ReqUserLogin(BrokerID=broker, UserID=user, Password=pwd) def ReqOrderInsert(self, pInstrument: str, pDirection: DirectType, pOffset: OffsetType, pPrice: float = 0.0, pVolume: int = 1, pType: OrderType = OrderType.Limit, pCustom: int = 0): """委托 :param pInstrument: :param pDirection: :param pOffset: :param pPrice: :param pVolume: :param pType: :param pCustom: :return: """ OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_AnyPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = 0.0 VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV if pType == OrderType.Market: # 市价 OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_AnyPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = 0.0 VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV elif pType == OrderType.Limit: # 限价 OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LimitPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_GFD LimitPrice = pPrice VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV elif pType == OrderType.FAK: # FAK OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LimitPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = pPrice VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV elif pType == OrderType.FOK: # FOK OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LimitPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = pPrice VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_CV # 全部数量 self._req += 1 self.t.ReqOrderInsert( BrokerID=self.broker, InvestorID=self.investor, InstrumentID=pInstrument, OrderRef="%06d%06d" % (self._req, pCustom % 1000000), UserID=self.investor, # 此处ctp_enum与at_struct名称冲突 Direction=TThostFtdcDirectionType.THOST_FTDC_D_Buy if pDirection == DirectType.Buy else TThostFtdcDirectionType.THOST_FTDC_D_Sell, CombOffsetFlag=chr(TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open.value if pOffset == OffsetType.Open else TThostFtdcOffsetFlagType.THOST_FTDC_OF_CloseToday.value if pOffset == OffsetType.CloseToday else TThostFtdcOffsetFlagType.THOST_FTDC_OF_Close.value), CombHedgeFlag=chr(TThostFtdcHedgeFlagType.THOST_FTDC_HF_Speculation.value), IsAutoSuspend=0, ForceCloseReason=TThostFtdcForceCloseReasonType.THOST_FTDC_FCC_NotForceClose, IsSwapOrder=0, ContingentCondition=TThostFtdcContingentConditionType.THOST_FTDC_CC_Immediately, VolumeCondition=VolumeCondition, MinVolume=1, VolumeTotalOriginal=pVolume, OrderPriceType=OrderPriceType, TimeCondition=TimeCondition, LimitPrice=LimitPrice, ) def ReqOrderAction(self, OrderID: str): """撤单 :param OrderID: """ of = self.orders[OrderID] if not of: return -1 else: pOrderId = of.OrderID return self.t.ReqOrderAction( self.broker, self.investor, OrderRef=pOrderId.split('|')[2], FrontID=int(pOrderId.split('|')[1]), SessionID=int(pOrderId.split('|')[0]), InstrumentID=of.InstrumentID, ActionFlag=TThostFtdcActionFlagType.THOST_FTDC_AF_Delete) def ReqUserLogout(self): """退出接口""" self.logined = False time.sleep(3) self.t.ReqUserLogout(BrokerID=self.broker, UserID=self.investor) self.t.RegisterSpi(None) self.t.Release() threading.Thread(target=self.OnDisConnected, args=(self, 0)).start() def OnConnected(self, obj): """接口连接 :param obj: """ print('=== [TRADE] OnConnected ==='.format('')) def OnDisConnected(self, obj, reason: int): """接口断开 :param obj: :param reason: """ print('=== [TRADE] OnDisConnected === \nreason: {0}'.format(reason)) def OnUserLogin(self, obj, info: InfoField): """登录响应 :param obj: :param info: """ print('=== [TRADE] OnUserLogin === \n{0}'.format(info)) def OnOrder(self, obj, f: OrderField): """委托响应 :param obj: :param f: """ print('=== [TRADE] OnOrder === \n{0}'.format(f.__dict__)) def OnTrade(self, obj, f: TradeField): """成交响应 :param obj: :param f: """ print('=== [TRADE] OnTrade === \n{0}'.format(f.__dict__)) def OnCancel(self, obj, f: OrderField): """ 撤单响应 :param self: :param obj: :param f:OrderField: """ print('=== [TRADE] OnCancel === \n{0}'.format(f.__dict__)) def OnErrCancel(self, obj, f: OrderField, info: InfoField): """ 撤单失败 :param self: :param obj: :param f:OrderField: :param info:InfoField: """ print('=== [TRADE] OnErrCancel ===\n{0}'.format(f.__dict__)) print(info) def OnErrOrder(self, obj, f: OrderField, info: InfoField): """ 委托错误 :param self: :param obj: :param f:OrderField: :param info:InfoField: """ print('=== [TRADE] OnErrOrder ===\n{0}'.format(f.__dict__)) print(info) def OnInstrumentStatus(self, obj, inst: str, status: InstrumentStatus): """ 交易状态 :param self: :param obj: :param inst:str: :param status:InstrumentStatus: """ print('{}:{}'.format(inst, str(status).strip().split('.')[-1])) def OnRtnNotice(self, obj, time: str, msg: str): """交易提醒 :param obj: :param time: :param msg: :return: """ print(f'=== OnRtnNotice===\n {time}:{msg}') def OnRtnQuote(self, obj, quote: CThostFtdcQuoteField): """报价通知 :param obj: :param quote: :return: """ print('=== [TRADE] OnRtnQuote ===\n{0}'.format(quote.__dict__)) def OnErrRtnQuote(self, obj, quote: CThostFtdcInputQuoteField, info: InfoField): """ :param obj: :param quote: :return: """ print('=== [TRADE] OnErrRtnQuote ===\n{0}'.format(quote.__dict__)) print(info) def OnErrRtnForQuoteInsert(self, obj, quote: CThostFtdcInputQuoteField, info: InfoField): """询价录入错误回报 :param obj: :param quote: :return: """ print('=== [TRADE] OnErrRtnForQuoteInsert ===\n{0}'.format(quote.__dict__)) print(info)
haifengat/hf_ctp_py_proxy
py_ctp/trade.py
CtpTrade.ReqUserLogin
python
def ReqUserLogin(self, user: str, pwd: str, broker: str): self.broker = broker self.investor = user self.password = pwd self.t.ReqUserLogin(BrokerID=broker, UserID=user, Password=pwd)
登录 :param user: :param pwd: :param broker:
train
https://github.com/haifengat/hf_ctp_py_proxy/blob/c2dc6dbde45aa6b097f75380474e91510d3f5d12/py_ctp/trade.py#L442-L452
null
class CtpTrade(): """""" def __init__(self): self.front_address = '' self.investor = '' self.password = '' self.broker = '' self.logined = False self.tradingday = '' self.instruments = {} self.orders = {} self.trades = {} self.account: TradingAccount = None self.positions = {} self.instrument_status = {} self._req = 0 self._session = '' self._orderid_sysid = {} self._posi = [] self.t = Trade() def _OnFrontConnected(self): threading.Thread(target=self.OnConnected, args=(self,)).start() def _OnFrontDisconnected(self, nReason): self.logined = False print(nReason) # 下午收盘后会不停断开再连接 4097错误 if nReason == 4097 or nReason == 4098: threading.Thread(target=self._reconnect).start() else: threading.Thread(target=self.OnDisConnected, args=(self, nReason)).start() def _reconnect(self): if sum([1 if stat == 'Continous' else 0 for exc, stat in self.instrument_status.items()]) == 0: print(time.strftime('%Y%m%d %H:%M:%S', time.localtime())) self.t.Release() time.sleep(600) self.ReqConnect(self.front_address) # def _OnRspUserLogout(self, pUserLogout: CThostFtdcUserLogoutField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): # pass def _OnRspUserLogin(self, pRspUserLogin: CThostFtdcRspUserLoginField(), pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" if pRspInfo.getErrorID() == 0: self.session = pRspUserLogin.getSessionID() self.tradingday = pRspUserLogin.getTradingDay() self.t.ReqSettlementInfoConfirm(self.broker, self.investor) elif self.logined: threading.Thread(target=self._relogin).start() else: info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() threading.Thread(target=self.OnUserLogin, args=(self, info)).start() def _relogin(self): # 隔夜重连=>处理'初始化'错误 time.sleep(60 * 10) self.t.ReqUserLogin( BrokerID=self.broker, UserID=self.investor, Password=self.password, UserProductInfo='@haifeng') def _OnRspSettlementInfoConfirm( self, pSettlementInfoConfirm: CThostFtdcSettlementInfoConfirmField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): if not self.logined: time.sleep(0.5) """查询合约/持仓/权益""" threading.Thread(target=self._qry).start() # 开启查询 def _qry(self): """查询帐号相关信息""" # restart 模式, 待rtnorder 处理完毕后再进行查询,否则会造成position混乱 ord_cnt = 0 trd_cnt = 0 while True: time.sleep(0.5) if len(self.orders) == ord_cnt and len(self.trades) == trd_cnt: break ord_cnt = len(self.orders) trd_cnt = len(self.trades) self.t.ReqQryInstrument() time.sleep(1.1) self.t.ReqQryInvestorPosition(self.broker, self.investor) time.sleep(1.1) self.t.ReqQryTradingAccount(self.broker, self.investor) time.sleep(1.1) self.logined = True info = InfoField() info.ErrorID = 0 info.ErrorMsg = '正确' threading.Thread(target=self.OnUserLogin, args=(self, info)).start() # 调用Release后程序异常退出,但不报错误:接口断开了仍然调用了查询指令 while self.logined: """查询持仓与权益""" self.t.ReqQryInvestorPosition(self.broker, self.investor) time.sleep(1.1) if not self.logined: return self.t.ReqQryTradingAccount(self.broker, self.investor) time.sleep(1.1) def _OnRtnInstrumentStatus(self, pInstrumentStatus: CThostFtdcInstrumentStatusField): if pInstrumentStatus.getInstrumentID() == '': return status = InstrumentStatus.Continous if pInstrumentStatus.getInstrumentStatus() == TThostFtdcInstrumentStatusType.THOST_FTDC_IS_Continous: status = InstrumentStatus.Continous elif pInstrumentStatus.getInstrumentStatus() == TThostFtdcInstrumentStatusType.THOST_FTDC_IS_Closed: status = InstrumentStatus.Closed elif str(pInstrumentStatus.getInstrumentStatus()).startswith('Auction'): status = InstrumentStatus.Auction else: status = InstrumentStatus.NoTrading self.instrument_status[pInstrumentStatus.getInstrumentID()] = status self.OnInstrumentStatus(self, pInstrumentStatus.getInstrumentID(), status) def _OnRspQryInstrument(self, pInstrument: CThostFtdcInstrumentField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" inst = InstrumentField() inst.InstrumentID = pInstrument.getInstrumentID() inst.ProductID = pInstrument.getProductID() inst.ExchangeID = pInstrument.getExchangeID() inst.VolumeMultiple = pInstrument.getVolumeMultiple() inst.PriceTick = pInstrument.getPriceTick() inst.MaxOrderVolume = pInstrument.getMaxLimitOrderVolume() inst.ProductType = pInstrument.getProductClass().name # ProductClassType.Futures -> Futures self.instruments[inst.InstrumentID] = inst def _OnRspQryPosition(self, pInvestorPosition: CThostFtdcInvestorPositionField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" if pInvestorPosition.getInstrumentID() != '': # 偶尔出现NULL的数据导致数据转换错误 self._posi.append(pInvestorPosition) # Struct(**f.__dict__)) #dict -> object if bIsLast: # 先排序再group才有效 self._posi = sorted(self._posi, key=lambda c: '{0}_{1}'.format(c.getInstrumentID(), DirectType.Buy if c.getPosiDirection() == TThostFtdcPosiDirectionType.THOST_FTDC_PD_Long else DirectType.Sell)) # direction需从posidiction转换为dictiontype for key, group in itertools.groupby(self._posi, lambda c: '{0}_{1}'.format(c.getInstrumentID(), 'Buy' if c.getPosiDirection() == TThostFtdcPosiDirectionType.THOST_FTDC_PD_Long else 'Sell')): pf = self.positions.get(key) if not pf: pf = PositionField() self.positions[key] = pf pf.Position = 0 pf.TdPosition = 0 pf.YdPosition = 0 pf.CloseProfit = 0 pf.PositionProfit = 0 pf.Commission = 0 pf.Margin = 0 pf.Price = 0 cost = 0.0 for g in group: if not pf.InstrumentID: pf.InstrumentID = g.getInstrumentID() pf.Direction = DirectType.Buy if g.getPosiDirection() == TThostFtdcPosiDirectionType.THOST_FTDC_PD_Long else DirectType.Sell pf.Position += g.getPosition() pf.TdPosition += g.getTodayPosition() pf.YdPosition = pf.Position - pf.TdPosition pf.CloseProfit += g.getCloseProfit() pf.PositionProfit += g.getPositionProfit() pf.Commission += g.getCommission() pf.Margin += g.getUseMargin() cost += g.OpenCost # pf.Position <= 0 ? 0 : (g.Sum(n => n.PositionCost) / DicInstrumentField[pf.InstrumentID].VolumeMultiple / pf.Position); vm = self.instruments[pf.InstrumentID].VolumeMultiple pf.Price = 0 if pf.Position <= 0 else cost / vm / pf.Position self._posi.clear() def _OnRspQryPositionDetail(self, pInvestorPositionDetail: CThostFtdcInvestorPositionDetailField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """持仓明细""" if pInvestorPositionDetail.getInstrumentID() == '': return detail = PositionDetail() detail.Instrument = pInvestorPositionDetail.getInstrumentID() detail.CloseProfit = pInvestorPositionDetail.getCloseProfitByTrade() detail.Direction = DirectType.Buy if pInvestorPositionDetail.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell detail.HedgeFlag = HedgeType(list(TThostFtdcHedgeFlagType).index(pInvestorPositionDetail.getHedgeFlag())) detail.OpenDate = pInvestorPositionDetail.getOpenDate() detail.PositionProfit = pInvestorPositionDetail.getPositionProfitByTrade() detail.OpenPrice = pInvestorPositionDetail.getOpenPrice() detail.TradeType = TradeTypeType(list(TThostFtdcTradeTypeType).index(pInvestorPositionDetail.getTradeType())) detail.Volume = pInvestorPositionDetail.getVolume() self.position_details[pInvestorPositionDetail.getTradeID()] = detail def _OnRspQryAccount(self, pTradingAccount: CThostFtdcTradingAccountField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" if not self.account: self.account = TradingAccount() self.account.Available = pTradingAccount.getAvailable() self.account.CloseProfit = pTradingAccount.getCloseProfit() self.account.Commission = pTradingAccount.getCommission() self.account.CurrMargin = pTradingAccount.getCurrMargin() self.account.FrozenCash = pTradingAccount.getFrozenCash() self.account.PositionProfit = pTradingAccount.getPositionProfit() self.account.PreBalance = pTradingAccount.getPreBalance() + pTradingAccount.getDeposit() + pTradingAccount.getWithdraw() self.account.Fund = self.account.PreBalance + pTradingAccount.getCloseProfit() + pTradingAccount.getPositionProfit() - pTradingAccount.getCommission() self.account.Risk = 0 if self.account.Fund == 0 else self.account.CurrMargin / self.account.Fund def _OnRtnOrder(self, pOrder: CThostFtdcOrderField): """""" id = '{0}|{1}|{2}'.format(pOrder.getSessionID(), pOrder.getFrontID(), pOrder.getOrderRef()) of = self.orders.get(id) if not of: of = OrderField() if pOrder.getOrderRef().isdigit(): of.Custom = int(pOrder.getOrderRef()) % 1000000 of.InstrumentID = pOrder.getInstrumentID() of.InsertTime = pOrder.getInsertTime() of.Direction = DirectType.Buy if pOrder.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell ot = TThostFtdcOffsetFlagType(ord(pOrder.getCombOffsetFlag()[0])) of.Offset = OffsetType.Open if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open else OffsetType.CloseToday if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_CloseToday else OffsetType.Close of.Status = OrderStatus.Normal of.StatusMsg = pOrder.getStatusMsg() of.IsLocal = pOrder.getSessionID() == self.session of.LimitPrice = pOrder.getLimitPrice() of.OrderID = id of.Volume = pOrder.getVolumeTotalOriginal() of.VolumeLeft = of.Volume self.orders[id] = of threading.Thread(target=self.OnOrder, args=(self, of)).start() elif pOrder.getOrderStatus() == TThostFtdcOrderStatusType.THOST_FTDC_OST_Canceled: of.Status = OrderStatus.Canceled of.StatusMsg = pOrder.getStatusMsg() if of.StatusMsg.find('被拒绝') >= 0: info = InfoField() info.ErrorID = -1 info.ErrorMsg = of.StatusMsg threading.Thread(target=self.OnErrOrder, args=(self, of, info)).start() else: threading.Thread(target=self.OnCancel, args=(self, of)).start() else: if pOrder.getOrderSysID(): of.SysID = pOrder.getOrderSysID() self._orderid_sysid[pOrder.getOrderSysID()] = id # 记录sysid与orderid关联,方便Trade时查找处理 def _OnRtnTrade(self, f): """""" tf = TradeField() tf.Direction = DirectType.Buy if f.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell tf.ExchangeID = f.getExchangeID() tf.InstrumentID = f.getInstrumentID() tf.Offset = OffsetType.Open if f.getOffsetFlag() == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open else OffsetType.Close if f.getOffsetFlag() == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Close else OffsetType.CloseToday tf.Price = f.getPrice() tf.SysID = f.getOrderSysID() tf.TradeID = f.getTradeID() tf.TradeTime = f.getTradeTime() tf.TradingDay = f.getTradingDay() tf.Volume = f.getVolume() self.trades[tf.TradeID] = tf id = self._orderid_sysid[tf.SysID] of = self.orders[id] tf.OrderID = id # tradeid 与 orderid 关联 of.TradeTime = tf.TradeTime of.AvgPrice = (of.AvgPrice * (of.Volume - of.VolumeLeft) + tf.Price * tf.Volume) / (of.Volume - of.VolumeLeft + tf.Volume) of.TradeVolume = tf.Volume of.VolumeLeft -= tf.Volume if of.VolumeLeft == 0: of.Status = OrderStatus.Filled of.StatusMsg = '全部成交' else: of.Status = OrderStatus.Partial of.StatusMsg = '部分成交' # 更新持仓 ***** if tf.Offset == OffsetType.Open: key = '{0}_{1}'.format(tf.InstrumentID, 'Buy' if tf.Direction == DirectType.Buy else 'Sell') pf = self.positions.get(key) if not pf: pf = PositionField() self.positions[key] = pf pf.InstrumentID = tf.InstrumentID pf.Direction = tf.Direction pf.Price = (pf.Price * pf.Position + tf.Price * tf.Volume) / (pf.Position + tf.Volume) pf.TdPosition += tf.Volume pf.Position += tf.Volume else: key = '{0}_{1}'.format(tf.InstrumentID, DirectType.Sell if tf.Direction == DirectType.Buy else DirectType.Buy) pf = self.positions.get(key) if pf: # 有可能出现无持仓的情况 if tf.Offset == OffsetType.CloseToday: pf.TdPosition -= tf.Volume else: tdclose = min(pf.TdPosition, tf.Volume) if pf.TdPosition > 0: pf.TdPosition -= tdclose pf.YdPosition -= max(0, tf.Volume - tdclose) pf.Position -= tf.Volume threading.Thread(target=self._onRtn, args=(of, tf)).start() def _onRtn(self, of, tf): self.OnOrder(self, of) self.OnTrade(self, tf) def _OnRspOrder(self, pInputOrder: CThostFtdcInputOrderField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() id = '{0}|{1}|{2}'.format(self.session, '0', pInputOrder.getOrderRef()) of = self.orders.get(id) if not of: of = OrderField() l = int(pInputOrder.getOrderRef()) of.Custom = l % 1000000 of.InstrumentID = pInputOrder.getInstrumentID() of.InsertTime = time.strftime('%H:%M:%S', time.localtime()) # 对direction需特别处理(具体见ctp_struct) of.Direction = DirectType.Buy if pInputOrder.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell ot = TThostFtdcOffsetFlagType(ord(pInputOrder.getCombOffsetFlag()[0])) of.Offset = OffsetType.Open if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open else OffsetType.CloseToday if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_CloseToday else OffsetType.Close # of.Status = OrderStatus.Normal # of.StatusMsg = f.getStatusMsg() of.IsLocal = True of.LimitPrice = pInputOrder.getLimitPrice() of.OrderID = id of.Volume = pInputOrder.getVolumeTotalOriginal() of.VolumeLeft = of.Volume self.orders[id] = of of.Status = OrderStatus.Error of.StatusMsg = '{0}:{1}'.format(info.ErrorID, info.ErrorMsg) threading.Thread(target=self.OnErrOrder, args=(self, of, info)).start() def _OnErrOrder(self, pInputOrder: CThostFtdcInputOrderField, pRspInfo: CThostFtdcRspInfoField): """""" id = '{0}|{1}|{2}'.format(self.session, '0', pInputOrder.getOrderRef()) of = self.orders.get(id) info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() if of and of.IsLocal: of.Status = OrderStatus.Error of.StatusMsg = '{0}:{1}'.format(pRspInfo.getErrorID(), pRspInfo.getErrorMsg()) threading.Thread(target=self.OnErrOrder, args=(self, of, info)).start() def _OnRspOrderAction(self, pInputOrderAction: CThostFtdcInputOrderActionField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): id = "{0}|{1}|{2}".format(pInputOrderAction.getSessionID(), pInputOrderAction.getFrontID(), pInputOrderAction.getOrderRef()) if self.logined and id in self.orders: info = InfoField() info.ErrorID = pRspInfo.ErrorID info.ErrorMsg = pRspInfo.ErrorMsg threading.Thread(target=self.OnErrCancel, args=(self, self.orders[id], info)).start() def _OnRtnNotice(self, pTradingNoticeInfo: CThostFtdcTradingNoticeInfoField): '''交易提醒''' msg = pTradingNoticeInfo.getFieldContent() if len(msg) > 0: threading.Thread(target=self.OnRtnNotice, args=(self, pTradingNoticeInfo.getSendTime(), msg)).start() def _OnRtnQuote(self, pQuote: CThostFtdcQuoteField): threading.Thread(target=self.OnRtnQuote, args=(self, pQuote)).start() def _OnErrRtnQuote(self, pInputQuote: CThostFtdcInputQuoteField, pRspInfo: CThostFtdcRspInfoField): info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() threading.Thread(target=self.OnErrRtnQuote, args=(self, pInputQuote, info)).start() def _OnErrForQuoteInsert(self, pInputForQuote: CThostFtdcInputForQuoteField, pRspInfo: CThostFtdcRspInfoField): info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() threading.Thread(target=self.OnErrRtnForQuoteInsert, args=(self, pInputForQuote, info)).start() def ReqConnect(self, front: str): """连接交易前置 :param front: """ self.t.CreateApi() spi = self.t.CreateSpi() self.t.RegisterSpi(spi) self.t.OnFrontConnected = self._OnFrontConnected self.t.OnRspUserLogin = self._OnRspUserLogin self.t.OnFrontDisconnected = self._OnFrontDisconnected # self.t.OnRspUserLogout = self._OnRspUserLogout self.t.OnRspSettlementInfoConfirm = self._OnRspSettlementInfoConfirm self.t.OnRtnOrder = self._OnRtnOrder self.t.OnRtnTrade = self._OnRtnTrade self.t.OnRspOrderInsert = self._OnRspOrder self.t.OnErrRtnOrderInsert = self._OnErrOrder self.t.OnRspOrderAction = self._OnRspOrderAction self.t.OnRtnInstrumentStatus = self._OnRtnInstrumentStatus self.t.OnRspQryInstrument = self._OnRspQryInstrument self.t.OnRspQryTradingAccount = self._OnRspQryAccount self.t.OnRspQryInvestorPosition = self._OnRspQryPosition self.t.OnRspQryInvestorPositionDetail = self._OnRspQryPositionDetail self.t.OnRtnTradingNotice = self._OnRtnNotice self.t.OnRtnQuote = self._OnRtnQuote self.t.OnErrRtnQuoteInsert = self._OnErrRtnQuote self.t.OnErrRtnForQuoteInsert = self._OnErrForQuoteInsert self.front_address = front self.t.RegCB() self.t.RegisterFront(front) self.t.SubscribePrivateTopic(0) # restart 同步处理order trade self.t.SubscribePublicTopic(0) self.t.Init() # self.t.Join() def ReqOrderInsert(self, pInstrument: str, pDirection: DirectType, pOffset: OffsetType, pPrice: float = 0.0, pVolume: int = 1, pType: OrderType = OrderType.Limit, pCustom: int = 0): """委托 :param pInstrument: :param pDirection: :param pOffset: :param pPrice: :param pVolume: :param pType: :param pCustom: :return: """ OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_AnyPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = 0.0 VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV if pType == OrderType.Market: # 市价 OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_AnyPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = 0.0 VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV elif pType == OrderType.Limit: # 限价 OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LimitPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_GFD LimitPrice = pPrice VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV elif pType == OrderType.FAK: # FAK OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LimitPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = pPrice VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV elif pType == OrderType.FOK: # FOK OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LimitPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = pPrice VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_CV # 全部数量 self._req += 1 self.t.ReqOrderInsert( BrokerID=self.broker, InvestorID=self.investor, InstrumentID=pInstrument, OrderRef="%06d%06d" % (self._req, pCustom % 1000000), UserID=self.investor, # 此处ctp_enum与at_struct名称冲突 Direction=TThostFtdcDirectionType.THOST_FTDC_D_Buy if pDirection == DirectType.Buy else TThostFtdcDirectionType.THOST_FTDC_D_Sell, CombOffsetFlag=chr(TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open.value if pOffset == OffsetType.Open else TThostFtdcOffsetFlagType.THOST_FTDC_OF_CloseToday.value if pOffset == OffsetType.CloseToday else TThostFtdcOffsetFlagType.THOST_FTDC_OF_Close.value), CombHedgeFlag=chr(TThostFtdcHedgeFlagType.THOST_FTDC_HF_Speculation.value), IsAutoSuspend=0, ForceCloseReason=TThostFtdcForceCloseReasonType.THOST_FTDC_FCC_NotForceClose, IsSwapOrder=0, ContingentCondition=TThostFtdcContingentConditionType.THOST_FTDC_CC_Immediately, VolumeCondition=VolumeCondition, MinVolume=1, VolumeTotalOriginal=pVolume, OrderPriceType=OrderPriceType, TimeCondition=TimeCondition, LimitPrice=LimitPrice, ) def ReqOrderAction(self, OrderID: str): """撤单 :param OrderID: """ of = self.orders[OrderID] if not of: return -1 else: pOrderId = of.OrderID return self.t.ReqOrderAction( self.broker, self.investor, OrderRef=pOrderId.split('|')[2], FrontID=int(pOrderId.split('|')[1]), SessionID=int(pOrderId.split('|')[0]), InstrumentID=of.InstrumentID, ActionFlag=TThostFtdcActionFlagType.THOST_FTDC_AF_Delete) def ReqUserLogout(self): """退出接口""" self.logined = False time.sleep(3) self.t.ReqUserLogout(BrokerID=self.broker, UserID=self.investor) self.t.RegisterSpi(None) self.t.Release() threading.Thread(target=self.OnDisConnected, args=(self, 0)).start() def OnConnected(self, obj): """接口连接 :param obj: """ print('=== [TRADE] OnConnected ==='.format('')) def OnDisConnected(self, obj, reason: int): """接口断开 :param obj: :param reason: """ print('=== [TRADE] OnDisConnected === \nreason: {0}'.format(reason)) def OnUserLogin(self, obj, info: InfoField): """登录响应 :param obj: :param info: """ print('=== [TRADE] OnUserLogin === \n{0}'.format(info)) def OnOrder(self, obj, f: OrderField): """委托响应 :param obj: :param f: """ print('=== [TRADE] OnOrder === \n{0}'.format(f.__dict__)) def OnTrade(self, obj, f: TradeField): """成交响应 :param obj: :param f: """ print('=== [TRADE] OnTrade === \n{0}'.format(f.__dict__)) def OnCancel(self, obj, f: OrderField): """ 撤单响应 :param self: :param obj: :param f:OrderField: """ print('=== [TRADE] OnCancel === \n{0}'.format(f.__dict__)) def OnErrCancel(self, obj, f: OrderField, info: InfoField): """ 撤单失败 :param self: :param obj: :param f:OrderField: :param info:InfoField: """ print('=== [TRADE] OnErrCancel ===\n{0}'.format(f.__dict__)) print(info) def OnErrOrder(self, obj, f: OrderField, info: InfoField): """ 委托错误 :param self: :param obj: :param f:OrderField: :param info:InfoField: """ print('=== [TRADE] OnErrOrder ===\n{0}'.format(f.__dict__)) print(info) def OnInstrumentStatus(self, obj, inst: str, status: InstrumentStatus): """ 交易状态 :param self: :param obj: :param inst:str: :param status:InstrumentStatus: """ print('{}:{}'.format(inst, str(status).strip().split('.')[-1])) def OnRtnNotice(self, obj, time: str, msg: str): """交易提醒 :param obj: :param time: :param msg: :return: """ print(f'=== OnRtnNotice===\n {time}:{msg}') def OnRtnQuote(self, obj, quote: CThostFtdcQuoteField): """报价通知 :param obj: :param quote: :return: """ print('=== [TRADE] OnRtnQuote ===\n{0}'.format(quote.__dict__)) def OnErrRtnQuote(self, obj, quote: CThostFtdcInputQuoteField, info: InfoField): """ :param obj: :param quote: :return: """ print('=== [TRADE] OnErrRtnQuote ===\n{0}'.format(quote.__dict__)) print(info) def OnErrRtnForQuoteInsert(self, obj, quote: CThostFtdcInputQuoteField, info: InfoField): """询价录入错误回报 :param obj: :param quote: :return: """ print('=== [TRADE] OnErrRtnForQuoteInsert ===\n{0}'.format(quote.__dict__)) print(info)
haifengat/hf_ctp_py_proxy
py_ctp/trade.py
CtpTrade.ReqOrderInsert
python
def ReqOrderInsert(self, pInstrument: str, pDirection: DirectType, pOffset: OffsetType, pPrice: float = 0.0, pVolume: int = 1, pType: OrderType = OrderType.Limit, pCustom: int = 0): OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_AnyPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = 0.0 VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV if pType == OrderType.Market: # 市价 OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_AnyPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = 0.0 VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV elif pType == OrderType.Limit: # 限价 OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LimitPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_GFD LimitPrice = pPrice VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV elif pType == OrderType.FAK: # FAK OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LimitPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = pPrice VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV elif pType == OrderType.FOK: # FOK OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LimitPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = pPrice VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_CV # 全部数量 self._req += 1 self.t.ReqOrderInsert( BrokerID=self.broker, InvestorID=self.investor, InstrumentID=pInstrument, OrderRef="%06d%06d" % (self._req, pCustom % 1000000), UserID=self.investor, # 此处ctp_enum与at_struct名称冲突 Direction=TThostFtdcDirectionType.THOST_FTDC_D_Buy if pDirection == DirectType.Buy else TThostFtdcDirectionType.THOST_FTDC_D_Sell, CombOffsetFlag=chr(TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open.value if pOffset == OffsetType.Open else TThostFtdcOffsetFlagType.THOST_FTDC_OF_CloseToday.value if pOffset == OffsetType.CloseToday else TThostFtdcOffsetFlagType.THOST_FTDC_OF_Close.value), CombHedgeFlag=chr(TThostFtdcHedgeFlagType.THOST_FTDC_HF_Speculation.value), IsAutoSuspend=0, ForceCloseReason=TThostFtdcForceCloseReasonType.THOST_FTDC_FCC_NotForceClose, IsSwapOrder=0, ContingentCondition=TThostFtdcContingentConditionType.THOST_FTDC_CC_Immediately, VolumeCondition=VolumeCondition, MinVolume=1, VolumeTotalOriginal=pVolume, OrderPriceType=OrderPriceType, TimeCondition=TimeCondition, LimitPrice=LimitPrice, )
委托 :param pInstrument: :param pDirection: :param pOffset: :param pPrice: :param pVolume: :param pType: :param pCustom: :return:
train
https://github.com/haifengat/hf_ctp_py_proxy/blob/c2dc6dbde45aa6b097f75380474e91510d3f5d12/py_ctp/trade.py#L454-L513
null
class CtpTrade(): """""" def __init__(self): self.front_address = '' self.investor = '' self.password = '' self.broker = '' self.logined = False self.tradingday = '' self.instruments = {} self.orders = {} self.trades = {} self.account: TradingAccount = None self.positions = {} self.instrument_status = {} self._req = 0 self._session = '' self._orderid_sysid = {} self._posi = [] self.t = Trade() def _OnFrontConnected(self): threading.Thread(target=self.OnConnected, args=(self,)).start() def _OnFrontDisconnected(self, nReason): self.logined = False print(nReason) # 下午收盘后会不停断开再连接 4097错误 if nReason == 4097 or nReason == 4098: threading.Thread(target=self._reconnect).start() else: threading.Thread(target=self.OnDisConnected, args=(self, nReason)).start() def _reconnect(self): if sum([1 if stat == 'Continous' else 0 for exc, stat in self.instrument_status.items()]) == 0: print(time.strftime('%Y%m%d %H:%M:%S', time.localtime())) self.t.Release() time.sleep(600) self.ReqConnect(self.front_address) # def _OnRspUserLogout(self, pUserLogout: CThostFtdcUserLogoutField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): # pass def _OnRspUserLogin(self, pRspUserLogin: CThostFtdcRspUserLoginField(), pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" if pRspInfo.getErrorID() == 0: self.session = pRspUserLogin.getSessionID() self.tradingday = pRspUserLogin.getTradingDay() self.t.ReqSettlementInfoConfirm(self.broker, self.investor) elif self.logined: threading.Thread(target=self._relogin).start() else: info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() threading.Thread(target=self.OnUserLogin, args=(self, info)).start() def _relogin(self): # 隔夜重连=>处理'初始化'错误 time.sleep(60 * 10) self.t.ReqUserLogin( BrokerID=self.broker, UserID=self.investor, Password=self.password, UserProductInfo='@haifeng') def _OnRspSettlementInfoConfirm( self, pSettlementInfoConfirm: CThostFtdcSettlementInfoConfirmField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): if not self.logined: time.sleep(0.5) """查询合约/持仓/权益""" threading.Thread(target=self._qry).start() # 开启查询 def _qry(self): """查询帐号相关信息""" # restart 模式, 待rtnorder 处理完毕后再进行查询,否则会造成position混乱 ord_cnt = 0 trd_cnt = 0 while True: time.sleep(0.5) if len(self.orders) == ord_cnt and len(self.trades) == trd_cnt: break ord_cnt = len(self.orders) trd_cnt = len(self.trades) self.t.ReqQryInstrument() time.sleep(1.1) self.t.ReqQryInvestorPosition(self.broker, self.investor) time.sleep(1.1) self.t.ReqQryTradingAccount(self.broker, self.investor) time.sleep(1.1) self.logined = True info = InfoField() info.ErrorID = 0 info.ErrorMsg = '正确' threading.Thread(target=self.OnUserLogin, args=(self, info)).start() # 调用Release后程序异常退出,但不报错误:接口断开了仍然调用了查询指令 while self.logined: """查询持仓与权益""" self.t.ReqQryInvestorPosition(self.broker, self.investor) time.sleep(1.1) if not self.logined: return self.t.ReqQryTradingAccount(self.broker, self.investor) time.sleep(1.1) def _OnRtnInstrumentStatus(self, pInstrumentStatus: CThostFtdcInstrumentStatusField): if pInstrumentStatus.getInstrumentID() == '': return status = InstrumentStatus.Continous if pInstrumentStatus.getInstrumentStatus() == TThostFtdcInstrumentStatusType.THOST_FTDC_IS_Continous: status = InstrumentStatus.Continous elif pInstrumentStatus.getInstrumentStatus() == TThostFtdcInstrumentStatusType.THOST_FTDC_IS_Closed: status = InstrumentStatus.Closed elif str(pInstrumentStatus.getInstrumentStatus()).startswith('Auction'): status = InstrumentStatus.Auction else: status = InstrumentStatus.NoTrading self.instrument_status[pInstrumentStatus.getInstrumentID()] = status self.OnInstrumentStatus(self, pInstrumentStatus.getInstrumentID(), status) def _OnRspQryInstrument(self, pInstrument: CThostFtdcInstrumentField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" inst = InstrumentField() inst.InstrumentID = pInstrument.getInstrumentID() inst.ProductID = pInstrument.getProductID() inst.ExchangeID = pInstrument.getExchangeID() inst.VolumeMultiple = pInstrument.getVolumeMultiple() inst.PriceTick = pInstrument.getPriceTick() inst.MaxOrderVolume = pInstrument.getMaxLimitOrderVolume() inst.ProductType = pInstrument.getProductClass().name # ProductClassType.Futures -> Futures self.instruments[inst.InstrumentID] = inst def _OnRspQryPosition(self, pInvestorPosition: CThostFtdcInvestorPositionField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" if pInvestorPosition.getInstrumentID() != '': # 偶尔出现NULL的数据导致数据转换错误 self._posi.append(pInvestorPosition) # Struct(**f.__dict__)) #dict -> object if bIsLast: # 先排序再group才有效 self._posi = sorted(self._posi, key=lambda c: '{0}_{1}'.format(c.getInstrumentID(), DirectType.Buy if c.getPosiDirection() == TThostFtdcPosiDirectionType.THOST_FTDC_PD_Long else DirectType.Sell)) # direction需从posidiction转换为dictiontype for key, group in itertools.groupby(self._posi, lambda c: '{0}_{1}'.format(c.getInstrumentID(), 'Buy' if c.getPosiDirection() == TThostFtdcPosiDirectionType.THOST_FTDC_PD_Long else 'Sell')): pf = self.positions.get(key) if not pf: pf = PositionField() self.positions[key] = pf pf.Position = 0 pf.TdPosition = 0 pf.YdPosition = 0 pf.CloseProfit = 0 pf.PositionProfit = 0 pf.Commission = 0 pf.Margin = 0 pf.Price = 0 cost = 0.0 for g in group: if not pf.InstrumentID: pf.InstrumentID = g.getInstrumentID() pf.Direction = DirectType.Buy if g.getPosiDirection() == TThostFtdcPosiDirectionType.THOST_FTDC_PD_Long else DirectType.Sell pf.Position += g.getPosition() pf.TdPosition += g.getTodayPosition() pf.YdPosition = pf.Position - pf.TdPosition pf.CloseProfit += g.getCloseProfit() pf.PositionProfit += g.getPositionProfit() pf.Commission += g.getCommission() pf.Margin += g.getUseMargin() cost += g.OpenCost # pf.Position <= 0 ? 0 : (g.Sum(n => n.PositionCost) / DicInstrumentField[pf.InstrumentID].VolumeMultiple / pf.Position); vm = self.instruments[pf.InstrumentID].VolumeMultiple pf.Price = 0 if pf.Position <= 0 else cost / vm / pf.Position self._posi.clear() def _OnRspQryPositionDetail(self, pInvestorPositionDetail: CThostFtdcInvestorPositionDetailField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """持仓明细""" if pInvestorPositionDetail.getInstrumentID() == '': return detail = PositionDetail() detail.Instrument = pInvestorPositionDetail.getInstrumentID() detail.CloseProfit = pInvestorPositionDetail.getCloseProfitByTrade() detail.Direction = DirectType.Buy if pInvestorPositionDetail.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell detail.HedgeFlag = HedgeType(list(TThostFtdcHedgeFlagType).index(pInvestorPositionDetail.getHedgeFlag())) detail.OpenDate = pInvestorPositionDetail.getOpenDate() detail.PositionProfit = pInvestorPositionDetail.getPositionProfitByTrade() detail.OpenPrice = pInvestorPositionDetail.getOpenPrice() detail.TradeType = TradeTypeType(list(TThostFtdcTradeTypeType).index(pInvestorPositionDetail.getTradeType())) detail.Volume = pInvestorPositionDetail.getVolume() self.position_details[pInvestorPositionDetail.getTradeID()] = detail def _OnRspQryAccount(self, pTradingAccount: CThostFtdcTradingAccountField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" if not self.account: self.account = TradingAccount() self.account.Available = pTradingAccount.getAvailable() self.account.CloseProfit = pTradingAccount.getCloseProfit() self.account.Commission = pTradingAccount.getCommission() self.account.CurrMargin = pTradingAccount.getCurrMargin() self.account.FrozenCash = pTradingAccount.getFrozenCash() self.account.PositionProfit = pTradingAccount.getPositionProfit() self.account.PreBalance = pTradingAccount.getPreBalance() + pTradingAccount.getDeposit() + pTradingAccount.getWithdraw() self.account.Fund = self.account.PreBalance + pTradingAccount.getCloseProfit() + pTradingAccount.getPositionProfit() - pTradingAccount.getCommission() self.account.Risk = 0 if self.account.Fund == 0 else self.account.CurrMargin / self.account.Fund def _OnRtnOrder(self, pOrder: CThostFtdcOrderField): """""" id = '{0}|{1}|{2}'.format(pOrder.getSessionID(), pOrder.getFrontID(), pOrder.getOrderRef()) of = self.orders.get(id) if not of: of = OrderField() if pOrder.getOrderRef().isdigit(): of.Custom = int(pOrder.getOrderRef()) % 1000000 of.InstrumentID = pOrder.getInstrumentID() of.InsertTime = pOrder.getInsertTime() of.Direction = DirectType.Buy if pOrder.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell ot = TThostFtdcOffsetFlagType(ord(pOrder.getCombOffsetFlag()[0])) of.Offset = OffsetType.Open if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open else OffsetType.CloseToday if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_CloseToday else OffsetType.Close of.Status = OrderStatus.Normal of.StatusMsg = pOrder.getStatusMsg() of.IsLocal = pOrder.getSessionID() == self.session of.LimitPrice = pOrder.getLimitPrice() of.OrderID = id of.Volume = pOrder.getVolumeTotalOriginal() of.VolumeLeft = of.Volume self.orders[id] = of threading.Thread(target=self.OnOrder, args=(self, of)).start() elif pOrder.getOrderStatus() == TThostFtdcOrderStatusType.THOST_FTDC_OST_Canceled: of.Status = OrderStatus.Canceled of.StatusMsg = pOrder.getStatusMsg() if of.StatusMsg.find('被拒绝') >= 0: info = InfoField() info.ErrorID = -1 info.ErrorMsg = of.StatusMsg threading.Thread(target=self.OnErrOrder, args=(self, of, info)).start() else: threading.Thread(target=self.OnCancel, args=(self, of)).start() else: if pOrder.getOrderSysID(): of.SysID = pOrder.getOrderSysID() self._orderid_sysid[pOrder.getOrderSysID()] = id # 记录sysid与orderid关联,方便Trade时查找处理 def _OnRtnTrade(self, f): """""" tf = TradeField() tf.Direction = DirectType.Buy if f.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell tf.ExchangeID = f.getExchangeID() tf.InstrumentID = f.getInstrumentID() tf.Offset = OffsetType.Open if f.getOffsetFlag() == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open else OffsetType.Close if f.getOffsetFlag() == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Close else OffsetType.CloseToday tf.Price = f.getPrice() tf.SysID = f.getOrderSysID() tf.TradeID = f.getTradeID() tf.TradeTime = f.getTradeTime() tf.TradingDay = f.getTradingDay() tf.Volume = f.getVolume() self.trades[tf.TradeID] = tf id = self._orderid_sysid[tf.SysID] of = self.orders[id] tf.OrderID = id # tradeid 与 orderid 关联 of.TradeTime = tf.TradeTime of.AvgPrice = (of.AvgPrice * (of.Volume - of.VolumeLeft) + tf.Price * tf.Volume) / (of.Volume - of.VolumeLeft + tf.Volume) of.TradeVolume = tf.Volume of.VolumeLeft -= tf.Volume if of.VolumeLeft == 0: of.Status = OrderStatus.Filled of.StatusMsg = '全部成交' else: of.Status = OrderStatus.Partial of.StatusMsg = '部分成交' # 更新持仓 ***** if tf.Offset == OffsetType.Open: key = '{0}_{1}'.format(tf.InstrumentID, 'Buy' if tf.Direction == DirectType.Buy else 'Sell') pf = self.positions.get(key) if not pf: pf = PositionField() self.positions[key] = pf pf.InstrumentID = tf.InstrumentID pf.Direction = tf.Direction pf.Price = (pf.Price * pf.Position + tf.Price * tf.Volume) / (pf.Position + tf.Volume) pf.TdPosition += tf.Volume pf.Position += tf.Volume else: key = '{0}_{1}'.format(tf.InstrumentID, DirectType.Sell if tf.Direction == DirectType.Buy else DirectType.Buy) pf = self.positions.get(key) if pf: # 有可能出现无持仓的情况 if tf.Offset == OffsetType.CloseToday: pf.TdPosition -= tf.Volume else: tdclose = min(pf.TdPosition, tf.Volume) if pf.TdPosition > 0: pf.TdPosition -= tdclose pf.YdPosition -= max(0, tf.Volume - tdclose) pf.Position -= tf.Volume threading.Thread(target=self._onRtn, args=(of, tf)).start() def _onRtn(self, of, tf): self.OnOrder(self, of) self.OnTrade(self, tf) def _OnRspOrder(self, pInputOrder: CThostFtdcInputOrderField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() id = '{0}|{1}|{2}'.format(self.session, '0', pInputOrder.getOrderRef()) of = self.orders.get(id) if not of: of = OrderField() l = int(pInputOrder.getOrderRef()) of.Custom = l % 1000000 of.InstrumentID = pInputOrder.getInstrumentID() of.InsertTime = time.strftime('%H:%M:%S', time.localtime()) # 对direction需特别处理(具体见ctp_struct) of.Direction = DirectType.Buy if pInputOrder.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell ot = TThostFtdcOffsetFlagType(ord(pInputOrder.getCombOffsetFlag()[0])) of.Offset = OffsetType.Open if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open else OffsetType.CloseToday if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_CloseToday else OffsetType.Close # of.Status = OrderStatus.Normal # of.StatusMsg = f.getStatusMsg() of.IsLocal = True of.LimitPrice = pInputOrder.getLimitPrice() of.OrderID = id of.Volume = pInputOrder.getVolumeTotalOriginal() of.VolumeLeft = of.Volume self.orders[id] = of of.Status = OrderStatus.Error of.StatusMsg = '{0}:{1}'.format(info.ErrorID, info.ErrorMsg) threading.Thread(target=self.OnErrOrder, args=(self, of, info)).start() def _OnErrOrder(self, pInputOrder: CThostFtdcInputOrderField, pRspInfo: CThostFtdcRspInfoField): """""" id = '{0}|{1}|{2}'.format(self.session, '0', pInputOrder.getOrderRef()) of = self.orders.get(id) info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() if of and of.IsLocal: of.Status = OrderStatus.Error of.StatusMsg = '{0}:{1}'.format(pRspInfo.getErrorID(), pRspInfo.getErrorMsg()) threading.Thread(target=self.OnErrOrder, args=(self, of, info)).start() def _OnRspOrderAction(self, pInputOrderAction: CThostFtdcInputOrderActionField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): id = "{0}|{1}|{2}".format(pInputOrderAction.getSessionID(), pInputOrderAction.getFrontID(), pInputOrderAction.getOrderRef()) if self.logined and id in self.orders: info = InfoField() info.ErrorID = pRspInfo.ErrorID info.ErrorMsg = pRspInfo.ErrorMsg threading.Thread(target=self.OnErrCancel, args=(self, self.orders[id], info)).start() def _OnRtnNotice(self, pTradingNoticeInfo: CThostFtdcTradingNoticeInfoField): '''交易提醒''' msg = pTradingNoticeInfo.getFieldContent() if len(msg) > 0: threading.Thread(target=self.OnRtnNotice, args=(self, pTradingNoticeInfo.getSendTime(), msg)).start() def _OnRtnQuote(self, pQuote: CThostFtdcQuoteField): threading.Thread(target=self.OnRtnQuote, args=(self, pQuote)).start() def _OnErrRtnQuote(self, pInputQuote: CThostFtdcInputQuoteField, pRspInfo: CThostFtdcRspInfoField): info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() threading.Thread(target=self.OnErrRtnQuote, args=(self, pInputQuote, info)).start() def _OnErrForQuoteInsert(self, pInputForQuote: CThostFtdcInputForQuoteField, pRspInfo: CThostFtdcRspInfoField): info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() threading.Thread(target=self.OnErrRtnForQuoteInsert, args=(self, pInputForQuote, info)).start() def ReqConnect(self, front: str): """连接交易前置 :param front: """ self.t.CreateApi() spi = self.t.CreateSpi() self.t.RegisterSpi(spi) self.t.OnFrontConnected = self._OnFrontConnected self.t.OnRspUserLogin = self._OnRspUserLogin self.t.OnFrontDisconnected = self._OnFrontDisconnected # self.t.OnRspUserLogout = self._OnRspUserLogout self.t.OnRspSettlementInfoConfirm = self._OnRspSettlementInfoConfirm self.t.OnRtnOrder = self._OnRtnOrder self.t.OnRtnTrade = self._OnRtnTrade self.t.OnRspOrderInsert = self._OnRspOrder self.t.OnErrRtnOrderInsert = self._OnErrOrder self.t.OnRspOrderAction = self._OnRspOrderAction self.t.OnRtnInstrumentStatus = self._OnRtnInstrumentStatus self.t.OnRspQryInstrument = self._OnRspQryInstrument self.t.OnRspQryTradingAccount = self._OnRspQryAccount self.t.OnRspQryInvestorPosition = self._OnRspQryPosition self.t.OnRspQryInvestorPositionDetail = self._OnRspQryPositionDetail self.t.OnRtnTradingNotice = self._OnRtnNotice self.t.OnRtnQuote = self._OnRtnQuote self.t.OnErrRtnQuoteInsert = self._OnErrRtnQuote self.t.OnErrRtnForQuoteInsert = self._OnErrForQuoteInsert self.front_address = front self.t.RegCB() self.t.RegisterFront(front) self.t.SubscribePrivateTopic(0) # restart 同步处理order trade self.t.SubscribePublicTopic(0) self.t.Init() # self.t.Join() def ReqUserLogin(self, user: str, pwd: str, broker: str): """登录 :param user: :param pwd: :param broker: """ self.broker = broker self.investor = user self.password = pwd self.t.ReqUserLogin(BrokerID=broker, UserID=user, Password=pwd) def ReqOrderAction(self, OrderID: str): """撤单 :param OrderID: """ of = self.orders[OrderID] if not of: return -1 else: pOrderId = of.OrderID return self.t.ReqOrderAction( self.broker, self.investor, OrderRef=pOrderId.split('|')[2], FrontID=int(pOrderId.split('|')[1]), SessionID=int(pOrderId.split('|')[0]), InstrumentID=of.InstrumentID, ActionFlag=TThostFtdcActionFlagType.THOST_FTDC_AF_Delete) def ReqUserLogout(self): """退出接口""" self.logined = False time.sleep(3) self.t.ReqUserLogout(BrokerID=self.broker, UserID=self.investor) self.t.RegisterSpi(None) self.t.Release() threading.Thread(target=self.OnDisConnected, args=(self, 0)).start() def OnConnected(self, obj): """接口连接 :param obj: """ print('=== [TRADE] OnConnected ==='.format('')) def OnDisConnected(self, obj, reason: int): """接口断开 :param obj: :param reason: """ print('=== [TRADE] OnDisConnected === \nreason: {0}'.format(reason)) def OnUserLogin(self, obj, info: InfoField): """登录响应 :param obj: :param info: """ print('=== [TRADE] OnUserLogin === \n{0}'.format(info)) def OnOrder(self, obj, f: OrderField): """委托响应 :param obj: :param f: """ print('=== [TRADE] OnOrder === \n{0}'.format(f.__dict__)) def OnTrade(self, obj, f: TradeField): """成交响应 :param obj: :param f: """ print('=== [TRADE] OnTrade === \n{0}'.format(f.__dict__)) def OnCancel(self, obj, f: OrderField): """ 撤单响应 :param self: :param obj: :param f:OrderField: """ print('=== [TRADE] OnCancel === \n{0}'.format(f.__dict__)) def OnErrCancel(self, obj, f: OrderField, info: InfoField): """ 撤单失败 :param self: :param obj: :param f:OrderField: :param info:InfoField: """ print('=== [TRADE] OnErrCancel ===\n{0}'.format(f.__dict__)) print(info) def OnErrOrder(self, obj, f: OrderField, info: InfoField): """ 委托错误 :param self: :param obj: :param f:OrderField: :param info:InfoField: """ print('=== [TRADE] OnErrOrder ===\n{0}'.format(f.__dict__)) print(info) def OnInstrumentStatus(self, obj, inst: str, status: InstrumentStatus): """ 交易状态 :param self: :param obj: :param inst:str: :param status:InstrumentStatus: """ print('{}:{}'.format(inst, str(status).strip().split('.')[-1])) def OnRtnNotice(self, obj, time: str, msg: str): """交易提醒 :param obj: :param time: :param msg: :return: """ print(f'=== OnRtnNotice===\n {time}:{msg}') def OnRtnQuote(self, obj, quote: CThostFtdcQuoteField): """报价通知 :param obj: :param quote: :return: """ print('=== [TRADE] OnRtnQuote ===\n{0}'.format(quote.__dict__)) def OnErrRtnQuote(self, obj, quote: CThostFtdcInputQuoteField, info: InfoField): """ :param obj: :param quote: :return: """ print('=== [TRADE] OnErrRtnQuote ===\n{0}'.format(quote.__dict__)) print(info) def OnErrRtnForQuoteInsert(self, obj, quote: CThostFtdcInputQuoteField, info: InfoField): """询价录入错误回报 :param obj: :param quote: :return: """ print('=== [TRADE] OnErrRtnForQuoteInsert ===\n{0}'.format(quote.__dict__)) print(info)
haifengat/hf_ctp_py_proxy
py_ctp/trade.py
CtpTrade.ReqOrderAction
python
def ReqOrderAction(self, OrderID: str): of = self.orders[OrderID] if not of: return -1 else: pOrderId = of.OrderID return self.t.ReqOrderAction( self.broker, self.investor, OrderRef=pOrderId.split('|')[2], FrontID=int(pOrderId.split('|')[1]), SessionID=int(pOrderId.split('|')[0]), InstrumentID=of.InstrumentID, ActionFlag=TThostFtdcActionFlagType.THOST_FTDC_AF_Delete)
撤单 :param OrderID:
train
https://github.com/haifengat/hf_ctp_py_proxy/blob/c2dc6dbde45aa6b097f75380474e91510d3f5d12/py_ctp/trade.py#L515-L533
null
class CtpTrade(): """""" def __init__(self): self.front_address = '' self.investor = '' self.password = '' self.broker = '' self.logined = False self.tradingday = '' self.instruments = {} self.orders = {} self.trades = {} self.account: TradingAccount = None self.positions = {} self.instrument_status = {} self._req = 0 self._session = '' self._orderid_sysid = {} self._posi = [] self.t = Trade() def _OnFrontConnected(self): threading.Thread(target=self.OnConnected, args=(self,)).start() def _OnFrontDisconnected(self, nReason): self.logined = False print(nReason) # 下午收盘后会不停断开再连接 4097错误 if nReason == 4097 or nReason == 4098: threading.Thread(target=self._reconnect).start() else: threading.Thread(target=self.OnDisConnected, args=(self, nReason)).start() def _reconnect(self): if sum([1 if stat == 'Continous' else 0 for exc, stat in self.instrument_status.items()]) == 0: print(time.strftime('%Y%m%d %H:%M:%S', time.localtime())) self.t.Release() time.sleep(600) self.ReqConnect(self.front_address) # def _OnRspUserLogout(self, pUserLogout: CThostFtdcUserLogoutField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): # pass def _OnRspUserLogin(self, pRspUserLogin: CThostFtdcRspUserLoginField(), pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" if pRspInfo.getErrorID() == 0: self.session = pRspUserLogin.getSessionID() self.tradingday = pRspUserLogin.getTradingDay() self.t.ReqSettlementInfoConfirm(self.broker, self.investor) elif self.logined: threading.Thread(target=self._relogin).start() else: info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() threading.Thread(target=self.OnUserLogin, args=(self, info)).start() def _relogin(self): # 隔夜重连=>处理'初始化'错误 time.sleep(60 * 10) self.t.ReqUserLogin( BrokerID=self.broker, UserID=self.investor, Password=self.password, UserProductInfo='@haifeng') def _OnRspSettlementInfoConfirm( self, pSettlementInfoConfirm: CThostFtdcSettlementInfoConfirmField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): if not self.logined: time.sleep(0.5) """查询合约/持仓/权益""" threading.Thread(target=self._qry).start() # 开启查询 def _qry(self): """查询帐号相关信息""" # restart 模式, 待rtnorder 处理完毕后再进行查询,否则会造成position混乱 ord_cnt = 0 trd_cnt = 0 while True: time.sleep(0.5) if len(self.orders) == ord_cnt and len(self.trades) == trd_cnt: break ord_cnt = len(self.orders) trd_cnt = len(self.trades) self.t.ReqQryInstrument() time.sleep(1.1) self.t.ReqQryInvestorPosition(self.broker, self.investor) time.sleep(1.1) self.t.ReqQryTradingAccount(self.broker, self.investor) time.sleep(1.1) self.logined = True info = InfoField() info.ErrorID = 0 info.ErrorMsg = '正确' threading.Thread(target=self.OnUserLogin, args=(self, info)).start() # 调用Release后程序异常退出,但不报错误:接口断开了仍然调用了查询指令 while self.logined: """查询持仓与权益""" self.t.ReqQryInvestorPosition(self.broker, self.investor) time.sleep(1.1) if not self.logined: return self.t.ReqQryTradingAccount(self.broker, self.investor) time.sleep(1.1) def _OnRtnInstrumentStatus(self, pInstrumentStatus: CThostFtdcInstrumentStatusField): if pInstrumentStatus.getInstrumentID() == '': return status = InstrumentStatus.Continous if pInstrumentStatus.getInstrumentStatus() == TThostFtdcInstrumentStatusType.THOST_FTDC_IS_Continous: status = InstrumentStatus.Continous elif pInstrumentStatus.getInstrumentStatus() == TThostFtdcInstrumentStatusType.THOST_FTDC_IS_Closed: status = InstrumentStatus.Closed elif str(pInstrumentStatus.getInstrumentStatus()).startswith('Auction'): status = InstrumentStatus.Auction else: status = InstrumentStatus.NoTrading self.instrument_status[pInstrumentStatus.getInstrumentID()] = status self.OnInstrumentStatus(self, pInstrumentStatus.getInstrumentID(), status) def _OnRspQryInstrument(self, pInstrument: CThostFtdcInstrumentField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" inst = InstrumentField() inst.InstrumentID = pInstrument.getInstrumentID() inst.ProductID = pInstrument.getProductID() inst.ExchangeID = pInstrument.getExchangeID() inst.VolumeMultiple = pInstrument.getVolumeMultiple() inst.PriceTick = pInstrument.getPriceTick() inst.MaxOrderVolume = pInstrument.getMaxLimitOrderVolume() inst.ProductType = pInstrument.getProductClass().name # ProductClassType.Futures -> Futures self.instruments[inst.InstrumentID] = inst def _OnRspQryPosition(self, pInvestorPosition: CThostFtdcInvestorPositionField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" if pInvestorPosition.getInstrumentID() != '': # 偶尔出现NULL的数据导致数据转换错误 self._posi.append(pInvestorPosition) # Struct(**f.__dict__)) #dict -> object if bIsLast: # 先排序再group才有效 self._posi = sorted(self._posi, key=lambda c: '{0}_{1}'.format(c.getInstrumentID(), DirectType.Buy if c.getPosiDirection() == TThostFtdcPosiDirectionType.THOST_FTDC_PD_Long else DirectType.Sell)) # direction需从posidiction转换为dictiontype for key, group in itertools.groupby(self._posi, lambda c: '{0}_{1}'.format(c.getInstrumentID(), 'Buy' if c.getPosiDirection() == TThostFtdcPosiDirectionType.THOST_FTDC_PD_Long else 'Sell')): pf = self.positions.get(key) if not pf: pf = PositionField() self.positions[key] = pf pf.Position = 0 pf.TdPosition = 0 pf.YdPosition = 0 pf.CloseProfit = 0 pf.PositionProfit = 0 pf.Commission = 0 pf.Margin = 0 pf.Price = 0 cost = 0.0 for g in group: if not pf.InstrumentID: pf.InstrumentID = g.getInstrumentID() pf.Direction = DirectType.Buy if g.getPosiDirection() == TThostFtdcPosiDirectionType.THOST_FTDC_PD_Long else DirectType.Sell pf.Position += g.getPosition() pf.TdPosition += g.getTodayPosition() pf.YdPosition = pf.Position - pf.TdPosition pf.CloseProfit += g.getCloseProfit() pf.PositionProfit += g.getPositionProfit() pf.Commission += g.getCommission() pf.Margin += g.getUseMargin() cost += g.OpenCost # pf.Position <= 0 ? 0 : (g.Sum(n => n.PositionCost) / DicInstrumentField[pf.InstrumentID].VolumeMultiple / pf.Position); vm = self.instruments[pf.InstrumentID].VolumeMultiple pf.Price = 0 if pf.Position <= 0 else cost / vm / pf.Position self._posi.clear() def _OnRspQryPositionDetail(self, pInvestorPositionDetail: CThostFtdcInvestorPositionDetailField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """持仓明细""" if pInvestorPositionDetail.getInstrumentID() == '': return detail = PositionDetail() detail.Instrument = pInvestorPositionDetail.getInstrumentID() detail.CloseProfit = pInvestorPositionDetail.getCloseProfitByTrade() detail.Direction = DirectType.Buy if pInvestorPositionDetail.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell detail.HedgeFlag = HedgeType(list(TThostFtdcHedgeFlagType).index(pInvestorPositionDetail.getHedgeFlag())) detail.OpenDate = pInvestorPositionDetail.getOpenDate() detail.PositionProfit = pInvestorPositionDetail.getPositionProfitByTrade() detail.OpenPrice = pInvestorPositionDetail.getOpenPrice() detail.TradeType = TradeTypeType(list(TThostFtdcTradeTypeType).index(pInvestorPositionDetail.getTradeType())) detail.Volume = pInvestorPositionDetail.getVolume() self.position_details[pInvestorPositionDetail.getTradeID()] = detail def _OnRspQryAccount(self, pTradingAccount: CThostFtdcTradingAccountField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" if not self.account: self.account = TradingAccount() self.account.Available = pTradingAccount.getAvailable() self.account.CloseProfit = pTradingAccount.getCloseProfit() self.account.Commission = pTradingAccount.getCommission() self.account.CurrMargin = pTradingAccount.getCurrMargin() self.account.FrozenCash = pTradingAccount.getFrozenCash() self.account.PositionProfit = pTradingAccount.getPositionProfit() self.account.PreBalance = pTradingAccount.getPreBalance() + pTradingAccount.getDeposit() + pTradingAccount.getWithdraw() self.account.Fund = self.account.PreBalance + pTradingAccount.getCloseProfit() + pTradingAccount.getPositionProfit() - pTradingAccount.getCommission() self.account.Risk = 0 if self.account.Fund == 0 else self.account.CurrMargin / self.account.Fund def _OnRtnOrder(self, pOrder: CThostFtdcOrderField): """""" id = '{0}|{1}|{2}'.format(pOrder.getSessionID(), pOrder.getFrontID(), pOrder.getOrderRef()) of = self.orders.get(id) if not of: of = OrderField() if pOrder.getOrderRef().isdigit(): of.Custom = int(pOrder.getOrderRef()) % 1000000 of.InstrumentID = pOrder.getInstrumentID() of.InsertTime = pOrder.getInsertTime() of.Direction = DirectType.Buy if pOrder.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell ot = TThostFtdcOffsetFlagType(ord(pOrder.getCombOffsetFlag()[0])) of.Offset = OffsetType.Open if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open else OffsetType.CloseToday if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_CloseToday else OffsetType.Close of.Status = OrderStatus.Normal of.StatusMsg = pOrder.getStatusMsg() of.IsLocal = pOrder.getSessionID() == self.session of.LimitPrice = pOrder.getLimitPrice() of.OrderID = id of.Volume = pOrder.getVolumeTotalOriginal() of.VolumeLeft = of.Volume self.orders[id] = of threading.Thread(target=self.OnOrder, args=(self, of)).start() elif pOrder.getOrderStatus() == TThostFtdcOrderStatusType.THOST_FTDC_OST_Canceled: of.Status = OrderStatus.Canceled of.StatusMsg = pOrder.getStatusMsg() if of.StatusMsg.find('被拒绝') >= 0: info = InfoField() info.ErrorID = -1 info.ErrorMsg = of.StatusMsg threading.Thread(target=self.OnErrOrder, args=(self, of, info)).start() else: threading.Thread(target=self.OnCancel, args=(self, of)).start() else: if pOrder.getOrderSysID(): of.SysID = pOrder.getOrderSysID() self._orderid_sysid[pOrder.getOrderSysID()] = id # 记录sysid与orderid关联,方便Trade时查找处理 def _OnRtnTrade(self, f): """""" tf = TradeField() tf.Direction = DirectType.Buy if f.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell tf.ExchangeID = f.getExchangeID() tf.InstrumentID = f.getInstrumentID() tf.Offset = OffsetType.Open if f.getOffsetFlag() == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open else OffsetType.Close if f.getOffsetFlag() == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Close else OffsetType.CloseToday tf.Price = f.getPrice() tf.SysID = f.getOrderSysID() tf.TradeID = f.getTradeID() tf.TradeTime = f.getTradeTime() tf.TradingDay = f.getTradingDay() tf.Volume = f.getVolume() self.trades[tf.TradeID] = tf id = self._orderid_sysid[tf.SysID] of = self.orders[id] tf.OrderID = id # tradeid 与 orderid 关联 of.TradeTime = tf.TradeTime of.AvgPrice = (of.AvgPrice * (of.Volume - of.VolumeLeft) + tf.Price * tf.Volume) / (of.Volume - of.VolumeLeft + tf.Volume) of.TradeVolume = tf.Volume of.VolumeLeft -= tf.Volume if of.VolumeLeft == 0: of.Status = OrderStatus.Filled of.StatusMsg = '全部成交' else: of.Status = OrderStatus.Partial of.StatusMsg = '部分成交' # 更新持仓 ***** if tf.Offset == OffsetType.Open: key = '{0}_{1}'.format(tf.InstrumentID, 'Buy' if tf.Direction == DirectType.Buy else 'Sell') pf = self.positions.get(key) if not pf: pf = PositionField() self.positions[key] = pf pf.InstrumentID = tf.InstrumentID pf.Direction = tf.Direction pf.Price = (pf.Price * pf.Position + tf.Price * tf.Volume) / (pf.Position + tf.Volume) pf.TdPosition += tf.Volume pf.Position += tf.Volume else: key = '{0}_{1}'.format(tf.InstrumentID, DirectType.Sell if tf.Direction == DirectType.Buy else DirectType.Buy) pf = self.positions.get(key) if pf: # 有可能出现无持仓的情况 if tf.Offset == OffsetType.CloseToday: pf.TdPosition -= tf.Volume else: tdclose = min(pf.TdPosition, tf.Volume) if pf.TdPosition > 0: pf.TdPosition -= tdclose pf.YdPosition -= max(0, tf.Volume - tdclose) pf.Position -= tf.Volume threading.Thread(target=self._onRtn, args=(of, tf)).start() def _onRtn(self, of, tf): self.OnOrder(self, of) self.OnTrade(self, tf) def _OnRspOrder(self, pInputOrder: CThostFtdcInputOrderField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() id = '{0}|{1}|{2}'.format(self.session, '0', pInputOrder.getOrderRef()) of = self.orders.get(id) if not of: of = OrderField() l = int(pInputOrder.getOrderRef()) of.Custom = l % 1000000 of.InstrumentID = pInputOrder.getInstrumentID() of.InsertTime = time.strftime('%H:%M:%S', time.localtime()) # 对direction需特别处理(具体见ctp_struct) of.Direction = DirectType.Buy if pInputOrder.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell ot = TThostFtdcOffsetFlagType(ord(pInputOrder.getCombOffsetFlag()[0])) of.Offset = OffsetType.Open if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open else OffsetType.CloseToday if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_CloseToday else OffsetType.Close # of.Status = OrderStatus.Normal # of.StatusMsg = f.getStatusMsg() of.IsLocal = True of.LimitPrice = pInputOrder.getLimitPrice() of.OrderID = id of.Volume = pInputOrder.getVolumeTotalOriginal() of.VolumeLeft = of.Volume self.orders[id] = of of.Status = OrderStatus.Error of.StatusMsg = '{0}:{1}'.format(info.ErrorID, info.ErrorMsg) threading.Thread(target=self.OnErrOrder, args=(self, of, info)).start() def _OnErrOrder(self, pInputOrder: CThostFtdcInputOrderField, pRspInfo: CThostFtdcRspInfoField): """""" id = '{0}|{1}|{2}'.format(self.session, '0', pInputOrder.getOrderRef()) of = self.orders.get(id) info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() if of and of.IsLocal: of.Status = OrderStatus.Error of.StatusMsg = '{0}:{1}'.format(pRspInfo.getErrorID(), pRspInfo.getErrorMsg()) threading.Thread(target=self.OnErrOrder, args=(self, of, info)).start() def _OnRspOrderAction(self, pInputOrderAction: CThostFtdcInputOrderActionField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): id = "{0}|{1}|{2}".format(pInputOrderAction.getSessionID(), pInputOrderAction.getFrontID(), pInputOrderAction.getOrderRef()) if self.logined and id in self.orders: info = InfoField() info.ErrorID = pRspInfo.ErrorID info.ErrorMsg = pRspInfo.ErrorMsg threading.Thread(target=self.OnErrCancel, args=(self, self.orders[id], info)).start() def _OnRtnNotice(self, pTradingNoticeInfo: CThostFtdcTradingNoticeInfoField): '''交易提醒''' msg = pTradingNoticeInfo.getFieldContent() if len(msg) > 0: threading.Thread(target=self.OnRtnNotice, args=(self, pTradingNoticeInfo.getSendTime(), msg)).start() def _OnRtnQuote(self, pQuote: CThostFtdcQuoteField): threading.Thread(target=self.OnRtnQuote, args=(self, pQuote)).start() def _OnErrRtnQuote(self, pInputQuote: CThostFtdcInputQuoteField, pRspInfo: CThostFtdcRspInfoField): info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() threading.Thread(target=self.OnErrRtnQuote, args=(self, pInputQuote, info)).start() def _OnErrForQuoteInsert(self, pInputForQuote: CThostFtdcInputForQuoteField, pRspInfo: CThostFtdcRspInfoField): info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() threading.Thread(target=self.OnErrRtnForQuoteInsert, args=(self, pInputForQuote, info)).start() def ReqConnect(self, front: str): """连接交易前置 :param front: """ self.t.CreateApi() spi = self.t.CreateSpi() self.t.RegisterSpi(spi) self.t.OnFrontConnected = self._OnFrontConnected self.t.OnRspUserLogin = self._OnRspUserLogin self.t.OnFrontDisconnected = self._OnFrontDisconnected # self.t.OnRspUserLogout = self._OnRspUserLogout self.t.OnRspSettlementInfoConfirm = self._OnRspSettlementInfoConfirm self.t.OnRtnOrder = self._OnRtnOrder self.t.OnRtnTrade = self._OnRtnTrade self.t.OnRspOrderInsert = self._OnRspOrder self.t.OnErrRtnOrderInsert = self._OnErrOrder self.t.OnRspOrderAction = self._OnRspOrderAction self.t.OnRtnInstrumentStatus = self._OnRtnInstrumentStatus self.t.OnRspQryInstrument = self._OnRspQryInstrument self.t.OnRspQryTradingAccount = self._OnRspQryAccount self.t.OnRspQryInvestorPosition = self._OnRspQryPosition self.t.OnRspQryInvestorPositionDetail = self._OnRspQryPositionDetail self.t.OnRtnTradingNotice = self._OnRtnNotice self.t.OnRtnQuote = self._OnRtnQuote self.t.OnErrRtnQuoteInsert = self._OnErrRtnQuote self.t.OnErrRtnForQuoteInsert = self._OnErrForQuoteInsert self.front_address = front self.t.RegCB() self.t.RegisterFront(front) self.t.SubscribePrivateTopic(0) # restart 同步处理order trade self.t.SubscribePublicTopic(0) self.t.Init() # self.t.Join() def ReqUserLogin(self, user: str, pwd: str, broker: str): """登录 :param user: :param pwd: :param broker: """ self.broker = broker self.investor = user self.password = pwd self.t.ReqUserLogin(BrokerID=broker, UserID=user, Password=pwd) def ReqOrderInsert(self, pInstrument: str, pDirection: DirectType, pOffset: OffsetType, pPrice: float = 0.0, pVolume: int = 1, pType: OrderType = OrderType.Limit, pCustom: int = 0): """委托 :param pInstrument: :param pDirection: :param pOffset: :param pPrice: :param pVolume: :param pType: :param pCustom: :return: """ OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_AnyPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = 0.0 VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV if pType == OrderType.Market: # 市价 OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_AnyPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = 0.0 VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV elif pType == OrderType.Limit: # 限价 OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LimitPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_GFD LimitPrice = pPrice VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV elif pType == OrderType.FAK: # FAK OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LimitPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = pPrice VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV elif pType == OrderType.FOK: # FOK OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LimitPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = pPrice VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_CV # 全部数量 self._req += 1 self.t.ReqOrderInsert( BrokerID=self.broker, InvestorID=self.investor, InstrumentID=pInstrument, OrderRef="%06d%06d" % (self._req, pCustom % 1000000), UserID=self.investor, # 此处ctp_enum与at_struct名称冲突 Direction=TThostFtdcDirectionType.THOST_FTDC_D_Buy if pDirection == DirectType.Buy else TThostFtdcDirectionType.THOST_FTDC_D_Sell, CombOffsetFlag=chr(TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open.value if pOffset == OffsetType.Open else TThostFtdcOffsetFlagType.THOST_FTDC_OF_CloseToday.value if pOffset == OffsetType.CloseToday else TThostFtdcOffsetFlagType.THOST_FTDC_OF_Close.value), CombHedgeFlag=chr(TThostFtdcHedgeFlagType.THOST_FTDC_HF_Speculation.value), IsAutoSuspend=0, ForceCloseReason=TThostFtdcForceCloseReasonType.THOST_FTDC_FCC_NotForceClose, IsSwapOrder=0, ContingentCondition=TThostFtdcContingentConditionType.THOST_FTDC_CC_Immediately, VolumeCondition=VolumeCondition, MinVolume=1, VolumeTotalOriginal=pVolume, OrderPriceType=OrderPriceType, TimeCondition=TimeCondition, LimitPrice=LimitPrice, ) def ReqUserLogout(self): """退出接口""" self.logined = False time.sleep(3) self.t.ReqUserLogout(BrokerID=self.broker, UserID=self.investor) self.t.RegisterSpi(None) self.t.Release() threading.Thread(target=self.OnDisConnected, args=(self, 0)).start() def OnConnected(self, obj): """接口连接 :param obj: """ print('=== [TRADE] OnConnected ==='.format('')) def OnDisConnected(self, obj, reason: int): """接口断开 :param obj: :param reason: """ print('=== [TRADE] OnDisConnected === \nreason: {0}'.format(reason)) def OnUserLogin(self, obj, info: InfoField): """登录响应 :param obj: :param info: """ print('=== [TRADE] OnUserLogin === \n{0}'.format(info)) def OnOrder(self, obj, f: OrderField): """委托响应 :param obj: :param f: """ print('=== [TRADE] OnOrder === \n{0}'.format(f.__dict__)) def OnTrade(self, obj, f: TradeField): """成交响应 :param obj: :param f: """ print('=== [TRADE] OnTrade === \n{0}'.format(f.__dict__)) def OnCancel(self, obj, f: OrderField): """ 撤单响应 :param self: :param obj: :param f:OrderField: """ print('=== [TRADE] OnCancel === \n{0}'.format(f.__dict__)) def OnErrCancel(self, obj, f: OrderField, info: InfoField): """ 撤单失败 :param self: :param obj: :param f:OrderField: :param info:InfoField: """ print('=== [TRADE] OnErrCancel ===\n{0}'.format(f.__dict__)) print(info) def OnErrOrder(self, obj, f: OrderField, info: InfoField): """ 委托错误 :param self: :param obj: :param f:OrderField: :param info:InfoField: """ print('=== [TRADE] OnErrOrder ===\n{0}'.format(f.__dict__)) print(info) def OnInstrumentStatus(self, obj, inst: str, status: InstrumentStatus): """ 交易状态 :param self: :param obj: :param inst:str: :param status:InstrumentStatus: """ print('{}:{}'.format(inst, str(status).strip().split('.')[-1])) def OnRtnNotice(self, obj, time: str, msg: str): """交易提醒 :param obj: :param time: :param msg: :return: """ print(f'=== OnRtnNotice===\n {time}:{msg}') def OnRtnQuote(self, obj, quote: CThostFtdcQuoteField): """报价通知 :param obj: :param quote: :return: """ print('=== [TRADE] OnRtnQuote ===\n{0}'.format(quote.__dict__)) def OnErrRtnQuote(self, obj, quote: CThostFtdcInputQuoteField, info: InfoField): """ :param obj: :param quote: :return: """ print('=== [TRADE] OnErrRtnQuote ===\n{0}'.format(quote.__dict__)) print(info) def OnErrRtnForQuoteInsert(self, obj, quote: CThostFtdcInputQuoteField, info: InfoField): """询价录入错误回报 :param obj: :param quote: :return: """ print('=== [TRADE] OnErrRtnForQuoteInsert ===\n{0}'.format(quote.__dict__)) print(info)
haifengat/hf_ctp_py_proxy
py_ctp/trade.py
CtpTrade.ReqUserLogout
python
def ReqUserLogout(self): self.logined = False time.sleep(3) self.t.ReqUserLogout(BrokerID=self.broker, UserID=self.investor) self.t.RegisterSpi(None) self.t.Release() threading.Thread(target=self.OnDisConnected, args=(self, 0)).start()
退出接口
train
https://github.com/haifengat/hf_ctp_py_proxy/blob/c2dc6dbde45aa6b097f75380474e91510d3f5d12/py_ctp/trade.py#L535-L542
null
class CtpTrade(): """""" def __init__(self): self.front_address = '' self.investor = '' self.password = '' self.broker = '' self.logined = False self.tradingday = '' self.instruments = {} self.orders = {} self.trades = {} self.account: TradingAccount = None self.positions = {} self.instrument_status = {} self._req = 0 self._session = '' self._orderid_sysid = {} self._posi = [] self.t = Trade() def _OnFrontConnected(self): threading.Thread(target=self.OnConnected, args=(self,)).start() def _OnFrontDisconnected(self, nReason): self.logined = False print(nReason) # 下午收盘后会不停断开再连接 4097错误 if nReason == 4097 or nReason == 4098: threading.Thread(target=self._reconnect).start() else: threading.Thread(target=self.OnDisConnected, args=(self, nReason)).start() def _reconnect(self): if sum([1 if stat == 'Continous' else 0 for exc, stat in self.instrument_status.items()]) == 0: print(time.strftime('%Y%m%d %H:%M:%S', time.localtime())) self.t.Release() time.sleep(600) self.ReqConnect(self.front_address) # def _OnRspUserLogout(self, pUserLogout: CThostFtdcUserLogoutField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): # pass def _OnRspUserLogin(self, pRspUserLogin: CThostFtdcRspUserLoginField(), pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" if pRspInfo.getErrorID() == 0: self.session = pRspUserLogin.getSessionID() self.tradingday = pRspUserLogin.getTradingDay() self.t.ReqSettlementInfoConfirm(self.broker, self.investor) elif self.logined: threading.Thread(target=self._relogin).start() else: info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() threading.Thread(target=self.OnUserLogin, args=(self, info)).start() def _relogin(self): # 隔夜重连=>处理'初始化'错误 time.sleep(60 * 10) self.t.ReqUserLogin( BrokerID=self.broker, UserID=self.investor, Password=self.password, UserProductInfo='@haifeng') def _OnRspSettlementInfoConfirm( self, pSettlementInfoConfirm: CThostFtdcSettlementInfoConfirmField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): if not self.logined: time.sleep(0.5) """查询合约/持仓/权益""" threading.Thread(target=self._qry).start() # 开启查询 def _qry(self): """查询帐号相关信息""" # restart 模式, 待rtnorder 处理完毕后再进行查询,否则会造成position混乱 ord_cnt = 0 trd_cnt = 0 while True: time.sleep(0.5) if len(self.orders) == ord_cnt and len(self.trades) == trd_cnt: break ord_cnt = len(self.orders) trd_cnt = len(self.trades) self.t.ReqQryInstrument() time.sleep(1.1) self.t.ReqQryInvestorPosition(self.broker, self.investor) time.sleep(1.1) self.t.ReqQryTradingAccount(self.broker, self.investor) time.sleep(1.1) self.logined = True info = InfoField() info.ErrorID = 0 info.ErrorMsg = '正确' threading.Thread(target=self.OnUserLogin, args=(self, info)).start() # 调用Release后程序异常退出,但不报错误:接口断开了仍然调用了查询指令 while self.logined: """查询持仓与权益""" self.t.ReqQryInvestorPosition(self.broker, self.investor) time.sleep(1.1) if not self.logined: return self.t.ReqQryTradingAccount(self.broker, self.investor) time.sleep(1.1) def _OnRtnInstrumentStatus(self, pInstrumentStatus: CThostFtdcInstrumentStatusField): if pInstrumentStatus.getInstrumentID() == '': return status = InstrumentStatus.Continous if pInstrumentStatus.getInstrumentStatus() == TThostFtdcInstrumentStatusType.THOST_FTDC_IS_Continous: status = InstrumentStatus.Continous elif pInstrumentStatus.getInstrumentStatus() == TThostFtdcInstrumentStatusType.THOST_FTDC_IS_Closed: status = InstrumentStatus.Closed elif str(pInstrumentStatus.getInstrumentStatus()).startswith('Auction'): status = InstrumentStatus.Auction else: status = InstrumentStatus.NoTrading self.instrument_status[pInstrumentStatus.getInstrumentID()] = status self.OnInstrumentStatus(self, pInstrumentStatus.getInstrumentID(), status) def _OnRspQryInstrument(self, pInstrument: CThostFtdcInstrumentField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" inst = InstrumentField() inst.InstrumentID = pInstrument.getInstrumentID() inst.ProductID = pInstrument.getProductID() inst.ExchangeID = pInstrument.getExchangeID() inst.VolumeMultiple = pInstrument.getVolumeMultiple() inst.PriceTick = pInstrument.getPriceTick() inst.MaxOrderVolume = pInstrument.getMaxLimitOrderVolume() inst.ProductType = pInstrument.getProductClass().name # ProductClassType.Futures -> Futures self.instruments[inst.InstrumentID] = inst def _OnRspQryPosition(self, pInvestorPosition: CThostFtdcInvestorPositionField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" if pInvestorPosition.getInstrumentID() != '': # 偶尔出现NULL的数据导致数据转换错误 self._posi.append(pInvestorPosition) # Struct(**f.__dict__)) #dict -> object if bIsLast: # 先排序再group才有效 self._posi = sorted(self._posi, key=lambda c: '{0}_{1}'.format(c.getInstrumentID(), DirectType.Buy if c.getPosiDirection() == TThostFtdcPosiDirectionType.THOST_FTDC_PD_Long else DirectType.Sell)) # direction需从posidiction转换为dictiontype for key, group in itertools.groupby(self._posi, lambda c: '{0}_{1}'.format(c.getInstrumentID(), 'Buy' if c.getPosiDirection() == TThostFtdcPosiDirectionType.THOST_FTDC_PD_Long else 'Sell')): pf = self.positions.get(key) if not pf: pf = PositionField() self.positions[key] = pf pf.Position = 0 pf.TdPosition = 0 pf.YdPosition = 0 pf.CloseProfit = 0 pf.PositionProfit = 0 pf.Commission = 0 pf.Margin = 0 pf.Price = 0 cost = 0.0 for g in group: if not pf.InstrumentID: pf.InstrumentID = g.getInstrumentID() pf.Direction = DirectType.Buy if g.getPosiDirection() == TThostFtdcPosiDirectionType.THOST_FTDC_PD_Long else DirectType.Sell pf.Position += g.getPosition() pf.TdPosition += g.getTodayPosition() pf.YdPosition = pf.Position - pf.TdPosition pf.CloseProfit += g.getCloseProfit() pf.PositionProfit += g.getPositionProfit() pf.Commission += g.getCommission() pf.Margin += g.getUseMargin() cost += g.OpenCost # pf.Position <= 0 ? 0 : (g.Sum(n => n.PositionCost) / DicInstrumentField[pf.InstrumentID].VolumeMultiple / pf.Position); vm = self.instruments[pf.InstrumentID].VolumeMultiple pf.Price = 0 if pf.Position <= 0 else cost / vm / pf.Position self._posi.clear() def _OnRspQryPositionDetail(self, pInvestorPositionDetail: CThostFtdcInvestorPositionDetailField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """持仓明细""" if pInvestorPositionDetail.getInstrumentID() == '': return detail = PositionDetail() detail.Instrument = pInvestorPositionDetail.getInstrumentID() detail.CloseProfit = pInvestorPositionDetail.getCloseProfitByTrade() detail.Direction = DirectType.Buy if pInvestorPositionDetail.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell detail.HedgeFlag = HedgeType(list(TThostFtdcHedgeFlagType).index(pInvestorPositionDetail.getHedgeFlag())) detail.OpenDate = pInvestorPositionDetail.getOpenDate() detail.PositionProfit = pInvestorPositionDetail.getPositionProfitByTrade() detail.OpenPrice = pInvestorPositionDetail.getOpenPrice() detail.TradeType = TradeTypeType(list(TThostFtdcTradeTypeType).index(pInvestorPositionDetail.getTradeType())) detail.Volume = pInvestorPositionDetail.getVolume() self.position_details[pInvestorPositionDetail.getTradeID()] = detail def _OnRspQryAccount(self, pTradingAccount: CThostFtdcTradingAccountField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" if not self.account: self.account = TradingAccount() self.account.Available = pTradingAccount.getAvailable() self.account.CloseProfit = pTradingAccount.getCloseProfit() self.account.Commission = pTradingAccount.getCommission() self.account.CurrMargin = pTradingAccount.getCurrMargin() self.account.FrozenCash = pTradingAccount.getFrozenCash() self.account.PositionProfit = pTradingAccount.getPositionProfit() self.account.PreBalance = pTradingAccount.getPreBalance() + pTradingAccount.getDeposit() + pTradingAccount.getWithdraw() self.account.Fund = self.account.PreBalance + pTradingAccount.getCloseProfit() + pTradingAccount.getPositionProfit() - pTradingAccount.getCommission() self.account.Risk = 0 if self.account.Fund == 0 else self.account.CurrMargin / self.account.Fund def _OnRtnOrder(self, pOrder: CThostFtdcOrderField): """""" id = '{0}|{1}|{2}'.format(pOrder.getSessionID(), pOrder.getFrontID(), pOrder.getOrderRef()) of = self.orders.get(id) if not of: of = OrderField() if pOrder.getOrderRef().isdigit(): of.Custom = int(pOrder.getOrderRef()) % 1000000 of.InstrumentID = pOrder.getInstrumentID() of.InsertTime = pOrder.getInsertTime() of.Direction = DirectType.Buy if pOrder.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell ot = TThostFtdcOffsetFlagType(ord(pOrder.getCombOffsetFlag()[0])) of.Offset = OffsetType.Open if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open else OffsetType.CloseToday if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_CloseToday else OffsetType.Close of.Status = OrderStatus.Normal of.StatusMsg = pOrder.getStatusMsg() of.IsLocal = pOrder.getSessionID() == self.session of.LimitPrice = pOrder.getLimitPrice() of.OrderID = id of.Volume = pOrder.getVolumeTotalOriginal() of.VolumeLeft = of.Volume self.orders[id] = of threading.Thread(target=self.OnOrder, args=(self, of)).start() elif pOrder.getOrderStatus() == TThostFtdcOrderStatusType.THOST_FTDC_OST_Canceled: of.Status = OrderStatus.Canceled of.StatusMsg = pOrder.getStatusMsg() if of.StatusMsg.find('被拒绝') >= 0: info = InfoField() info.ErrorID = -1 info.ErrorMsg = of.StatusMsg threading.Thread(target=self.OnErrOrder, args=(self, of, info)).start() else: threading.Thread(target=self.OnCancel, args=(self, of)).start() else: if pOrder.getOrderSysID(): of.SysID = pOrder.getOrderSysID() self._orderid_sysid[pOrder.getOrderSysID()] = id # 记录sysid与orderid关联,方便Trade时查找处理 def _OnRtnTrade(self, f): """""" tf = TradeField() tf.Direction = DirectType.Buy if f.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell tf.ExchangeID = f.getExchangeID() tf.InstrumentID = f.getInstrumentID() tf.Offset = OffsetType.Open if f.getOffsetFlag() == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open else OffsetType.Close if f.getOffsetFlag() == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Close else OffsetType.CloseToday tf.Price = f.getPrice() tf.SysID = f.getOrderSysID() tf.TradeID = f.getTradeID() tf.TradeTime = f.getTradeTime() tf.TradingDay = f.getTradingDay() tf.Volume = f.getVolume() self.trades[tf.TradeID] = tf id = self._orderid_sysid[tf.SysID] of = self.orders[id] tf.OrderID = id # tradeid 与 orderid 关联 of.TradeTime = tf.TradeTime of.AvgPrice = (of.AvgPrice * (of.Volume - of.VolumeLeft) + tf.Price * tf.Volume) / (of.Volume - of.VolumeLeft + tf.Volume) of.TradeVolume = tf.Volume of.VolumeLeft -= tf.Volume if of.VolumeLeft == 0: of.Status = OrderStatus.Filled of.StatusMsg = '全部成交' else: of.Status = OrderStatus.Partial of.StatusMsg = '部分成交' # 更新持仓 ***** if tf.Offset == OffsetType.Open: key = '{0}_{1}'.format(tf.InstrumentID, 'Buy' if tf.Direction == DirectType.Buy else 'Sell') pf = self.positions.get(key) if not pf: pf = PositionField() self.positions[key] = pf pf.InstrumentID = tf.InstrumentID pf.Direction = tf.Direction pf.Price = (pf.Price * pf.Position + tf.Price * tf.Volume) / (pf.Position + tf.Volume) pf.TdPosition += tf.Volume pf.Position += tf.Volume else: key = '{0}_{1}'.format(tf.InstrumentID, DirectType.Sell if tf.Direction == DirectType.Buy else DirectType.Buy) pf = self.positions.get(key) if pf: # 有可能出现无持仓的情况 if tf.Offset == OffsetType.CloseToday: pf.TdPosition -= tf.Volume else: tdclose = min(pf.TdPosition, tf.Volume) if pf.TdPosition > 0: pf.TdPosition -= tdclose pf.YdPosition -= max(0, tf.Volume - tdclose) pf.Position -= tf.Volume threading.Thread(target=self._onRtn, args=(of, tf)).start() def _onRtn(self, of, tf): self.OnOrder(self, of) self.OnTrade(self, tf) def _OnRspOrder(self, pInputOrder: CThostFtdcInputOrderField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() id = '{0}|{1}|{2}'.format(self.session, '0', pInputOrder.getOrderRef()) of = self.orders.get(id) if not of: of = OrderField() l = int(pInputOrder.getOrderRef()) of.Custom = l % 1000000 of.InstrumentID = pInputOrder.getInstrumentID() of.InsertTime = time.strftime('%H:%M:%S', time.localtime()) # 对direction需特别处理(具体见ctp_struct) of.Direction = DirectType.Buy if pInputOrder.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell ot = TThostFtdcOffsetFlagType(ord(pInputOrder.getCombOffsetFlag()[0])) of.Offset = OffsetType.Open if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open else OffsetType.CloseToday if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_CloseToday else OffsetType.Close # of.Status = OrderStatus.Normal # of.StatusMsg = f.getStatusMsg() of.IsLocal = True of.LimitPrice = pInputOrder.getLimitPrice() of.OrderID = id of.Volume = pInputOrder.getVolumeTotalOriginal() of.VolumeLeft = of.Volume self.orders[id] = of of.Status = OrderStatus.Error of.StatusMsg = '{0}:{1}'.format(info.ErrorID, info.ErrorMsg) threading.Thread(target=self.OnErrOrder, args=(self, of, info)).start() def _OnErrOrder(self, pInputOrder: CThostFtdcInputOrderField, pRspInfo: CThostFtdcRspInfoField): """""" id = '{0}|{1}|{2}'.format(self.session, '0', pInputOrder.getOrderRef()) of = self.orders.get(id) info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() if of and of.IsLocal: of.Status = OrderStatus.Error of.StatusMsg = '{0}:{1}'.format(pRspInfo.getErrorID(), pRspInfo.getErrorMsg()) threading.Thread(target=self.OnErrOrder, args=(self, of, info)).start() def _OnRspOrderAction(self, pInputOrderAction: CThostFtdcInputOrderActionField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): id = "{0}|{1}|{2}".format(pInputOrderAction.getSessionID(), pInputOrderAction.getFrontID(), pInputOrderAction.getOrderRef()) if self.logined and id in self.orders: info = InfoField() info.ErrorID = pRspInfo.ErrorID info.ErrorMsg = pRspInfo.ErrorMsg threading.Thread(target=self.OnErrCancel, args=(self, self.orders[id], info)).start() def _OnRtnNotice(self, pTradingNoticeInfo: CThostFtdcTradingNoticeInfoField): '''交易提醒''' msg = pTradingNoticeInfo.getFieldContent() if len(msg) > 0: threading.Thread(target=self.OnRtnNotice, args=(self, pTradingNoticeInfo.getSendTime(), msg)).start() def _OnRtnQuote(self, pQuote: CThostFtdcQuoteField): threading.Thread(target=self.OnRtnQuote, args=(self, pQuote)).start() def _OnErrRtnQuote(self, pInputQuote: CThostFtdcInputQuoteField, pRspInfo: CThostFtdcRspInfoField): info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() threading.Thread(target=self.OnErrRtnQuote, args=(self, pInputQuote, info)).start() def _OnErrForQuoteInsert(self, pInputForQuote: CThostFtdcInputForQuoteField, pRspInfo: CThostFtdcRspInfoField): info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() threading.Thread(target=self.OnErrRtnForQuoteInsert, args=(self, pInputForQuote, info)).start() def ReqConnect(self, front: str): """连接交易前置 :param front: """ self.t.CreateApi() spi = self.t.CreateSpi() self.t.RegisterSpi(spi) self.t.OnFrontConnected = self._OnFrontConnected self.t.OnRspUserLogin = self._OnRspUserLogin self.t.OnFrontDisconnected = self._OnFrontDisconnected # self.t.OnRspUserLogout = self._OnRspUserLogout self.t.OnRspSettlementInfoConfirm = self._OnRspSettlementInfoConfirm self.t.OnRtnOrder = self._OnRtnOrder self.t.OnRtnTrade = self._OnRtnTrade self.t.OnRspOrderInsert = self._OnRspOrder self.t.OnErrRtnOrderInsert = self._OnErrOrder self.t.OnRspOrderAction = self._OnRspOrderAction self.t.OnRtnInstrumentStatus = self._OnRtnInstrumentStatus self.t.OnRspQryInstrument = self._OnRspQryInstrument self.t.OnRspQryTradingAccount = self._OnRspQryAccount self.t.OnRspQryInvestorPosition = self._OnRspQryPosition self.t.OnRspQryInvestorPositionDetail = self._OnRspQryPositionDetail self.t.OnRtnTradingNotice = self._OnRtnNotice self.t.OnRtnQuote = self._OnRtnQuote self.t.OnErrRtnQuoteInsert = self._OnErrRtnQuote self.t.OnErrRtnForQuoteInsert = self._OnErrForQuoteInsert self.front_address = front self.t.RegCB() self.t.RegisterFront(front) self.t.SubscribePrivateTopic(0) # restart 同步处理order trade self.t.SubscribePublicTopic(0) self.t.Init() # self.t.Join() def ReqUserLogin(self, user: str, pwd: str, broker: str): """登录 :param user: :param pwd: :param broker: """ self.broker = broker self.investor = user self.password = pwd self.t.ReqUserLogin(BrokerID=broker, UserID=user, Password=pwd) def ReqOrderInsert(self, pInstrument: str, pDirection: DirectType, pOffset: OffsetType, pPrice: float = 0.0, pVolume: int = 1, pType: OrderType = OrderType.Limit, pCustom: int = 0): """委托 :param pInstrument: :param pDirection: :param pOffset: :param pPrice: :param pVolume: :param pType: :param pCustom: :return: """ OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_AnyPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = 0.0 VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV if pType == OrderType.Market: # 市价 OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_AnyPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = 0.0 VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV elif pType == OrderType.Limit: # 限价 OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LimitPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_GFD LimitPrice = pPrice VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV elif pType == OrderType.FAK: # FAK OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LimitPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = pPrice VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV elif pType == OrderType.FOK: # FOK OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LimitPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = pPrice VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_CV # 全部数量 self._req += 1 self.t.ReqOrderInsert( BrokerID=self.broker, InvestorID=self.investor, InstrumentID=pInstrument, OrderRef="%06d%06d" % (self._req, pCustom % 1000000), UserID=self.investor, # 此处ctp_enum与at_struct名称冲突 Direction=TThostFtdcDirectionType.THOST_FTDC_D_Buy if pDirection == DirectType.Buy else TThostFtdcDirectionType.THOST_FTDC_D_Sell, CombOffsetFlag=chr(TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open.value if pOffset == OffsetType.Open else TThostFtdcOffsetFlagType.THOST_FTDC_OF_CloseToday.value if pOffset == OffsetType.CloseToday else TThostFtdcOffsetFlagType.THOST_FTDC_OF_Close.value), CombHedgeFlag=chr(TThostFtdcHedgeFlagType.THOST_FTDC_HF_Speculation.value), IsAutoSuspend=0, ForceCloseReason=TThostFtdcForceCloseReasonType.THOST_FTDC_FCC_NotForceClose, IsSwapOrder=0, ContingentCondition=TThostFtdcContingentConditionType.THOST_FTDC_CC_Immediately, VolumeCondition=VolumeCondition, MinVolume=1, VolumeTotalOriginal=pVolume, OrderPriceType=OrderPriceType, TimeCondition=TimeCondition, LimitPrice=LimitPrice, ) def ReqOrderAction(self, OrderID: str): """撤单 :param OrderID: """ of = self.orders[OrderID] if not of: return -1 else: pOrderId = of.OrderID return self.t.ReqOrderAction( self.broker, self.investor, OrderRef=pOrderId.split('|')[2], FrontID=int(pOrderId.split('|')[1]), SessionID=int(pOrderId.split('|')[0]), InstrumentID=of.InstrumentID, ActionFlag=TThostFtdcActionFlagType.THOST_FTDC_AF_Delete) def OnConnected(self, obj): """接口连接 :param obj: """ print('=== [TRADE] OnConnected ==='.format('')) def OnDisConnected(self, obj, reason: int): """接口断开 :param obj: :param reason: """ print('=== [TRADE] OnDisConnected === \nreason: {0}'.format(reason)) def OnUserLogin(self, obj, info: InfoField): """登录响应 :param obj: :param info: """ print('=== [TRADE] OnUserLogin === \n{0}'.format(info)) def OnOrder(self, obj, f: OrderField): """委托响应 :param obj: :param f: """ print('=== [TRADE] OnOrder === \n{0}'.format(f.__dict__)) def OnTrade(self, obj, f: TradeField): """成交响应 :param obj: :param f: """ print('=== [TRADE] OnTrade === \n{0}'.format(f.__dict__)) def OnCancel(self, obj, f: OrderField): """ 撤单响应 :param self: :param obj: :param f:OrderField: """ print('=== [TRADE] OnCancel === \n{0}'.format(f.__dict__)) def OnErrCancel(self, obj, f: OrderField, info: InfoField): """ 撤单失败 :param self: :param obj: :param f:OrderField: :param info:InfoField: """ print('=== [TRADE] OnErrCancel ===\n{0}'.format(f.__dict__)) print(info) def OnErrOrder(self, obj, f: OrderField, info: InfoField): """ 委托错误 :param self: :param obj: :param f:OrderField: :param info:InfoField: """ print('=== [TRADE] OnErrOrder ===\n{0}'.format(f.__dict__)) print(info) def OnInstrumentStatus(self, obj, inst: str, status: InstrumentStatus): """ 交易状态 :param self: :param obj: :param inst:str: :param status:InstrumentStatus: """ print('{}:{}'.format(inst, str(status).strip().split('.')[-1])) def OnRtnNotice(self, obj, time: str, msg: str): """交易提醒 :param obj: :param time: :param msg: :return: """ print(f'=== OnRtnNotice===\n {time}:{msg}') def OnRtnQuote(self, obj, quote: CThostFtdcQuoteField): """报价通知 :param obj: :param quote: :return: """ print('=== [TRADE] OnRtnQuote ===\n{0}'.format(quote.__dict__)) def OnErrRtnQuote(self, obj, quote: CThostFtdcInputQuoteField, info: InfoField): """ :param obj: :param quote: :return: """ print('=== [TRADE] OnErrRtnQuote ===\n{0}'.format(quote.__dict__)) print(info) def OnErrRtnForQuoteInsert(self, obj, quote: CThostFtdcInputQuoteField, info: InfoField): """询价录入错误回报 :param obj: :param quote: :return: """ print('=== [TRADE] OnErrRtnForQuoteInsert ===\n{0}'.format(quote.__dict__)) print(info)
haifengat/hf_ctp_py_proxy
py_ctp/trade.py
CtpTrade.OnErrCancel
python
def OnErrCancel(self, obj, f: OrderField, info: InfoField): print('=== [TRADE] OnErrCancel ===\n{0}'.format(f.__dict__)) print(info)
撤单失败 :param self: :param obj: :param f:OrderField: :param info:InfoField:
train
https://github.com/haifengat/hf_ctp_py_proxy/blob/c2dc6dbde45aa6b097f75380474e91510d3f5d12/py_ctp/trade.py#L592-L601
null
class CtpTrade(): """""" def __init__(self): self.front_address = '' self.investor = '' self.password = '' self.broker = '' self.logined = False self.tradingday = '' self.instruments = {} self.orders = {} self.trades = {} self.account: TradingAccount = None self.positions = {} self.instrument_status = {} self._req = 0 self._session = '' self._orderid_sysid = {} self._posi = [] self.t = Trade() def _OnFrontConnected(self): threading.Thread(target=self.OnConnected, args=(self,)).start() def _OnFrontDisconnected(self, nReason): self.logined = False print(nReason) # 下午收盘后会不停断开再连接 4097错误 if nReason == 4097 or nReason == 4098: threading.Thread(target=self._reconnect).start() else: threading.Thread(target=self.OnDisConnected, args=(self, nReason)).start() def _reconnect(self): if sum([1 if stat == 'Continous' else 0 for exc, stat in self.instrument_status.items()]) == 0: print(time.strftime('%Y%m%d %H:%M:%S', time.localtime())) self.t.Release() time.sleep(600) self.ReqConnect(self.front_address) # def _OnRspUserLogout(self, pUserLogout: CThostFtdcUserLogoutField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): # pass def _OnRspUserLogin(self, pRspUserLogin: CThostFtdcRspUserLoginField(), pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" if pRspInfo.getErrorID() == 0: self.session = pRspUserLogin.getSessionID() self.tradingday = pRspUserLogin.getTradingDay() self.t.ReqSettlementInfoConfirm(self.broker, self.investor) elif self.logined: threading.Thread(target=self._relogin).start() else: info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() threading.Thread(target=self.OnUserLogin, args=(self, info)).start() def _relogin(self): # 隔夜重连=>处理'初始化'错误 time.sleep(60 * 10) self.t.ReqUserLogin( BrokerID=self.broker, UserID=self.investor, Password=self.password, UserProductInfo='@haifeng') def _OnRspSettlementInfoConfirm( self, pSettlementInfoConfirm: CThostFtdcSettlementInfoConfirmField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): if not self.logined: time.sleep(0.5) """查询合约/持仓/权益""" threading.Thread(target=self._qry).start() # 开启查询 def _qry(self): """查询帐号相关信息""" # restart 模式, 待rtnorder 处理完毕后再进行查询,否则会造成position混乱 ord_cnt = 0 trd_cnt = 0 while True: time.sleep(0.5) if len(self.orders) == ord_cnt and len(self.trades) == trd_cnt: break ord_cnt = len(self.orders) trd_cnt = len(self.trades) self.t.ReqQryInstrument() time.sleep(1.1) self.t.ReqQryInvestorPosition(self.broker, self.investor) time.sleep(1.1) self.t.ReqQryTradingAccount(self.broker, self.investor) time.sleep(1.1) self.logined = True info = InfoField() info.ErrorID = 0 info.ErrorMsg = '正确' threading.Thread(target=self.OnUserLogin, args=(self, info)).start() # 调用Release后程序异常退出,但不报错误:接口断开了仍然调用了查询指令 while self.logined: """查询持仓与权益""" self.t.ReqQryInvestorPosition(self.broker, self.investor) time.sleep(1.1) if not self.logined: return self.t.ReqQryTradingAccount(self.broker, self.investor) time.sleep(1.1) def _OnRtnInstrumentStatus(self, pInstrumentStatus: CThostFtdcInstrumentStatusField): if pInstrumentStatus.getInstrumentID() == '': return status = InstrumentStatus.Continous if pInstrumentStatus.getInstrumentStatus() == TThostFtdcInstrumentStatusType.THOST_FTDC_IS_Continous: status = InstrumentStatus.Continous elif pInstrumentStatus.getInstrumentStatus() == TThostFtdcInstrumentStatusType.THOST_FTDC_IS_Closed: status = InstrumentStatus.Closed elif str(pInstrumentStatus.getInstrumentStatus()).startswith('Auction'): status = InstrumentStatus.Auction else: status = InstrumentStatus.NoTrading self.instrument_status[pInstrumentStatus.getInstrumentID()] = status self.OnInstrumentStatus(self, pInstrumentStatus.getInstrumentID(), status) def _OnRspQryInstrument(self, pInstrument: CThostFtdcInstrumentField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" inst = InstrumentField() inst.InstrumentID = pInstrument.getInstrumentID() inst.ProductID = pInstrument.getProductID() inst.ExchangeID = pInstrument.getExchangeID() inst.VolumeMultiple = pInstrument.getVolumeMultiple() inst.PriceTick = pInstrument.getPriceTick() inst.MaxOrderVolume = pInstrument.getMaxLimitOrderVolume() inst.ProductType = pInstrument.getProductClass().name # ProductClassType.Futures -> Futures self.instruments[inst.InstrumentID] = inst def _OnRspQryPosition(self, pInvestorPosition: CThostFtdcInvestorPositionField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" if pInvestorPosition.getInstrumentID() != '': # 偶尔出现NULL的数据导致数据转换错误 self._posi.append(pInvestorPosition) # Struct(**f.__dict__)) #dict -> object if bIsLast: # 先排序再group才有效 self._posi = sorted(self._posi, key=lambda c: '{0}_{1}'.format(c.getInstrumentID(), DirectType.Buy if c.getPosiDirection() == TThostFtdcPosiDirectionType.THOST_FTDC_PD_Long else DirectType.Sell)) # direction需从posidiction转换为dictiontype for key, group in itertools.groupby(self._posi, lambda c: '{0}_{1}'.format(c.getInstrumentID(), 'Buy' if c.getPosiDirection() == TThostFtdcPosiDirectionType.THOST_FTDC_PD_Long else 'Sell')): pf = self.positions.get(key) if not pf: pf = PositionField() self.positions[key] = pf pf.Position = 0 pf.TdPosition = 0 pf.YdPosition = 0 pf.CloseProfit = 0 pf.PositionProfit = 0 pf.Commission = 0 pf.Margin = 0 pf.Price = 0 cost = 0.0 for g in group: if not pf.InstrumentID: pf.InstrumentID = g.getInstrumentID() pf.Direction = DirectType.Buy if g.getPosiDirection() == TThostFtdcPosiDirectionType.THOST_FTDC_PD_Long else DirectType.Sell pf.Position += g.getPosition() pf.TdPosition += g.getTodayPosition() pf.YdPosition = pf.Position - pf.TdPosition pf.CloseProfit += g.getCloseProfit() pf.PositionProfit += g.getPositionProfit() pf.Commission += g.getCommission() pf.Margin += g.getUseMargin() cost += g.OpenCost # pf.Position <= 0 ? 0 : (g.Sum(n => n.PositionCost) / DicInstrumentField[pf.InstrumentID].VolumeMultiple / pf.Position); vm = self.instruments[pf.InstrumentID].VolumeMultiple pf.Price = 0 if pf.Position <= 0 else cost / vm / pf.Position self._posi.clear() def _OnRspQryPositionDetail(self, pInvestorPositionDetail: CThostFtdcInvestorPositionDetailField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """持仓明细""" if pInvestorPositionDetail.getInstrumentID() == '': return detail = PositionDetail() detail.Instrument = pInvestorPositionDetail.getInstrumentID() detail.CloseProfit = pInvestorPositionDetail.getCloseProfitByTrade() detail.Direction = DirectType.Buy if pInvestorPositionDetail.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell detail.HedgeFlag = HedgeType(list(TThostFtdcHedgeFlagType).index(pInvestorPositionDetail.getHedgeFlag())) detail.OpenDate = pInvestorPositionDetail.getOpenDate() detail.PositionProfit = pInvestorPositionDetail.getPositionProfitByTrade() detail.OpenPrice = pInvestorPositionDetail.getOpenPrice() detail.TradeType = TradeTypeType(list(TThostFtdcTradeTypeType).index(pInvestorPositionDetail.getTradeType())) detail.Volume = pInvestorPositionDetail.getVolume() self.position_details[pInvestorPositionDetail.getTradeID()] = detail def _OnRspQryAccount(self, pTradingAccount: CThostFtdcTradingAccountField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" if not self.account: self.account = TradingAccount() self.account.Available = pTradingAccount.getAvailable() self.account.CloseProfit = pTradingAccount.getCloseProfit() self.account.Commission = pTradingAccount.getCommission() self.account.CurrMargin = pTradingAccount.getCurrMargin() self.account.FrozenCash = pTradingAccount.getFrozenCash() self.account.PositionProfit = pTradingAccount.getPositionProfit() self.account.PreBalance = pTradingAccount.getPreBalance() + pTradingAccount.getDeposit() + pTradingAccount.getWithdraw() self.account.Fund = self.account.PreBalance + pTradingAccount.getCloseProfit() + pTradingAccount.getPositionProfit() - pTradingAccount.getCommission() self.account.Risk = 0 if self.account.Fund == 0 else self.account.CurrMargin / self.account.Fund def _OnRtnOrder(self, pOrder: CThostFtdcOrderField): """""" id = '{0}|{1}|{2}'.format(pOrder.getSessionID(), pOrder.getFrontID(), pOrder.getOrderRef()) of = self.orders.get(id) if not of: of = OrderField() if pOrder.getOrderRef().isdigit(): of.Custom = int(pOrder.getOrderRef()) % 1000000 of.InstrumentID = pOrder.getInstrumentID() of.InsertTime = pOrder.getInsertTime() of.Direction = DirectType.Buy if pOrder.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell ot = TThostFtdcOffsetFlagType(ord(pOrder.getCombOffsetFlag()[0])) of.Offset = OffsetType.Open if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open else OffsetType.CloseToday if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_CloseToday else OffsetType.Close of.Status = OrderStatus.Normal of.StatusMsg = pOrder.getStatusMsg() of.IsLocal = pOrder.getSessionID() == self.session of.LimitPrice = pOrder.getLimitPrice() of.OrderID = id of.Volume = pOrder.getVolumeTotalOriginal() of.VolumeLeft = of.Volume self.orders[id] = of threading.Thread(target=self.OnOrder, args=(self, of)).start() elif pOrder.getOrderStatus() == TThostFtdcOrderStatusType.THOST_FTDC_OST_Canceled: of.Status = OrderStatus.Canceled of.StatusMsg = pOrder.getStatusMsg() if of.StatusMsg.find('被拒绝') >= 0: info = InfoField() info.ErrorID = -1 info.ErrorMsg = of.StatusMsg threading.Thread(target=self.OnErrOrder, args=(self, of, info)).start() else: threading.Thread(target=self.OnCancel, args=(self, of)).start() else: if pOrder.getOrderSysID(): of.SysID = pOrder.getOrderSysID() self._orderid_sysid[pOrder.getOrderSysID()] = id # 记录sysid与orderid关联,方便Trade时查找处理 def _OnRtnTrade(self, f): """""" tf = TradeField() tf.Direction = DirectType.Buy if f.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell tf.ExchangeID = f.getExchangeID() tf.InstrumentID = f.getInstrumentID() tf.Offset = OffsetType.Open if f.getOffsetFlag() == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open else OffsetType.Close if f.getOffsetFlag() == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Close else OffsetType.CloseToday tf.Price = f.getPrice() tf.SysID = f.getOrderSysID() tf.TradeID = f.getTradeID() tf.TradeTime = f.getTradeTime() tf.TradingDay = f.getTradingDay() tf.Volume = f.getVolume() self.trades[tf.TradeID] = tf id = self._orderid_sysid[tf.SysID] of = self.orders[id] tf.OrderID = id # tradeid 与 orderid 关联 of.TradeTime = tf.TradeTime of.AvgPrice = (of.AvgPrice * (of.Volume - of.VolumeLeft) + tf.Price * tf.Volume) / (of.Volume - of.VolumeLeft + tf.Volume) of.TradeVolume = tf.Volume of.VolumeLeft -= tf.Volume if of.VolumeLeft == 0: of.Status = OrderStatus.Filled of.StatusMsg = '全部成交' else: of.Status = OrderStatus.Partial of.StatusMsg = '部分成交' # 更新持仓 ***** if tf.Offset == OffsetType.Open: key = '{0}_{1}'.format(tf.InstrumentID, 'Buy' if tf.Direction == DirectType.Buy else 'Sell') pf = self.positions.get(key) if not pf: pf = PositionField() self.positions[key] = pf pf.InstrumentID = tf.InstrumentID pf.Direction = tf.Direction pf.Price = (pf.Price * pf.Position + tf.Price * tf.Volume) / (pf.Position + tf.Volume) pf.TdPosition += tf.Volume pf.Position += tf.Volume else: key = '{0}_{1}'.format(tf.InstrumentID, DirectType.Sell if tf.Direction == DirectType.Buy else DirectType.Buy) pf = self.positions.get(key) if pf: # 有可能出现无持仓的情况 if tf.Offset == OffsetType.CloseToday: pf.TdPosition -= tf.Volume else: tdclose = min(pf.TdPosition, tf.Volume) if pf.TdPosition > 0: pf.TdPosition -= tdclose pf.YdPosition -= max(0, tf.Volume - tdclose) pf.Position -= tf.Volume threading.Thread(target=self._onRtn, args=(of, tf)).start() def _onRtn(self, of, tf): self.OnOrder(self, of) self.OnTrade(self, tf) def _OnRspOrder(self, pInputOrder: CThostFtdcInputOrderField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() id = '{0}|{1}|{2}'.format(self.session, '0', pInputOrder.getOrderRef()) of = self.orders.get(id) if not of: of = OrderField() l = int(pInputOrder.getOrderRef()) of.Custom = l % 1000000 of.InstrumentID = pInputOrder.getInstrumentID() of.InsertTime = time.strftime('%H:%M:%S', time.localtime()) # 对direction需特别处理(具体见ctp_struct) of.Direction = DirectType.Buy if pInputOrder.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell ot = TThostFtdcOffsetFlagType(ord(pInputOrder.getCombOffsetFlag()[0])) of.Offset = OffsetType.Open if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open else OffsetType.CloseToday if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_CloseToday else OffsetType.Close # of.Status = OrderStatus.Normal # of.StatusMsg = f.getStatusMsg() of.IsLocal = True of.LimitPrice = pInputOrder.getLimitPrice() of.OrderID = id of.Volume = pInputOrder.getVolumeTotalOriginal() of.VolumeLeft = of.Volume self.orders[id] = of of.Status = OrderStatus.Error of.StatusMsg = '{0}:{1}'.format(info.ErrorID, info.ErrorMsg) threading.Thread(target=self.OnErrOrder, args=(self, of, info)).start() def _OnErrOrder(self, pInputOrder: CThostFtdcInputOrderField, pRspInfo: CThostFtdcRspInfoField): """""" id = '{0}|{1}|{2}'.format(self.session, '0', pInputOrder.getOrderRef()) of = self.orders.get(id) info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() if of and of.IsLocal: of.Status = OrderStatus.Error of.StatusMsg = '{0}:{1}'.format(pRspInfo.getErrorID(), pRspInfo.getErrorMsg()) threading.Thread(target=self.OnErrOrder, args=(self, of, info)).start() def _OnRspOrderAction(self, pInputOrderAction: CThostFtdcInputOrderActionField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): id = "{0}|{1}|{2}".format(pInputOrderAction.getSessionID(), pInputOrderAction.getFrontID(), pInputOrderAction.getOrderRef()) if self.logined and id in self.orders: info = InfoField() info.ErrorID = pRspInfo.ErrorID info.ErrorMsg = pRspInfo.ErrorMsg threading.Thread(target=self.OnErrCancel, args=(self, self.orders[id], info)).start() def _OnRtnNotice(self, pTradingNoticeInfo: CThostFtdcTradingNoticeInfoField): '''交易提醒''' msg = pTradingNoticeInfo.getFieldContent() if len(msg) > 0: threading.Thread(target=self.OnRtnNotice, args=(self, pTradingNoticeInfo.getSendTime(), msg)).start() def _OnRtnQuote(self, pQuote: CThostFtdcQuoteField): threading.Thread(target=self.OnRtnQuote, args=(self, pQuote)).start() def _OnErrRtnQuote(self, pInputQuote: CThostFtdcInputQuoteField, pRspInfo: CThostFtdcRspInfoField): info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() threading.Thread(target=self.OnErrRtnQuote, args=(self, pInputQuote, info)).start() def _OnErrForQuoteInsert(self, pInputForQuote: CThostFtdcInputForQuoteField, pRspInfo: CThostFtdcRspInfoField): info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() threading.Thread(target=self.OnErrRtnForQuoteInsert, args=(self, pInputForQuote, info)).start() def ReqConnect(self, front: str): """连接交易前置 :param front: """ self.t.CreateApi() spi = self.t.CreateSpi() self.t.RegisterSpi(spi) self.t.OnFrontConnected = self._OnFrontConnected self.t.OnRspUserLogin = self._OnRspUserLogin self.t.OnFrontDisconnected = self._OnFrontDisconnected # self.t.OnRspUserLogout = self._OnRspUserLogout self.t.OnRspSettlementInfoConfirm = self._OnRspSettlementInfoConfirm self.t.OnRtnOrder = self._OnRtnOrder self.t.OnRtnTrade = self._OnRtnTrade self.t.OnRspOrderInsert = self._OnRspOrder self.t.OnErrRtnOrderInsert = self._OnErrOrder self.t.OnRspOrderAction = self._OnRspOrderAction self.t.OnRtnInstrumentStatus = self._OnRtnInstrumentStatus self.t.OnRspQryInstrument = self._OnRspQryInstrument self.t.OnRspQryTradingAccount = self._OnRspQryAccount self.t.OnRspQryInvestorPosition = self._OnRspQryPosition self.t.OnRspQryInvestorPositionDetail = self._OnRspQryPositionDetail self.t.OnRtnTradingNotice = self._OnRtnNotice self.t.OnRtnQuote = self._OnRtnQuote self.t.OnErrRtnQuoteInsert = self._OnErrRtnQuote self.t.OnErrRtnForQuoteInsert = self._OnErrForQuoteInsert self.front_address = front self.t.RegCB() self.t.RegisterFront(front) self.t.SubscribePrivateTopic(0) # restart 同步处理order trade self.t.SubscribePublicTopic(0) self.t.Init() # self.t.Join() def ReqUserLogin(self, user: str, pwd: str, broker: str): """登录 :param user: :param pwd: :param broker: """ self.broker = broker self.investor = user self.password = pwd self.t.ReqUserLogin(BrokerID=broker, UserID=user, Password=pwd) def ReqOrderInsert(self, pInstrument: str, pDirection: DirectType, pOffset: OffsetType, pPrice: float = 0.0, pVolume: int = 1, pType: OrderType = OrderType.Limit, pCustom: int = 0): """委托 :param pInstrument: :param pDirection: :param pOffset: :param pPrice: :param pVolume: :param pType: :param pCustom: :return: """ OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_AnyPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = 0.0 VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV if pType == OrderType.Market: # 市价 OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_AnyPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = 0.0 VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV elif pType == OrderType.Limit: # 限价 OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LimitPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_GFD LimitPrice = pPrice VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV elif pType == OrderType.FAK: # FAK OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LimitPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = pPrice VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV elif pType == OrderType.FOK: # FOK OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LimitPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = pPrice VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_CV # 全部数量 self._req += 1 self.t.ReqOrderInsert( BrokerID=self.broker, InvestorID=self.investor, InstrumentID=pInstrument, OrderRef="%06d%06d" % (self._req, pCustom % 1000000), UserID=self.investor, # 此处ctp_enum与at_struct名称冲突 Direction=TThostFtdcDirectionType.THOST_FTDC_D_Buy if pDirection == DirectType.Buy else TThostFtdcDirectionType.THOST_FTDC_D_Sell, CombOffsetFlag=chr(TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open.value if pOffset == OffsetType.Open else TThostFtdcOffsetFlagType.THOST_FTDC_OF_CloseToday.value if pOffset == OffsetType.CloseToday else TThostFtdcOffsetFlagType.THOST_FTDC_OF_Close.value), CombHedgeFlag=chr(TThostFtdcHedgeFlagType.THOST_FTDC_HF_Speculation.value), IsAutoSuspend=0, ForceCloseReason=TThostFtdcForceCloseReasonType.THOST_FTDC_FCC_NotForceClose, IsSwapOrder=0, ContingentCondition=TThostFtdcContingentConditionType.THOST_FTDC_CC_Immediately, VolumeCondition=VolumeCondition, MinVolume=1, VolumeTotalOriginal=pVolume, OrderPriceType=OrderPriceType, TimeCondition=TimeCondition, LimitPrice=LimitPrice, ) def ReqOrderAction(self, OrderID: str): """撤单 :param OrderID: """ of = self.orders[OrderID] if not of: return -1 else: pOrderId = of.OrderID return self.t.ReqOrderAction( self.broker, self.investor, OrderRef=pOrderId.split('|')[2], FrontID=int(pOrderId.split('|')[1]), SessionID=int(pOrderId.split('|')[0]), InstrumentID=of.InstrumentID, ActionFlag=TThostFtdcActionFlagType.THOST_FTDC_AF_Delete) def ReqUserLogout(self): """退出接口""" self.logined = False time.sleep(3) self.t.ReqUserLogout(BrokerID=self.broker, UserID=self.investor) self.t.RegisterSpi(None) self.t.Release() threading.Thread(target=self.OnDisConnected, args=(self, 0)).start() def OnConnected(self, obj): """接口连接 :param obj: """ print('=== [TRADE] OnConnected ==='.format('')) def OnDisConnected(self, obj, reason: int): """接口断开 :param obj: :param reason: """ print('=== [TRADE] OnDisConnected === \nreason: {0}'.format(reason)) def OnUserLogin(self, obj, info: InfoField): """登录响应 :param obj: :param info: """ print('=== [TRADE] OnUserLogin === \n{0}'.format(info)) def OnOrder(self, obj, f: OrderField): """委托响应 :param obj: :param f: """ print('=== [TRADE] OnOrder === \n{0}'.format(f.__dict__)) def OnTrade(self, obj, f: TradeField): """成交响应 :param obj: :param f: """ print('=== [TRADE] OnTrade === \n{0}'.format(f.__dict__)) def OnCancel(self, obj, f: OrderField): """ 撤单响应 :param self: :param obj: :param f:OrderField: """ print('=== [TRADE] OnCancel === \n{0}'.format(f.__dict__)) def OnErrOrder(self, obj, f: OrderField, info: InfoField): """ 委托错误 :param self: :param obj: :param f:OrderField: :param info:InfoField: """ print('=== [TRADE] OnErrOrder ===\n{0}'.format(f.__dict__)) print(info) def OnInstrumentStatus(self, obj, inst: str, status: InstrumentStatus): """ 交易状态 :param self: :param obj: :param inst:str: :param status:InstrumentStatus: """ print('{}:{}'.format(inst, str(status).strip().split('.')[-1])) def OnRtnNotice(self, obj, time: str, msg: str): """交易提醒 :param obj: :param time: :param msg: :return: """ print(f'=== OnRtnNotice===\n {time}:{msg}') def OnRtnQuote(self, obj, quote: CThostFtdcQuoteField): """报价通知 :param obj: :param quote: :return: """ print('=== [TRADE] OnRtnQuote ===\n{0}'.format(quote.__dict__)) def OnErrRtnQuote(self, obj, quote: CThostFtdcInputQuoteField, info: InfoField): """ :param obj: :param quote: :return: """ print('=== [TRADE] OnErrRtnQuote ===\n{0}'.format(quote.__dict__)) print(info) def OnErrRtnForQuoteInsert(self, obj, quote: CThostFtdcInputQuoteField, info: InfoField): """询价录入错误回报 :param obj: :param quote: :return: """ print('=== [TRADE] OnErrRtnForQuoteInsert ===\n{0}'.format(quote.__dict__)) print(info)
haifengat/hf_ctp_py_proxy
py_ctp/trade.py
CtpTrade.OnInstrumentStatus
python
def OnInstrumentStatus(self, obj, inst: str, status: InstrumentStatus): print('{}:{}'.format(inst, str(status).strip().split('.')[-1]))
交易状态 :param self: :param obj: :param inst:str: :param status:InstrumentStatus:
train
https://github.com/haifengat/hf_ctp_py_proxy/blob/c2dc6dbde45aa6b097f75380474e91510d3f5d12/py_ctp/trade.py#L614-L622
null
class CtpTrade(): """""" def __init__(self): self.front_address = '' self.investor = '' self.password = '' self.broker = '' self.logined = False self.tradingday = '' self.instruments = {} self.orders = {} self.trades = {} self.account: TradingAccount = None self.positions = {} self.instrument_status = {} self._req = 0 self._session = '' self._orderid_sysid = {} self._posi = [] self.t = Trade() def _OnFrontConnected(self): threading.Thread(target=self.OnConnected, args=(self,)).start() def _OnFrontDisconnected(self, nReason): self.logined = False print(nReason) # 下午收盘后会不停断开再连接 4097错误 if nReason == 4097 or nReason == 4098: threading.Thread(target=self._reconnect).start() else: threading.Thread(target=self.OnDisConnected, args=(self, nReason)).start() def _reconnect(self): if sum([1 if stat == 'Continous' else 0 for exc, stat in self.instrument_status.items()]) == 0: print(time.strftime('%Y%m%d %H:%M:%S', time.localtime())) self.t.Release() time.sleep(600) self.ReqConnect(self.front_address) # def _OnRspUserLogout(self, pUserLogout: CThostFtdcUserLogoutField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): # pass def _OnRspUserLogin(self, pRspUserLogin: CThostFtdcRspUserLoginField(), pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" if pRspInfo.getErrorID() == 0: self.session = pRspUserLogin.getSessionID() self.tradingday = pRspUserLogin.getTradingDay() self.t.ReqSettlementInfoConfirm(self.broker, self.investor) elif self.logined: threading.Thread(target=self._relogin).start() else: info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() threading.Thread(target=self.OnUserLogin, args=(self, info)).start() def _relogin(self): # 隔夜重连=>处理'初始化'错误 time.sleep(60 * 10) self.t.ReqUserLogin( BrokerID=self.broker, UserID=self.investor, Password=self.password, UserProductInfo='@haifeng') def _OnRspSettlementInfoConfirm( self, pSettlementInfoConfirm: CThostFtdcSettlementInfoConfirmField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): if not self.logined: time.sleep(0.5) """查询合约/持仓/权益""" threading.Thread(target=self._qry).start() # 开启查询 def _qry(self): """查询帐号相关信息""" # restart 模式, 待rtnorder 处理完毕后再进行查询,否则会造成position混乱 ord_cnt = 0 trd_cnt = 0 while True: time.sleep(0.5) if len(self.orders) == ord_cnt and len(self.trades) == trd_cnt: break ord_cnt = len(self.orders) trd_cnt = len(self.trades) self.t.ReqQryInstrument() time.sleep(1.1) self.t.ReqQryInvestorPosition(self.broker, self.investor) time.sleep(1.1) self.t.ReqQryTradingAccount(self.broker, self.investor) time.sleep(1.1) self.logined = True info = InfoField() info.ErrorID = 0 info.ErrorMsg = '正确' threading.Thread(target=self.OnUserLogin, args=(self, info)).start() # 调用Release后程序异常退出,但不报错误:接口断开了仍然调用了查询指令 while self.logined: """查询持仓与权益""" self.t.ReqQryInvestorPosition(self.broker, self.investor) time.sleep(1.1) if not self.logined: return self.t.ReqQryTradingAccount(self.broker, self.investor) time.sleep(1.1) def _OnRtnInstrumentStatus(self, pInstrumentStatus: CThostFtdcInstrumentStatusField): if pInstrumentStatus.getInstrumentID() == '': return status = InstrumentStatus.Continous if pInstrumentStatus.getInstrumentStatus() == TThostFtdcInstrumentStatusType.THOST_FTDC_IS_Continous: status = InstrumentStatus.Continous elif pInstrumentStatus.getInstrumentStatus() == TThostFtdcInstrumentStatusType.THOST_FTDC_IS_Closed: status = InstrumentStatus.Closed elif str(pInstrumentStatus.getInstrumentStatus()).startswith('Auction'): status = InstrumentStatus.Auction else: status = InstrumentStatus.NoTrading self.instrument_status[pInstrumentStatus.getInstrumentID()] = status self.OnInstrumentStatus(self, pInstrumentStatus.getInstrumentID(), status) def _OnRspQryInstrument(self, pInstrument: CThostFtdcInstrumentField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" inst = InstrumentField() inst.InstrumentID = pInstrument.getInstrumentID() inst.ProductID = pInstrument.getProductID() inst.ExchangeID = pInstrument.getExchangeID() inst.VolumeMultiple = pInstrument.getVolumeMultiple() inst.PriceTick = pInstrument.getPriceTick() inst.MaxOrderVolume = pInstrument.getMaxLimitOrderVolume() inst.ProductType = pInstrument.getProductClass().name # ProductClassType.Futures -> Futures self.instruments[inst.InstrumentID] = inst def _OnRspQryPosition(self, pInvestorPosition: CThostFtdcInvestorPositionField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" if pInvestorPosition.getInstrumentID() != '': # 偶尔出现NULL的数据导致数据转换错误 self._posi.append(pInvestorPosition) # Struct(**f.__dict__)) #dict -> object if bIsLast: # 先排序再group才有效 self._posi = sorted(self._posi, key=lambda c: '{0}_{1}'.format(c.getInstrumentID(), DirectType.Buy if c.getPosiDirection() == TThostFtdcPosiDirectionType.THOST_FTDC_PD_Long else DirectType.Sell)) # direction需从posidiction转换为dictiontype for key, group in itertools.groupby(self._posi, lambda c: '{0}_{1}'.format(c.getInstrumentID(), 'Buy' if c.getPosiDirection() == TThostFtdcPosiDirectionType.THOST_FTDC_PD_Long else 'Sell')): pf = self.positions.get(key) if not pf: pf = PositionField() self.positions[key] = pf pf.Position = 0 pf.TdPosition = 0 pf.YdPosition = 0 pf.CloseProfit = 0 pf.PositionProfit = 0 pf.Commission = 0 pf.Margin = 0 pf.Price = 0 cost = 0.0 for g in group: if not pf.InstrumentID: pf.InstrumentID = g.getInstrumentID() pf.Direction = DirectType.Buy if g.getPosiDirection() == TThostFtdcPosiDirectionType.THOST_FTDC_PD_Long else DirectType.Sell pf.Position += g.getPosition() pf.TdPosition += g.getTodayPosition() pf.YdPosition = pf.Position - pf.TdPosition pf.CloseProfit += g.getCloseProfit() pf.PositionProfit += g.getPositionProfit() pf.Commission += g.getCommission() pf.Margin += g.getUseMargin() cost += g.OpenCost # pf.Position <= 0 ? 0 : (g.Sum(n => n.PositionCost) / DicInstrumentField[pf.InstrumentID].VolumeMultiple / pf.Position); vm = self.instruments[pf.InstrumentID].VolumeMultiple pf.Price = 0 if pf.Position <= 0 else cost / vm / pf.Position self._posi.clear() def _OnRspQryPositionDetail(self, pInvestorPositionDetail: CThostFtdcInvestorPositionDetailField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """持仓明细""" if pInvestorPositionDetail.getInstrumentID() == '': return detail = PositionDetail() detail.Instrument = pInvestorPositionDetail.getInstrumentID() detail.CloseProfit = pInvestorPositionDetail.getCloseProfitByTrade() detail.Direction = DirectType.Buy if pInvestorPositionDetail.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell detail.HedgeFlag = HedgeType(list(TThostFtdcHedgeFlagType).index(pInvestorPositionDetail.getHedgeFlag())) detail.OpenDate = pInvestorPositionDetail.getOpenDate() detail.PositionProfit = pInvestorPositionDetail.getPositionProfitByTrade() detail.OpenPrice = pInvestorPositionDetail.getOpenPrice() detail.TradeType = TradeTypeType(list(TThostFtdcTradeTypeType).index(pInvestorPositionDetail.getTradeType())) detail.Volume = pInvestorPositionDetail.getVolume() self.position_details[pInvestorPositionDetail.getTradeID()] = detail def _OnRspQryAccount(self, pTradingAccount: CThostFtdcTradingAccountField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" if not self.account: self.account = TradingAccount() self.account.Available = pTradingAccount.getAvailable() self.account.CloseProfit = pTradingAccount.getCloseProfit() self.account.Commission = pTradingAccount.getCommission() self.account.CurrMargin = pTradingAccount.getCurrMargin() self.account.FrozenCash = pTradingAccount.getFrozenCash() self.account.PositionProfit = pTradingAccount.getPositionProfit() self.account.PreBalance = pTradingAccount.getPreBalance() + pTradingAccount.getDeposit() + pTradingAccount.getWithdraw() self.account.Fund = self.account.PreBalance + pTradingAccount.getCloseProfit() + pTradingAccount.getPositionProfit() - pTradingAccount.getCommission() self.account.Risk = 0 if self.account.Fund == 0 else self.account.CurrMargin / self.account.Fund def _OnRtnOrder(self, pOrder: CThostFtdcOrderField): """""" id = '{0}|{1}|{2}'.format(pOrder.getSessionID(), pOrder.getFrontID(), pOrder.getOrderRef()) of = self.orders.get(id) if not of: of = OrderField() if pOrder.getOrderRef().isdigit(): of.Custom = int(pOrder.getOrderRef()) % 1000000 of.InstrumentID = pOrder.getInstrumentID() of.InsertTime = pOrder.getInsertTime() of.Direction = DirectType.Buy if pOrder.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell ot = TThostFtdcOffsetFlagType(ord(pOrder.getCombOffsetFlag()[0])) of.Offset = OffsetType.Open if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open else OffsetType.CloseToday if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_CloseToday else OffsetType.Close of.Status = OrderStatus.Normal of.StatusMsg = pOrder.getStatusMsg() of.IsLocal = pOrder.getSessionID() == self.session of.LimitPrice = pOrder.getLimitPrice() of.OrderID = id of.Volume = pOrder.getVolumeTotalOriginal() of.VolumeLeft = of.Volume self.orders[id] = of threading.Thread(target=self.OnOrder, args=(self, of)).start() elif pOrder.getOrderStatus() == TThostFtdcOrderStatusType.THOST_FTDC_OST_Canceled: of.Status = OrderStatus.Canceled of.StatusMsg = pOrder.getStatusMsg() if of.StatusMsg.find('被拒绝') >= 0: info = InfoField() info.ErrorID = -1 info.ErrorMsg = of.StatusMsg threading.Thread(target=self.OnErrOrder, args=(self, of, info)).start() else: threading.Thread(target=self.OnCancel, args=(self, of)).start() else: if pOrder.getOrderSysID(): of.SysID = pOrder.getOrderSysID() self._orderid_sysid[pOrder.getOrderSysID()] = id # 记录sysid与orderid关联,方便Trade时查找处理 def _OnRtnTrade(self, f): """""" tf = TradeField() tf.Direction = DirectType.Buy if f.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell tf.ExchangeID = f.getExchangeID() tf.InstrumentID = f.getInstrumentID() tf.Offset = OffsetType.Open if f.getOffsetFlag() == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open else OffsetType.Close if f.getOffsetFlag() == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Close else OffsetType.CloseToday tf.Price = f.getPrice() tf.SysID = f.getOrderSysID() tf.TradeID = f.getTradeID() tf.TradeTime = f.getTradeTime() tf.TradingDay = f.getTradingDay() tf.Volume = f.getVolume() self.trades[tf.TradeID] = tf id = self._orderid_sysid[tf.SysID] of = self.orders[id] tf.OrderID = id # tradeid 与 orderid 关联 of.TradeTime = tf.TradeTime of.AvgPrice = (of.AvgPrice * (of.Volume - of.VolumeLeft) + tf.Price * tf.Volume) / (of.Volume - of.VolumeLeft + tf.Volume) of.TradeVolume = tf.Volume of.VolumeLeft -= tf.Volume if of.VolumeLeft == 0: of.Status = OrderStatus.Filled of.StatusMsg = '全部成交' else: of.Status = OrderStatus.Partial of.StatusMsg = '部分成交' # 更新持仓 ***** if tf.Offset == OffsetType.Open: key = '{0}_{1}'.format(tf.InstrumentID, 'Buy' if tf.Direction == DirectType.Buy else 'Sell') pf = self.positions.get(key) if not pf: pf = PositionField() self.positions[key] = pf pf.InstrumentID = tf.InstrumentID pf.Direction = tf.Direction pf.Price = (pf.Price * pf.Position + tf.Price * tf.Volume) / (pf.Position + tf.Volume) pf.TdPosition += tf.Volume pf.Position += tf.Volume else: key = '{0}_{1}'.format(tf.InstrumentID, DirectType.Sell if tf.Direction == DirectType.Buy else DirectType.Buy) pf = self.positions.get(key) if pf: # 有可能出现无持仓的情况 if tf.Offset == OffsetType.CloseToday: pf.TdPosition -= tf.Volume else: tdclose = min(pf.TdPosition, tf.Volume) if pf.TdPosition > 0: pf.TdPosition -= tdclose pf.YdPosition -= max(0, tf.Volume - tdclose) pf.Position -= tf.Volume threading.Thread(target=self._onRtn, args=(of, tf)).start() def _onRtn(self, of, tf): self.OnOrder(self, of) self.OnTrade(self, tf) def _OnRspOrder(self, pInputOrder: CThostFtdcInputOrderField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() id = '{0}|{1}|{2}'.format(self.session, '0', pInputOrder.getOrderRef()) of = self.orders.get(id) if not of: of = OrderField() l = int(pInputOrder.getOrderRef()) of.Custom = l % 1000000 of.InstrumentID = pInputOrder.getInstrumentID() of.InsertTime = time.strftime('%H:%M:%S', time.localtime()) # 对direction需特别处理(具体见ctp_struct) of.Direction = DirectType.Buy if pInputOrder.getDirection() == TThostFtdcDirectionType.THOST_FTDC_D_Buy else DirectType.Sell ot = TThostFtdcOffsetFlagType(ord(pInputOrder.getCombOffsetFlag()[0])) of.Offset = OffsetType.Open if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open else OffsetType.CloseToday if ot == TThostFtdcOffsetFlagType.THOST_FTDC_OF_CloseToday else OffsetType.Close # of.Status = OrderStatus.Normal # of.StatusMsg = f.getStatusMsg() of.IsLocal = True of.LimitPrice = pInputOrder.getLimitPrice() of.OrderID = id of.Volume = pInputOrder.getVolumeTotalOriginal() of.VolumeLeft = of.Volume self.orders[id] = of of.Status = OrderStatus.Error of.StatusMsg = '{0}:{1}'.format(info.ErrorID, info.ErrorMsg) threading.Thread(target=self.OnErrOrder, args=(self, of, info)).start() def _OnErrOrder(self, pInputOrder: CThostFtdcInputOrderField, pRspInfo: CThostFtdcRspInfoField): """""" id = '{0}|{1}|{2}'.format(self.session, '0', pInputOrder.getOrderRef()) of = self.orders.get(id) info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() if of and of.IsLocal: of.Status = OrderStatus.Error of.StatusMsg = '{0}:{1}'.format(pRspInfo.getErrorID(), pRspInfo.getErrorMsg()) threading.Thread(target=self.OnErrOrder, args=(self, of, info)).start() def _OnRspOrderAction(self, pInputOrderAction: CThostFtdcInputOrderActionField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): id = "{0}|{1}|{2}".format(pInputOrderAction.getSessionID(), pInputOrderAction.getFrontID(), pInputOrderAction.getOrderRef()) if self.logined and id in self.orders: info = InfoField() info.ErrorID = pRspInfo.ErrorID info.ErrorMsg = pRspInfo.ErrorMsg threading.Thread(target=self.OnErrCancel, args=(self, self.orders[id], info)).start() def _OnRtnNotice(self, pTradingNoticeInfo: CThostFtdcTradingNoticeInfoField): '''交易提醒''' msg = pTradingNoticeInfo.getFieldContent() if len(msg) > 0: threading.Thread(target=self.OnRtnNotice, args=(self, pTradingNoticeInfo.getSendTime(), msg)).start() def _OnRtnQuote(self, pQuote: CThostFtdcQuoteField): threading.Thread(target=self.OnRtnQuote, args=(self, pQuote)).start() def _OnErrRtnQuote(self, pInputQuote: CThostFtdcInputQuoteField, pRspInfo: CThostFtdcRspInfoField): info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() threading.Thread(target=self.OnErrRtnQuote, args=(self, pInputQuote, info)).start() def _OnErrForQuoteInsert(self, pInputForQuote: CThostFtdcInputForQuoteField, pRspInfo: CThostFtdcRspInfoField): info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() threading.Thread(target=self.OnErrRtnForQuoteInsert, args=(self, pInputForQuote, info)).start() def ReqConnect(self, front: str): """连接交易前置 :param front: """ self.t.CreateApi() spi = self.t.CreateSpi() self.t.RegisterSpi(spi) self.t.OnFrontConnected = self._OnFrontConnected self.t.OnRspUserLogin = self._OnRspUserLogin self.t.OnFrontDisconnected = self._OnFrontDisconnected # self.t.OnRspUserLogout = self._OnRspUserLogout self.t.OnRspSettlementInfoConfirm = self._OnRspSettlementInfoConfirm self.t.OnRtnOrder = self._OnRtnOrder self.t.OnRtnTrade = self._OnRtnTrade self.t.OnRspOrderInsert = self._OnRspOrder self.t.OnErrRtnOrderInsert = self._OnErrOrder self.t.OnRspOrderAction = self._OnRspOrderAction self.t.OnRtnInstrumentStatus = self._OnRtnInstrumentStatus self.t.OnRspQryInstrument = self._OnRspQryInstrument self.t.OnRspQryTradingAccount = self._OnRspQryAccount self.t.OnRspQryInvestorPosition = self._OnRspQryPosition self.t.OnRspQryInvestorPositionDetail = self._OnRspQryPositionDetail self.t.OnRtnTradingNotice = self._OnRtnNotice self.t.OnRtnQuote = self._OnRtnQuote self.t.OnErrRtnQuoteInsert = self._OnErrRtnQuote self.t.OnErrRtnForQuoteInsert = self._OnErrForQuoteInsert self.front_address = front self.t.RegCB() self.t.RegisterFront(front) self.t.SubscribePrivateTopic(0) # restart 同步处理order trade self.t.SubscribePublicTopic(0) self.t.Init() # self.t.Join() def ReqUserLogin(self, user: str, pwd: str, broker: str): """登录 :param user: :param pwd: :param broker: """ self.broker = broker self.investor = user self.password = pwd self.t.ReqUserLogin(BrokerID=broker, UserID=user, Password=pwd) def ReqOrderInsert(self, pInstrument: str, pDirection: DirectType, pOffset: OffsetType, pPrice: float = 0.0, pVolume: int = 1, pType: OrderType = OrderType.Limit, pCustom: int = 0): """委托 :param pInstrument: :param pDirection: :param pOffset: :param pPrice: :param pVolume: :param pType: :param pCustom: :return: """ OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_AnyPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = 0.0 VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV if pType == OrderType.Market: # 市价 OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_AnyPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = 0.0 VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV elif pType == OrderType.Limit: # 限价 OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LimitPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_GFD LimitPrice = pPrice VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV elif pType == OrderType.FAK: # FAK OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LimitPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = pPrice VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV elif pType == OrderType.FOK: # FOK OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LimitPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC LimitPrice = pPrice VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_CV # 全部数量 self._req += 1 self.t.ReqOrderInsert( BrokerID=self.broker, InvestorID=self.investor, InstrumentID=pInstrument, OrderRef="%06d%06d" % (self._req, pCustom % 1000000), UserID=self.investor, # 此处ctp_enum与at_struct名称冲突 Direction=TThostFtdcDirectionType.THOST_FTDC_D_Buy if pDirection == DirectType.Buy else TThostFtdcDirectionType.THOST_FTDC_D_Sell, CombOffsetFlag=chr(TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open.value if pOffset == OffsetType.Open else TThostFtdcOffsetFlagType.THOST_FTDC_OF_CloseToday.value if pOffset == OffsetType.CloseToday else TThostFtdcOffsetFlagType.THOST_FTDC_OF_Close.value), CombHedgeFlag=chr(TThostFtdcHedgeFlagType.THOST_FTDC_HF_Speculation.value), IsAutoSuspend=0, ForceCloseReason=TThostFtdcForceCloseReasonType.THOST_FTDC_FCC_NotForceClose, IsSwapOrder=0, ContingentCondition=TThostFtdcContingentConditionType.THOST_FTDC_CC_Immediately, VolumeCondition=VolumeCondition, MinVolume=1, VolumeTotalOriginal=pVolume, OrderPriceType=OrderPriceType, TimeCondition=TimeCondition, LimitPrice=LimitPrice, ) def ReqOrderAction(self, OrderID: str): """撤单 :param OrderID: """ of = self.orders[OrderID] if not of: return -1 else: pOrderId = of.OrderID return self.t.ReqOrderAction( self.broker, self.investor, OrderRef=pOrderId.split('|')[2], FrontID=int(pOrderId.split('|')[1]), SessionID=int(pOrderId.split('|')[0]), InstrumentID=of.InstrumentID, ActionFlag=TThostFtdcActionFlagType.THOST_FTDC_AF_Delete) def ReqUserLogout(self): """退出接口""" self.logined = False time.sleep(3) self.t.ReqUserLogout(BrokerID=self.broker, UserID=self.investor) self.t.RegisterSpi(None) self.t.Release() threading.Thread(target=self.OnDisConnected, args=(self, 0)).start() def OnConnected(self, obj): """接口连接 :param obj: """ print('=== [TRADE] OnConnected ==='.format('')) def OnDisConnected(self, obj, reason: int): """接口断开 :param obj: :param reason: """ print('=== [TRADE] OnDisConnected === \nreason: {0}'.format(reason)) def OnUserLogin(self, obj, info: InfoField): """登录响应 :param obj: :param info: """ print('=== [TRADE] OnUserLogin === \n{0}'.format(info)) def OnOrder(self, obj, f: OrderField): """委托响应 :param obj: :param f: """ print('=== [TRADE] OnOrder === \n{0}'.format(f.__dict__)) def OnTrade(self, obj, f: TradeField): """成交响应 :param obj: :param f: """ print('=== [TRADE] OnTrade === \n{0}'.format(f.__dict__)) def OnCancel(self, obj, f: OrderField): """ 撤单响应 :param self: :param obj: :param f:OrderField: """ print('=== [TRADE] OnCancel === \n{0}'.format(f.__dict__)) def OnErrCancel(self, obj, f: OrderField, info: InfoField): """ 撤单失败 :param self: :param obj: :param f:OrderField: :param info:InfoField: """ print('=== [TRADE] OnErrCancel ===\n{0}'.format(f.__dict__)) print(info) def OnErrOrder(self, obj, f: OrderField, info: InfoField): """ 委托错误 :param self: :param obj: :param f:OrderField: :param info:InfoField: """ print('=== [TRADE] OnErrOrder ===\n{0}'.format(f.__dict__)) print(info) def OnRtnNotice(self, obj, time: str, msg: str): """交易提醒 :param obj: :param time: :param msg: :return: """ print(f'=== OnRtnNotice===\n {time}:{msg}') def OnRtnQuote(self, obj, quote: CThostFtdcQuoteField): """报价通知 :param obj: :param quote: :return: """ print('=== [TRADE] OnRtnQuote ===\n{0}'.format(quote.__dict__)) def OnErrRtnQuote(self, obj, quote: CThostFtdcInputQuoteField, info: InfoField): """ :param obj: :param quote: :return: """ print('=== [TRADE] OnErrRtnQuote ===\n{0}'.format(quote.__dict__)) print(info) def OnErrRtnForQuoteInsert(self, obj, quote: CThostFtdcInputQuoteField, info: InfoField): """询价录入错误回报 :param obj: :param quote: :return: """ print('=== [TRADE] OnErrRtnForQuoteInsert ===\n{0}'.format(quote.__dict__)) print(info)
haifengat/hf_ctp_py_proxy
py_ctp/quote.py
CtpQuote.ReqConnect
python
def ReqConnect(self, pAddress: str): self.q.CreateApi() spi = self.q.CreateSpi() self.q.RegisterSpi(spi) self.q.OnFrontConnected = self._OnFrontConnected self.q.OnFrontDisconnected = self._OnFrontDisConnected self.q.OnRspUserLogin = self._OnRspUserLogin self.q.OnRtnDepthMarketData = self._OnRtnDepthMarketData self.q.OnRspSubMarketData = self._OnRspSubMarketData self.q.RegCB() self.q.RegisterFront(pAddress) self.q.Init()
连接行情前置 :param pAddress:
train
https://github.com/haifengat/hf_ctp_py_proxy/blob/c2dc6dbde45aa6b097f75380474e91510d3f5d12/py_ctp/quote.py#L26-L44
null
class CtpQuote(object): """""" def __init__(self): self.q = Quote() self.inst_tick = {} self.logined = False def ReqUserLogin(self, user: str, pwd: str, broker: str): """登录 :param user: :param pwd: :param broker: """ self.q.ReqUserLogin(BrokerID=broker, UserID=user, Password=pwd) def ReqSubscribeMarketData(self, pInstrument: str): """订阅合约行情 :param pInstrument: """ self.q.SubscribeMarketData(pInstrument) def ReqUserLogout(self): """退出接口(正常退出,不会触发OnFrontDisconnected)""" self.q.Release() # 确保隔夜或重新登录时的第1个tick不被发送到客户端 self.inst_tick.clear() self.logined = False threading.Thread(target=self.OnDisConnected, args=(self, 0)).start() def _OnFrontConnected(self): """""" threading.Thread(target=self.OnConnected, args=(self,)).start() def _OnFrontDisConnected(self, reason: int): """""" # 确保隔夜或重新登录时的第1个tick不被发送到客户端 self.inst_tick.clear() self.logined = False threading.Thread(target=self.OnDisConnected, args=(self, reason)).start() def _OnRspUserLogin(self, pRspUserLogin: CThostFtdcRspUserLoginField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() self.logined = True threading.Thread(target=self.OnUserLogin, args=(self, info)).start() def _OnRspSubMarketData(self, pSpecificInstrument: CThostFtdcSpecificInstrumentField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): pass def _OnRtnDepthMarketData(self, pDepthMarketData: CThostFtdcDepthMarketDataField): """""" tick: Tick = None # 这个逻辑交由应用端处理更合理 ==> 第一个tick不送给客户端(以处理隔夜早盘时收到夜盘的数据的问题) inst = pDepthMarketData.getInstrumentID() if inst not in self.inst_tick: tick = Tick() self.inst_tick[inst] = tick else: tick = self.inst_tick[inst] tick.AskPrice = pDepthMarketData.getAskPrice1() tick.AskVolume = pDepthMarketData.getAskVolume1() tick.AveragePrice = pDepthMarketData.getAveragePrice() tick.BidPrice = pDepthMarketData.getBidPrice1() tick.BidVolume = pDepthMarketData.getBidVolume1() tick.Instrument = pDepthMarketData.getInstrumentID() tick.LastPrice = pDepthMarketData.getLastPrice() tick.OpenInterest = pDepthMarketData.getOpenInterest() tick.Volume = pDepthMarketData.getVolume() # 用tradingday替代Actionday不可取 # day = pDepthMarketData.getTradingDay() # str = day + ' ' + pDepthMarketData.getUpdateTime() # if day is None or day == ' ': # str = time.strftime('%Y%m%d %H:%M:%S', time.localtime()) # tick.UpdateTime = str # time.strptime(str, '%Y%m%d %H:%M:%S') tick.UpdateTime = pDepthMarketData.getUpdateTime() tick.UpdateMillisec = pDepthMarketData.getUpdateMillisec() tick.UpperLimitPrice = pDepthMarketData.getUpperLimitPrice() tick.LowerLimitPrice = pDepthMarketData.getLowerLimitPrice() tick.PreOpenInterest = pDepthMarketData.getPreOpenInterest() # 用线程会导入多数据入库时报错 # threading.Thread(target=self.OnTick, (self, tick)) self.OnTick(self, tick) def OnDisConnected(self, obj, error: int): """""" print(f'=== [QUOTE] OnDisConnected===\nerror: {str(error)}') def OnConnected(self, obj): """""" print('=== [QUOTE] OnConnected ===') def OnUserLogin(self, obj, info: InfoField): """""" print(f'=== [QUOTE] OnUserLogin ===\n{info}') def OnTick(self, obj, f: Tick): """""" print(f'=== [QUOTE] OnTick ===\n{f.__dict__}')
haifengat/hf_ctp_py_proxy
py_ctp/quote.py
CtpQuote.ReqUserLogin
python
def ReqUserLogin(self, user: str, pwd: str, broker: str): self.q.ReqUserLogin(BrokerID=broker, UserID=user, Password=pwd)
登录 :param user: :param pwd: :param broker:
train
https://github.com/haifengat/hf_ctp_py_proxy/blob/c2dc6dbde45aa6b097f75380474e91510d3f5d12/py_ctp/quote.py#L46-L53
null
class CtpQuote(object): """""" def __init__(self): self.q = Quote() self.inst_tick = {} self.logined = False def ReqConnect(self, pAddress: str): """连接行情前置 :param pAddress: """ self.q.CreateApi() spi = self.q.CreateSpi() self.q.RegisterSpi(spi) self.q.OnFrontConnected = self._OnFrontConnected self.q.OnFrontDisconnected = self._OnFrontDisConnected self.q.OnRspUserLogin = self._OnRspUserLogin self.q.OnRtnDepthMarketData = self._OnRtnDepthMarketData self.q.OnRspSubMarketData = self._OnRspSubMarketData self.q.RegCB() self.q.RegisterFront(pAddress) self.q.Init() def ReqSubscribeMarketData(self, pInstrument: str): """订阅合约行情 :param pInstrument: """ self.q.SubscribeMarketData(pInstrument) def ReqUserLogout(self): """退出接口(正常退出,不会触发OnFrontDisconnected)""" self.q.Release() # 确保隔夜或重新登录时的第1个tick不被发送到客户端 self.inst_tick.clear() self.logined = False threading.Thread(target=self.OnDisConnected, args=(self, 0)).start() def _OnFrontConnected(self): """""" threading.Thread(target=self.OnConnected, args=(self,)).start() def _OnFrontDisConnected(self, reason: int): """""" # 确保隔夜或重新登录时的第1个tick不被发送到客户端 self.inst_tick.clear() self.logined = False threading.Thread(target=self.OnDisConnected, args=(self, reason)).start() def _OnRspUserLogin(self, pRspUserLogin: CThostFtdcRspUserLoginField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() self.logined = True threading.Thread(target=self.OnUserLogin, args=(self, info)).start() def _OnRspSubMarketData(self, pSpecificInstrument: CThostFtdcSpecificInstrumentField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): pass def _OnRtnDepthMarketData(self, pDepthMarketData: CThostFtdcDepthMarketDataField): """""" tick: Tick = None # 这个逻辑交由应用端处理更合理 ==> 第一个tick不送给客户端(以处理隔夜早盘时收到夜盘的数据的问题) inst = pDepthMarketData.getInstrumentID() if inst not in self.inst_tick: tick = Tick() self.inst_tick[inst] = tick else: tick = self.inst_tick[inst] tick.AskPrice = pDepthMarketData.getAskPrice1() tick.AskVolume = pDepthMarketData.getAskVolume1() tick.AveragePrice = pDepthMarketData.getAveragePrice() tick.BidPrice = pDepthMarketData.getBidPrice1() tick.BidVolume = pDepthMarketData.getBidVolume1() tick.Instrument = pDepthMarketData.getInstrumentID() tick.LastPrice = pDepthMarketData.getLastPrice() tick.OpenInterest = pDepthMarketData.getOpenInterest() tick.Volume = pDepthMarketData.getVolume() # 用tradingday替代Actionday不可取 # day = pDepthMarketData.getTradingDay() # str = day + ' ' + pDepthMarketData.getUpdateTime() # if day is None or day == ' ': # str = time.strftime('%Y%m%d %H:%M:%S', time.localtime()) # tick.UpdateTime = str # time.strptime(str, '%Y%m%d %H:%M:%S') tick.UpdateTime = pDepthMarketData.getUpdateTime() tick.UpdateMillisec = pDepthMarketData.getUpdateMillisec() tick.UpperLimitPrice = pDepthMarketData.getUpperLimitPrice() tick.LowerLimitPrice = pDepthMarketData.getLowerLimitPrice() tick.PreOpenInterest = pDepthMarketData.getPreOpenInterest() # 用线程会导入多数据入库时报错 # threading.Thread(target=self.OnTick, (self, tick)) self.OnTick(self, tick) def OnDisConnected(self, obj, error: int): """""" print(f'=== [QUOTE] OnDisConnected===\nerror: {str(error)}') def OnConnected(self, obj): """""" print('=== [QUOTE] OnConnected ===') def OnUserLogin(self, obj, info: InfoField): """""" print(f'=== [QUOTE] OnUserLogin ===\n{info}') def OnTick(self, obj, f: Tick): """""" print(f'=== [QUOTE] OnTick ===\n{f.__dict__}')
haifengat/hf_ctp_py_proxy
py_ctp/quote.py
CtpQuote.ReqUserLogout
python
def ReqUserLogout(self): self.q.Release() # 确保隔夜或重新登录时的第1个tick不被发送到客户端 self.inst_tick.clear() self.logined = False threading.Thread(target=self.OnDisConnected, args=(self, 0)).start()
退出接口(正常退出,不会触发OnFrontDisconnected)
train
https://github.com/haifengat/hf_ctp_py_proxy/blob/c2dc6dbde45aa6b097f75380474e91510d3f5d12/py_ctp/quote.py#L62-L69
null
class CtpQuote(object): """""" def __init__(self): self.q = Quote() self.inst_tick = {} self.logined = False def ReqConnect(self, pAddress: str): """连接行情前置 :param pAddress: """ self.q.CreateApi() spi = self.q.CreateSpi() self.q.RegisterSpi(spi) self.q.OnFrontConnected = self._OnFrontConnected self.q.OnFrontDisconnected = self._OnFrontDisConnected self.q.OnRspUserLogin = self._OnRspUserLogin self.q.OnRtnDepthMarketData = self._OnRtnDepthMarketData self.q.OnRspSubMarketData = self._OnRspSubMarketData self.q.RegCB() self.q.RegisterFront(pAddress) self.q.Init() def ReqUserLogin(self, user: str, pwd: str, broker: str): """登录 :param user: :param pwd: :param broker: """ self.q.ReqUserLogin(BrokerID=broker, UserID=user, Password=pwd) def ReqSubscribeMarketData(self, pInstrument: str): """订阅合约行情 :param pInstrument: """ self.q.SubscribeMarketData(pInstrument) def _OnFrontConnected(self): """""" threading.Thread(target=self.OnConnected, args=(self,)).start() def _OnFrontDisConnected(self, reason: int): """""" # 确保隔夜或重新登录时的第1个tick不被发送到客户端 self.inst_tick.clear() self.logined = False threading.Thread(target=self.OnDisConnected, args=(self, reason)).start() def _OnRspUserLogin(self, pRspUserLogin: CThostFtdcRspUserLoginField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): """""" info = InfoField() info.ErrorID = pRspInfo.getErrorID() info.ErrorMsg = pRspInfo.getErrorMsg() self.logined = True threading.Thread(target=self.OnUserLogin, args=(self, info)).start() def _OnRspSubMarketData(self, pSpecificInstrument: CThostFtdcSpecificInstrumentField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): pass def _OnRtnDepthMarketData(self, pDepthMarketData: CThostFtdcDepthMarketDataField): """""" tick: Tick = None # 这个逻辑交由应用端处理更合理 ==> 第一个tick不送给客户端(以处理隔夜早盘时收到夜盘的数据的问题) inst = pDepthMarketData.getInstrumentID() if inst not in self.inst_tick: tick = Tick() self.inst_tick[inst] = tick else: tick = self.inst_tick[inst] tick.AskPrice = pDepthMarketData.getAskPrice1() tick.AskVolume = pDepthMarketData.getAskVolume1() tick.AveragePrice = pDepthMarketData.getAveragePrice() tick.BidPrice = pDepthMarketData.getBidPrice1() tick.BidVolume = pDepthMarketData.getBidVolume1() tick.Instrument = pDepthMarketData.getInstrumentID() tick.LastPrice = pDepthMarketData.getLastPrice() tick.OpenInterest = pDepthMarketData.getOpenInterest() tick.Volume = pDepthMarketData.getVolume() # 用tradingday替代Actionday不可取 # day = pDepthMarketData.getTradingDay() # str = day + ' ' + pDepthMarketData.getUpdateTime() # if day is None or day == ' ': # str = time.strftime('%Y%m%d %H:%M:%S', time.localtime()) # tick.UpdateTime = str # time.strptime(str, '%Y%m%d %H:%M:%S') tick.UpdateTime = pDepthMarketData.getUpdateTime() tick.UpdateMillisec = pDepthMarketData.getUpdateMillisec() tick.UpperLimitPrice = pDepthMarketData.getUpperLimitPrice() tick.LowerLimitPrice = pDepthMarketData.getLowerLimitPrice() tick.PreOpenInterest = pDepthMarketData.getPreOpenInterest() # 用线程会导入多数据入库时报错 # threading.Thread(target=self.OnTick, (self, tick)) self.OnTick(self, tick) def OnDisConnected(self, obj, error: int): """""" print(f'=== [QUOTE] OnDisConnected===\nerror: {str(error)}') def OnConnected(self, obj): """""" print('=== [QUOTE] OnConnected ===') def OnUserLogin(self, obj, info: InfoField): """""" print(f'=== [QUOTE] OnUserLogin ===\n{info}') def OnTick(self, obj, f: Tick): """""" print(f'=== [QUOTE] OnTick ===\n{f.__dict__}')
outini/python-pylls
pylls/cachet.py
Components.groups
python
def groups(self): if not self._groups: self._groups = ComponentGroups(self.api_client) return self._groups
Component groups Special property which point to a :class:`~pylls.cachet.ComponentGroups` instance for convenience. This instance is initialized on first call.
train
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L86-L94
null
class Components(client.CachetAPIEndPoint): """Components API endpoint """ def __init__(self, *args, **kwargs): """Initialization method""" super(Components, self).__init__(*args, **kwargs) self._groups = None @property def get(self, component_id=None, **kwargs): """Get components :param component_id: Component ID (optional) :return: Components data (:class:`Generator`) Additional named arguments may be passed and are directly transmitted to API. It is useful to use the API search features. .. seealso:: https://docs.cachethq.io/reference#get-components .. seealso:: https://docs.cachethq.io/docs/advanced-api-usage """ path = 'components' if component_id is not None: path += '/%s' % component_id return self.paginate_get(path, data=kwargs) def create(self, name, status, description="", link="", order=0, group_id=0, enabled=True): """Create a new component :param str name: Name of the component :param int status: Status of the component; 1-4 :param str description: Description of the component (optional) :param str link: A hyperlink to the component (optional) :param int order: Order of the component (optional) :param int group_id: The group ID of the component (optional) :param bool enabled: Whether the component is enabled (optional) :return: Created component data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#components .. seealso:: https://docs.cachethq.io/docs/component-statuses """ data = ApiParams() data['name'] = name data['status'] = status data['description'] = description data['link'] = link data['order'] = order data['group_id'] = group_id data['enabled'] = enabled return self._post('components', data=data)['data'] def update(self, component_id, name=None, status=None, description=None, link=None, order=None, group_id=None, enabled=True): """Update a component :param int component_id: Component ID :param str name: Name of the component (optional) :param int status: Status of the component; 1-4 :param str description: Description of the component (optional) :param str link: A hyperlink to the component (optional) :param int order: Order of the component (optional) :param int group_id: The group ID of the component (optional) :param bool enabled: Whether the component is enabled (optional) :return: Updated component data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#components .. seealso:: https://docs.cachethq.io/docs/component-statuses """ data = ApiParams() data['component'] = component_id data['name'] = name data['status'] = status data['description'] = description data['link'] = link data['order'] = order data['group_id'] = group_id data['enabled'] = enabled return self._put('components/%s' % component_id, data=data)['data'] def delete(self, component_id): """Delete a component :param int component_id: Component ID :return: :obj:`None` .. seealso:: https://docs.cachethq.io/reference#delete-a-components """ self._delete('components/%s' % component_id)
outini/python-pylls
pylls/cachet.py
Components.get
python
def get(self, component_id=None, **kwargs): path = 'components' if component_id is not None: path += '/%s' % component_id return self.paginate_get(path, data=kwargs)
Get components :param component_id: Component ID (optional) :return: Components data (:class:`Generator`) Additional named arguments may be passed and are directly transmitted to API. It is useful to use the API search features. .. seealso:: https://docs.cachethq.io/reference#get-components .. seealso:: https://docs.cachethq.io/docs/advanced-api-usage
train
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L96-L111
null
class Components(client.CachetAPIEndPoint): """Components API endpoint """ def __init__(self, *args, **kwargs): """Initialization method""" super(Components, self).__init__(*args, **kwargs) self._groups = None @property def groups(self): """Component groups Special property which point to a :class:`~pylls.cachet.ComponentGroups` instance for convenience. This instance is initialized on first call. """ if not self._groups: self._groups = ComponentGroups(self.api_client) return self._groups def create(self, name, status, description="", link="", order=0, group_id=0, enabled=True): """Create a new component :param str name: Name of the component :param int status: Status of the component; 1-4 :param str description: Description of the component (optional) :param str link: A hyperlink to the component (optional) :param int order: Order of the component (optional) :param int group_id: The group ID of the component (optional) :param bool enabled: Whether the component is enabled (optional) :return: Created component data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#components .. seealso:: https://docs.cachethq.io/docs/component-statuses """ data = ApiParams() data['name'] = name data['status'] = status data['description'] = description data['link'] = link data['order'] = order data['group_id'] = group_id data['enabled'] = enabled return self._post('components', data=data)['data'] def update(self, component_id, name=None, status=None, description=None, link=None, order=None, group_id=None, enabled=True): """Update a component :param int component_id: Component ID :param str name: Name of the component (optional) :param int status: Status of the component; 1-4 :param str description: Description of the component (optional) :param str link: A hyperlink to the component (optional) :param int order: Order of the component (optional) :param int group_id: The group ID of the component (optional) :param bool enabled: Whether the component is enabled (optional) :return: Updated component data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#components .. seealso:: https://docs.cachethq.io/docs/component-statuses """ data = ApiParams() data['component'] = component_id data['name'] = name data['status'] = status data['description'] = description data['link'] = link data['order'] = order data['group_id'] = group_id data['enabled'] = enabled return self._put('components/%s' % component_id, data=data)['data'] def delete(self, component_id): """Delete a component :param int component_id: Component ID :return: :obj:`None` .. seealso:: https://docs.cachethq.io/reference#delete-a-components """ self._delete('components/%s' % component_id)
outini/python-pylls
pylls/cachet.py
Components.create
python
def create(self, name, status, description="", link="", order=0, group_id=0, enabled=True): data = ApiParams() data['name'] = name data['status'] = status data['description'] = description data['link'] = link data['order'] = order data['group_id'] = group_id data['enabled'] = enabled return self._post('components', data=data)['data']
Create a new component :param str name: Name of the component :param int status: Status of the component; 1-4 :param str description: Description of the component (optional) :param str link: A hyperlink to the component (optional) :param int order: Order of the component (optional) :param int group_id: The group ID of the component (optional) :param bool enabled: Whether the component is enabled (optional) :return: Created component data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#components .. seealso:: https://docs.cachethq.io/docs/component-statuses
train
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L113-L137
null
class Components(client.CachetAPIEndPoint): """Components API endpoint """ def __init__(self, *args, **kwargs): """Initialization method""" super(Components, self).__init__(*args, **kwargs) self._groups = None @property def groups(self): """Component groups Special property which point to a :class:`~pylls.cachet.ComponentGroups` instance for convenience. This instance is initialized on first call. """ if not self._groups: self._groups = ComponentGroups(self.api_client) return self._groups def get(self, component_id=None, **kwargs): """Get components :param component_id: Component ID (optional) :return: Components data (:class:`Generator`) Additional named arguments may be passed and are directly transmitted to API. It is useful to use the API search features. .. seealso:: https://docs.cachethq.io/reference#get-components .. seealso:: https://docs.cachethq.io/docs/advanced-api-usage """ path = 'components' if component_id is not None: path += '/%s' % component_id return self.paginate_get(path, data=kwargs) def update(self, component_id, name=None, status=None, description=None, link=None, order=None, group_id=None, enabled=True): """Update a component :param int component_id: Component ID :param str name: Name of the component (optional) :param int status: Status of the component; 1-4 :param str description: Description of the component (optional) :param str link: A hyperlink to the component (optional) :param int order: Order of the component (optional) :param int group_id: The group ID of the component (optional) :param bool enabled: Whether the component is enabled (optional) :return: Updated component data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#components .. seealso:: https://docs.cachethq.io/docs/component-statuses """ data = ApiParams() data['component'] = component_id data['name'] = name data['status'] = status data['description'] = description data['link'] = link data['order'] = order data['group_id'] = group_id data['enabled'] = enabled return self._put('components/%s' % component_id, data=data)['data'] def delete(self, component_id): """Delete a component :param int component_id: Component ID :return: :obj:`None` .. seealso:: https://docs.cachethq.io/reference#delete-a-components """ self._delete('components/%s' % component_id)
outini/python-pylls
pylls/cachet.py
Components.update
python
def update(self, component_id, name=None, status=None, description=None, link=None, order=None, group_id=None, enabled=True): data = ApiParams() data['component'] = component_id data['name'] = name data['status'] = status data['description'] = description data['link'] = link data['order'] = order data['group_id'] = group_id data['enabled'] = enabled return self._put('components/%s' % component_id, data=data)['data']
Update a component :param int component_id: Component ID :param str name: Name of the component (optional) :param int status: Status of the component; 1-4 :param str description: Description of the component (optional) :param str link: A hyperlink to the component (optional) :param int order: Order of the component (optional) :param int group_id: The group ID of the component (optional) :param bool enabled: Whether the component is enabled (optional) :return: Updated component data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#components .. seealso:: https://docs.cachethq.io/docs/component-statuses
train
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L139-L165
null
class Components(client.CachetAPIEndPoint): """Components API endpoint """ def __init__(self, *args, **kwargs): """Initialization method""" super(Components, self).__init__(*args, **kwargs) self._groups = None @property def groups(self): """Component groups Special property which point to a :class:`~pylls.cachet.ComponentGroups` instance for convenience. This instance is initialized on first call. """ if not self._groups: self._groups = ComponentGroups(self.api_client) return self._groups def get(self, component_id=None, **kwargs): """Get components :param component_id: Component ID (optional) :return: Components data (:class:`Generator`) Additional named arguments may be passed and are directly transmitted to API. It is useful to use the API search features. .. seealso:: https://docs.cachethq.io/reference#get-components .. seealso:: https://docs.cachethq.io/docs/advanced-api-usage """ path = 'components' if component_id is not None: path += '/%s' % component_id return self.paginate_get(path, data=kwargs) def create(self, name, status, description="", link="", order=0, group_id=0, enabled=True): """Create a new component :param str name: Name of the component :param int status: Status of the component; 1-4 :param str description: Description of the component (optional) :param str link: A hyperlink to the component (optional) :param int order: Order of the component (optional) :param int group_id: The group ID of the component (optional) :param bool enabled: Whether the component is enabled (optional) :return: Created component data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#components .. seealso:: https://docs.cachethq.io/docs/component-statuses """ data = ApiParams() data['name'] = name data['status'] = status data['description'] = description data['link'] = link data['order'] = order data['group_id'] = group_id data['enabled'] = enabled return self._post('components', data=data)['data'] def delete(self, component_id): """Delete a component :param int component_id: Component ID :return: :obj:`None` .. seealso:: https://docs.cachethq.io/reference#delete-a-components """ self._delete('components/%s' % component_id)
outini/python-pylls
pylls/cachet.py
ComponentGroups.get
python
def get(self, group_id=None, **kwargs): path = 'components/groups' if group_id is not None: path += '/%s' % group_id return self.paginate_get(path, data=kwargs)
Get component groups :param group_id: Component group ID (optional) :return: Component groups data (:class:`dict`) Additional named arguments may be passed and are directly transmitted to API. It is useful to use the API search features. .. seealso:: https://docs.cachethq.io/reference#get-componentgroups .. seealso:: https://docs.cachethq.io/docs/advanced-api-usage
train
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L185-L200
null
class ComponentGroups(client.CachetAPIEndPoint): """Component groups API endpoint """ def __init__(self, *args, **kwargs): """Initialization method""" super(ComponentGroups, self).__init__(*args, **kwargs) def create(self, name, order=None, collapsed=None): """Create a new Component Group :param str name: Name of the component group :param int order: Order of the component group :param int collapsed: Collapse the group? 0-2 :return: Created component group data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#post-componentgroups """ data = ApiParams() data['name'] = name data['order'] = order data['collapsed'] = collapsed return self._post('components/groups', data=data)['data'] def update(self, group_id, name=None, order=None, collapsed=None): """Update a Component Group :param int group_id: Component Group ID :param str name: Name of the component group :param int order: Order of the group :param int collapsed: Collapse the group? :return: Updated component group data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#put-component-group """ data = ApiParams() data['group'] = group_id data['name'] = name data['order'] = order data['collapsed'] = collapsed return self._put('components/groups/%s' % group_id, data=data)['data'] def delete(self, group_id): """Delete a Component Group :param int group_id: Component Group ID :return: :obj:`None` .. seealso:: https://docs.cachethq.io/reference#delete-a-component """ self._delete('components/groups/%s' % group_id)
outini/python-pylls
pylls/cachet.py
ComponentGroups.create
python
def create(self, name, order=None, collapsed=None): data = ApiParams() data['name'] = name data['order'] = order data['collapsed'] = collapsed return self._post('components/groups', data=data)['data']
Create a new Component Group :param str name: Name of the component group :param int order: Order of the component group :param int collapsed: Collapse the group? 0-2 :return: Created component group data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#post-componentgroups
train
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L202-L216
null
class ComponentGroups(client.CachetAPIEndPoint): """Component groups API endpoint """ def __init__(self, *args, **kwargs): """Initialization method""" super(ComponentGroups, self).__init__(*args, **kwargs) def get(self, group_id=None, **kwargs): """Get component groups :param group_id: Component group ID (optional) :return: Component groups data (:class:`dict`) Additional named arguments may be passed and are directly transmitted to API. It is useful to use the API search features. .. seealso:: https://docs.cachethq.io/reference#get-componentgroups .. seealso:: https://docs.cachethq.io/docs/advanced-api-usage """ path = 'components/groups' if group_id is not None: path += '/%s' % group_id return self.paginate_get(path, data=kwargs) def update(self, group_id, name=None, order=None, collapsed=None): """Update a Component Group :param int group_id: Component Group ID :param str name: Name of the component group :param int order: Order of the group :param int collapsed: Collapse the group? :return: Updated component group data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#put-component-group """ data = ApiParams() data['group'] = group_id data['name'] = name data['order'] = order data['collapsed'] = collapsed return self._put('components/groups/%s' % group_id, data=data)['data'] def delete(self, group_id): """Delete a Component Group :param int group_id: Component Group ID :return: :obj:`None` .. seealso:: https://docs.cachethq.io/reference#delete-a-component """ self._delete('components/groups/%s' % group_id)
outini/python-pylls
pylls/cachet.py
ComponentGroups.update
python
def update(self, group_id, name=None, order=None, collapsed=None): data = ApiParams() data['group'] = group_id data['name'] = name data['order'] = order data['collapsed'] = collapsed return self._put('components/groups/%s' % group_id, data=data)['data']
Update a Component Group :param int group_id: Component Group ID :param str name: Name of the component group :param int order: Order of the group :param int collapsed: Collapse the group? :return: Updated component group data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#put-component-group
train
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L218-L234
null
class ComponentGroups(client.CachetAPIEndPoint): """Component groups API endpoint """ def __init__(self, *args, **kwargs): """Initialization method""" super(ComponentGroups, self).__init__(*args, **kwargs) def get(self, group_id=None, **kwargs): """Get component groups :param group_id: Component group ID (optional) :return: Component groups data (:class:`dict`) Additional named arguments may be passed and are directly transmitted to API. It is useful to use the API search features. .. seealso:: https://docs.cachethq.io/reference#get-componentgroups .. seealso:: https://docs.cachethq.io/docs/advanced-api-usage """ path = 'components/groups' if group_id is not None: path += '/%s' % group_id return self.paginate_get(path, data=kwargs) def create(self, name, order=None, collapsed=None): """Create a new Component Group :param str name: Name of the component group :param int order: Order of the component group :param int collapsed: Collapse the group? 0-2 :return: Created component group data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#post-componentgroups """ data = ApiParams() data['name'] = name data['order'] = order data['collapsed'] = collapsed return self._post('components/groups', data=data)['data'] def delete(self, group_id): """Delete a Component Group :param int group_id: Component Group ID :return: :obj:`None` .. seealso:: https://docs.cachethq.io/reference#delete-a-component """ self._delete('components/groups/%s' % group_id)
outini/python-pylls
pylls/cachet.py
Incidents.get
python
def get(self, incident_id=None, **kwargs): path = 'incidents' if incident_id is not None: path += '/%s' % incident_id return self.paginate_get(path, data=kwargs)
Get incidents :param int incident_id: :return: Incidents data (:class:`dict`) Additional named arguments may be passed and are directly transmitted to API. It is useful to use the API search features. .. seealso:: https://docs.cachethq.io/reference#get-incidents .. seealso:: https://docs.cachethq.io/docs/advanced-api-usage
train
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L254-L269
null
class Incidents(client.CachetAPIEndPoint): """Incidents API endpoint """ def __init__(self, *args, **kwargs): """Initialization method""" super(Incidents, self).__init__(*args, **kwargs) def create(self, name, message, status, visible, component_id=None, component_status=None, notify=None, created_at=None, template=None, tplvars=None): """Create a new Incident :param str name: Name of the incident :param str message: Incident explanation message :param int status: Status of the incident :param int visible: Whether the incident is publicly visible :param int component_id: Component to update :param int component_status: The status to update the given component :param bool notify: Whether to notify subscribers :param str created_at: When the incident was created :param str template: The template slug to use :param list tplvars: The variables to pass to the template :return: Created incident data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#incidents """ data = ApiParams() data['name'] = name data['message'] = message data['status'] = status data['visible'] = visible data['component_id'] = component_id data['component_status'] = component_status data['notify'] = notify data['created_at'] = created_at data['template'] = template data['vars'] = tplvars return self._post('incidents', data=data)['data'] def update(self, incident_id, name=None, message=None, status=None, visible=None, component_id=None, component_status=None, notify=None, created_at=None, template=None, tpl_vars=None): """Update an Incident :param int incident_id: Incident ID :param str name: Name of the incident :param str message: Incident explanation message :param int status: Status of the incident :param int visible: Whether the incident is publicly visible :param int component_id: Component to update :param int component_status: The status to update the given component :param bool notify: Whether to notify subscribers :param str created_at: When the incident was created :param str template: The template slug to use :param list tpl_vars: The variables to pass to the template :return: Created incident data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#update-an-incident """ data = ApiParams() data['name'] = name data['message'] = message data['status'] = status data['visible'] = visible data['component_id'] = component_id data['component_status'] = component_status data['notify'] = notify data['created_at'] = created_at data['template'] = template data['vars'] = tpl_vars return self._put('incidents/%s' % incident_id, data=data)['data'] def delete(self, incident_id): """Delete an Incident :param int incident_id: Incident ID :return: :obj:`None` .. seealso:: https://docs.cachethq.io/reference#delete-an-incident """ self._delete('incidents/%s' % incident_id)
outini/python-pylls
pylls/cachet.py
Incidents.create
python
def create(self, name, message, status, visible, component_id=None, component_status=None, notify=None, created_at=None, template=None, tplvars=None): data = ApiParams() data['name'] = name data['message'] = message data['status'] = status data['visible'] = visible data['component_id'] = component_id data['component_status'] = component_status data['notify'] = notify data['created_at'] = created_at data['template'] = template data['vars'] = tplvars return self._post('incidents', data=data)['data']
Create a new Incident :param str name: Name of the incident :param str message: Incident explanation message :param int status: Status of the incident :param int visible: Whether the incident is publicly visible :param int component_id: Component to update :param int component_status: The status to update the given component :param bool notify: Whether to notify subscribers :param str created_at: When the incident was created :param str template: The template slug to use :param list tplvars: The variables to pass to the template :return: Created incident data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#incidents
train
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L271-L301
null
class Incidents(client.CachetAPIEndPoint): """Incidents API endpoint """ def __init__(self, *args, **kwargs): """Initialization method""" super(Incidents, self).__init__(*args, **kwargs) def get(self, incident_id=None, **kwargs): """Get incidents :param int incident_id: :return: Incidents data (:class:`dict`) Additional named arguments may be passed and are directly transmitted to API. It is useful to use the API search features. .. seealso:: https://docs.cachethq.io/reference#get-incidents .. seealso:: https://docs.cachethq.io/docs/advanced-api-usage """ path = 'incidents' if incident_id is not None: path += '/%s' % incident_id return self.paginate_get(path, data=kwargs) def update(self, incident_id, name=None, message=None, status=None, visible=None, component_id=None, component_status=None, notify=None, created_at=None, template=None, tpl_vars=None): """Update an Incident :param int incident_id: Incident ID :param str name: Name of the incident :param str message: Incident explanation message :param int status: Status of the incident :param int visible: Whether the incident is publicly visible :param int component_id: Component to update :param int component_status: The status to update the given component :param bool notify: Whether to notify subscribers :param str created_at: When the incident was created :param str template: The template slug to use :param list tpl_vars: The variables to pass to the template :return: Created incident data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#update-an-incident """ data = ApiParams() data['name'] = name data['message'] = message data['status'] = status data['visible'] = visible data['component_id'] = component_id data['component_status'] = component_status data['notify'] = notify data['created_at'] = created_at data['template'] = template data['vars'] = tpl_vars return self._put('incidents/%s' % incident_id, data=data)['data'] def delete(self, incident_id): """Delete an Incident :param int incident_id: Incident ID :return: :obj:`None` .. seealso:: https://docs.cachethq.io/reference#delete-an-incident """ self._delete('incidents/%s' % incident_id)
outini/python-pylls
pylls/cachet.py
Incidents.update
python
def update(self, incident_id, name=None, message=None, status=None, visible=None, component_id=None, component_status=None, notify=None, created_at=None, template=None, tpl_vars=None): data = ApiParams() data['name'] = name data['message'] = message data['status'] = status data['visible'] = visible data['component_id'] = component_id data['component_status'] = component_status data['notify'] = notify data['created_at'] = created_at data['template'] = template data['vars'] = tpl_vars return self._put('incidents/%s' % incident_id, data=data)['data']
Update an Incident :param int incident_id: Incident ID :param str name: Name of the incident :param str message: Incident explanation message :param int status: Status of the incident :param int visible: Whether the incident is publicly visible :param int component_id: Component to update :param int component_status: The status to update the given component :param bool notify: Whether to notify subscribers :param str created_at: When the incident was created :param str template: The template slug to use :param list tpl_vars: The variables to pass to the template :return: Created incident data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#update-an-incident
train
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L303-L334
null
class Incidents(client.CachetAPIEndPoint): """Incidents API endpoint """ def __init__(self, *args, **kwargs): """Initialization method""" super(Incidents, self).__init__(*args, **kwargs) def get(self, incident_id=None, **kwargs): """Get incidents :param int incident_id: :return: Incidents data (:class:`dict`) Additional named arguments may be passed and are directly transmitted to API. It is useful to use the API search features. .. seealso:: https://docs.cachethq.io/reference#get-incidents .. seealso:: https://docs.cachethq.io/docs/advanced-api-usage """ path = 'incidents' if incident_id is not None: path += '/%s' % incident_id return self.paginate_get(path, data=kwargs) def create(self, name, message, status, visible, component_id=None, component_status=None, notify=None, created_at=None, template=None, tplvars=None): """Create a new Incident :param str name: Name of the incident :param str message: Incident explanation message :param int status: Status of the incident :param int visible: Whether the incident is publicly visible :param int component_id: Component to update :param int component_status: The status to update the given component :param bool notify: Whether to notify subscribers :param str created_at: When the incident was created :param str template: The template slug to use :param list tplvars: The variables to pass to the template :return: Created incident data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#incidents """ data = ApiParams() data['name'] = name data['message'] = message data['status'] = status data['visible'] = visible data['component_id'] = component_id data['component_status'] = component_status data['notify'] = notify data['created_at'] = created_at data['template'] = template data['vars'] = tplvars return self._post('incidents', data=data)['data'] def delete(self, incident_id): """Delete an Incident :param int incident_id: Incident ID :return: :obj:`None` .. seealso:: https://docs.cachethq.io/reference#delete-an-incident """ self._delete('incidents/%s' % incident_id)
outini/python-pylls
pylls/cachet.py
Metrics.points
python
def points(self): if not self._points: self._points = MetricPoints(self.api_client) return self._points
Metric points Special property which point to a :class:`~pylls.cachet.MetricPoints` instance for convenience. This instance is initialized on first call.
train
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L356-L364
null
class Metrics(client.CachetAPIEndPoint): """Metrics API endpoint """ def __init__(self, *args, **kwargs): """Initialization method""" super(Metrics, self).__init__(*args, **kwargs) self._points = None @property def get(self, metric_id=None, **kwargs): """Get metrics :param int metric_id: Metric ID :return: Metrics data (:class:`dict`) Additional named arguments may be passed and are directly transmitted to API. It is useful to use the API search features. .. seealso:: https://docs.cachethq.io/reference#get-metrics .. seealso:: https://docs.cachethq.io/docs/advanced-api-usage """ path = 'metrics' if metric_id is not None: path += '/%s' % metric_id return self.paginate_get(path, data=kwargs) def create(self, name, suffix, description, default_value, display=None): """Create a new Metric :param str name: Name of metric :param str suffix: Metric unit :param str description: Description of what the metric is measuring :param int default_value: Default value to use when a point is added :param int display: Display the chart on the status page :return: Created metric data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#metrics """ data = ApiParams() data['name'] = name data['suffix'] = suffix data['description'] = description data['default_value'] = default_value data['display'] = display return self._post('metrics', data=data)['data'] def delete(self, metric_id): """Delete a Metric :param int metric_id: Metric ID :return: :obj:`None` .. seealso:: https://docs.cachethq.io/reference#delete-a-metric """ self._delete('metrics/%s' % metric_id)
outini/python-pylls
pylls/cachet.py
Metrics.get
python
def get(self, metric_id=None, **kwargs): path = 'metrics' if metric_id is not None: path += '/%s' % metric_id return self.paginate_get(path, data=kwargs)
Get metrics :param int metric_id: Metric ID :return: Metrics data (:class:`dict`) Additional named arguments may be passed and are directly transmitted to API. It is useful to use the API search features. .. seealso:: https://docs.cachethq.io/reference#get-metrics .. seealso:: https://docs.cachethq.io/docs/advanced-api-usage
train
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L366-L381
null
class Metrics(client.CachetAPIEndPoint): """Metrics API endpoint """ def __init__(self, *args, **kwargs): """Initialization method""" super(Metrics, self).__init__(*args, **kwargs) self._points = None @property def points(self): """Metric points Special property which point to a :class:`~pylls.cachet.MetricPoints` instance for convenience. This instance is initialized on first call. """ if not self._points: self._points = MetricPoints(self.api_client) return self._points def create(self, name, suffix, description, default_value, display=None): """Create a new Metric :param str name: Name of metric :param str suffix: Metric unit :param str description: Description of what the metric is measuring :param int default_value: Default value to use when a point is added :param int display: Display the chart on the status page :return: Created metric data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#metrics """ data = ApiParams() data['name'] = name data['suffix'] = suffix data['description'] = description data['default_value'] = default_value data['display'] = display return self._post('metrics', data=data)['data'] def delete(self, metric_id): """Delete a Metric :param int metric_id: Metric ID :return: :obj:`None` .. seealso:: https://docs.cachethq.io/reference#delete-a-metric """ self._delete('metrics/%s' % metric_id)
outini/python-pylls
pylls/cachet.py
Metrics.create
python
def create(self, name, suffix, description, default_value, display=None): data = ApiParams() data['name'] = name data['suffix'] = suffix data['description'] = description data['default_value'] = default_value data['display'] = display return self._post('metrics', data=data)['data']
Create a new Metric :param str name: Name of metric :param str suffix: Metric unit :param str description: Description of what the metric is measuring :param int default_value: Default value to use when a point is added :param int display: Display the chart on the status page :return: Created metric data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#metrics
train
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L383-L401
null
class Metrics(client.CachetAPIEndPoint): """Metrics API endpoint """ def __init__(self, *args, **kwargs): """Initialization method""" super(Metrics, self).__init__(*args, **kwargs) self._points = None @property def points(self): """Metric points Special property which point to a :class:`~pylls.cachet.MetricPoints` instance for convenience. This instance is initialized on first call. """ if not self._points: self._points = MetricPoints(self.api_client) return self._points def get(self, metric_id=None, **kwargs): """Get metrics :param int metric_id: Metric ID :return: Metrics data (:class:`dict`) Additional named arguments may be passed and are directly transmitted to API. It is useful to use the API search features. .. seealso:: https://docs.cachethq.io/reference#get-metrics .. seealso:: https://docs.cachethq.io/docs/advanced-api-usage """ path = 'metrics' if metric_id is not None: path += '/%s' % metric_id return self.paginate_get(path, data=kwargs) def delete(self, metric_id): """Delete a Metric :param int metric_id: Metric ID :return: :obj:`None` .. seealso:: https://docs.cachethq.io/reference#delete-a-metric """ self._delete('metrics/%s' % metric_id)
outini/python-pylls
pylls/cachet.py
MetricPoints.create
python
def create(self, metric_id, value, timestamp=None): data = ApiParams() data['value'] = value data['timestamp'] = timestamp return self._post('metrics/%s/points' % metric_id, data=data)['data']
Add a Metric Point to a Metric :param int metric_id: Metric ID :param int value: Value to plot on the metric graph :param str timestamp: Unix timestamp of the point was measured :return: Created metric point data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#post-metric-points
train
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L431-L444
null
class MetricPoints(client.CachetAPIEndPoint): """MetricPoints API endpoint """ def __init__(self, *args, **kwargs): """Initialization method""" super(MetricPoints, self).__init__(*args, **kwargs) def get(self, metric_id, **kwargs): """Get Points for a Metric :param int metric_id: Metric ID :return: Metric points data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#get-metric-points """ return self.paginate_get('metrics/%s/points' % metric_id, **kwargs) def delete(self, metric_id, point_id): """Delete a Metric Point :param metric_id: Metric ID :param point_id: Metric point ID :return: :obj:`None` .. seealso:: https://docs.cachethq.io/reference#delete-a-metric-point """ self._delete('metrics/%s/points/%s' % (metric_id, point_id))
outini/python-pylls
pylls/cachet.py
Subscribers.create
python
def create(self, email, verify=None, components=None): data = ApiParams() data['email'] = email data['verify'] = verify data['components'] = components return self._post('subscribers', data=data)['data']
Create a new subscriber :param str email: Email address to subscribe :param bool verify: Whether to send verification email :param list components: Components ID list, defaults to all :return: Created subscriber data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#subscribers
train
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L479-L493
null
class Subscribers(client.CachetAPIEndPoint): """Subscribers API endpoint """ def __init__(self, *args, **kwargs): """Initialization method""" super(Subscribers, self).__init__(*args, **kwargs) def get(self, **kwargs): """Returns all subscribers :return: Subscribers data (:class:`dict`) Additional named arguments may be passed and are directly transmitted to API. It is useful to use the API search features. .. seealso:: https://docs.cachethq.io/reference#get-subscribers .. seealso:: https://docs.cachethq.io/docs/advanced-api-usage """ return self.paginate_get('subscribers', data=kwargs) def delete(self, subscriber_id): """Delete a Subscriber :param int subscriber_id: Subscriber ID :return: :obj:`None` .. seealso:: https://docs.cachethq.io/reference#delete-subscriber """ self._delete('subscribers/%s' % subscriber_id)
outini/python-pylls
pylls/client.py
CachetAPIClient.request
python
def request(self, path, method, data=None, **kwargs): if self.api_token: self.request_headers['X-Cachet-Token'] = self.api_token if not path.startswith('http://') and not path.startswith('https://'): url = "%s/%s" % (self.api_endpoint, path) else: url = path if data is None: data = {} response = self.r_session.request(method, url, data=json.dumps(data), headers=self.request_headers, timeout=self.timeout, verify=self.verify, **kwargs) # If API returns an error, we simply raise and let caller handle it response.raise_for_status() try: return response.json() except ValueError: return {'data': response.text}
Handle requests to API :param str path: API endpoint's path to request :param str method: HTTP method to use :param dict data: Data to send (optional) :return: Parsed json response as :class:`dict` Additional named argument may be passed and are directly transmitted to :meth:`request` method of :class:`requests.Session` object.
train
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/client.py#L86-L121
null
class CachetAPIClient(object): """Simple Cachet API client It implements common HTTP methods GET, POST, PUT and DELETE This client is using :mod:`requests` package. Please see http://docs.python-requests.org/ for more information. :param bool verify: Control SSL certificate validation :param int timeout: Request timeout in seconds :param str api_endpoint: Cachet API endpoint :param str api_token: Cachet API token .. method:: get(self, path, data=None, **kwargs) Partial method invoking :meth:`~CachetAPIClient.request` with http method *GET*. .. method:: post(self, path, data=None, **kwargs) Partial method invoking :meth:`~CachetAPIClient.request` with http method *POST*. .. method:: put(self, path, data=None, **kwargs) Partial method invoking :meth:`~CachetAPIClient.request` with http method *PUT*. .. method:: delete(self, path, data=None, **kwargs) Partial method invoking :meth:`~CachetAPIClient.request` with http method *DELETE*. """ def __init__(self, api_endpoint, api_token=None, verify=None, timeout=None): """Initialization method""" self.verify = verify self.timeout = timeout self.api_endpoint = api_endpoint self.api_token = api_token self.request_headers = { 'User-Agent': 'python-pylls', 'Accept': 'application/json', 'Content-Type': 'application/json' } self.r_session = requests.Session() # Directly expose common HTTP methods self.get = partial(self.request, method='GET') self.post = partial(self.request, method='POST') self.put = partial(self.request, method='PUT') self.delete = partial(self.request, method='DELETE') def paginate_request(self, path, method, data=None, **kwargs): """Handle paginated requests to API :param str path: API endpoint's path to request :param str method: HTTP method to use :param dict data: Data to send (optional) :return: Response data items (:class:`Generator`) Cachet pagination is handled and next pages requested on demand. Additional named argument may be passed and are directly transmitted to :meth:`request` method of :class:`requests.Session` object. """ next_page = path while next_page: response = self.request(next_page, method, data=data, **kwargs) if not isinstance(response.get('data'), list): next_page = None yield response['data'] else: for entry in response['data']: yield entry # Get next page if it exists try: links = response['meta']['pagination']['links'] next_page = links.get('next_page') except KeyError: next_page = None
outini/python-pylls
pylls/client.py
CachetAPIClient.paginate_request
python
def paginate_request(self, path, method, data=None, **kwargs): next_page = path while next_page: response = self.request(next_page, method, data=data, **kwargs) if not isinstance(response.get('data'), list): next_page = None yield response['data'] else: for entry in response['data']: yield entry # Get next page if it exists try: links = response['meta']['pagination']['links'] next_page = links.get('next_page') except KeyError: next_page = None
Handle paginated requests to API :param str path: API endpoint's path to request :param str method: HTTP method to use :param dict data: Data to send (optional) :return: Response data items (:class:`Generator`) Cachet pagination is handled and next pages requested on demand. Additional named argument may be passed and are directly transmitted to :meth:`request` method of :class:`requests.Session` object.
train
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/client.py#L123-L152
[ "def request(self, path, method, data=None, **kwargs):\n \"\"\"Handle requests to API\n\n :param str path: API endpoint's path to request\n :param str method: HTTP method to use\n :param dict data: Data to send (optional)\n :return: Parsed json response as :class:`dict`\n\n Additional named argument may be passed and are directly transmitted\n to :meth:`request` method of :class:`requests.Session` object.\n \"\"\"\n if self.api_token:\n self.request_headers['X-Cachet-Token'] = self.api_token\n\n if not path.startswith('http://') and not path.startswith('https://'):\n url = \"%s/%s\" % (self.api_endpoint, path)\n else:\n url = path\n\n if data is None:\n data = {}\n\n response = self.r_session.request(method, url,\n data=json.dumps(data),\n headers=self.request_headers,\n timeout=self.timeout,\n verify=self.verify,\n **kwargs)\n\n # If API returns an error, we simply raise and let caller handle it\n response.raise_for_status()\n\n try:\n return response.json()\n except ValueError:\n return {'data': response.text}\n" ]
class CachetAPIClient(object): """Simple Cachet API client It implements common HTTP methods GET, POST, PUT and DELETE This client is using :mod:`requests` package. Please see http://docs.python-requests.org/ for more information. :param bool verify: Control SSL certificate validation :param int timeout: Request timeout in seconds :param str api_endpoint: Cachet API endpoint :param str api_token: Cachet API token .. method:: get(self, path, data=None, **kwargs) Partial method invoking :meth:`~CachetAPIClient.request` with http method *GET*. .. method:: post(self, path, data=None, **kwargs) Partial method invoking :meth:`~CachetAPIClient.request` with http method *POST*. .. method:: put(self, path, data=None, **kwargs) Partial method invoking :meth:`~CachetAPIClient.request` with http method *PUT*. .. method:: delete(self, path, data=None, **kwargs) Partial method invoking :meth:`~CachetAPIClient.request` with http method *DELETE*. """ def __init__(self, api_endpoint, api_token=None, verify=None, timeout=None): """Initialization method""" self.verify = verify self.timeout = timeout self.api_endpoint = api_endpoint self.api_token = api_token self.request_headers = { 'User-Agent': 'python-pylls', 'Accept': 'application/json', 'Content-Type': 'application/json' } self.r_session = requests.Session() # Directly expose common HTTP methods self.get = partial(self.request, method='GET') self.post = partial(self.request, method='POST') self.put = partial(self.request, method='PUT') self.delete = partial(self.request, method='DELETE') def request(self, path, method, data=None, **kwargs): """Handle requests to API :param str path: API endpoint's path to request :param str method: HTTP method to use :param dict data: Data to send (optional) :return: Parsed json response as :class:`dict` Additional named argument may be passed and are directly transmitted to :meth:`request` method of :class:`requests.Session` object. """ if self.api_token: self.request_headers['X-Cachet-Token'] = self.api_token if not path.startswith('http://') and not path.startswith('https://'): url = "%s/%s" % (self.api_endpoint, path) else: url = path if data is None: data = {} response = self.r_session.request(method, url, data=json.dumps(data), headers=self.request_headers, timeout=self.timeout, verify=self.verify, **kwargs) # If API returns an error, we simply raise and let caller handle it response.raise_for_status() try: return response.json() except ValueError: return {'data': response.text}
what-studio/smartformat
smartformat/dotnet.py
modify_number_pattern
python
def modify_number_pattern(number_pattern, **kwargs): params = ['pattern', 'prefix', 'suffix', 'grouping', 'int_prec', 'frac_prec', 'exp_prec', 'exp_plus'] for param in params: if param in kwargs: continue kwargs[param] = getattr(number_pattern, param) return NumberPattern(**kwargs)
Modifies a number pattern by specified keyword arguments.
train
https://github.com/what-studio/smartformat/blob/5731203cbf29617ab8d42542f9dac03d5e34b217/smartformat/dotnet.py#L31-L39
null
# -*- coding: utf-8 -*- """ smartformat.dotnet ~~~~~~~~~~~~~~~~~~ :copyright: (c) 2016 by What! Studio :license: BSD, see LICENSE for more details. """ import math from numbers import Number from babel import Locale from babel.numbers import ( format_currency, get_decimal_symbol, get_territory_currencies, NumberPattern, parse_pattern) from six import string_types, text_type as str from valuedispatch import valuedispatch from .local import LocalFormatter __all__ = ['DotNetFormatter'] NUMBER_DECIMAL_DIGITS = 2 PERCENT_DECIMAL_DIGITS = 2 SCIENTIFIC_DECIMAL_DIGITS = 6 @valuedispatch def format_field(spec, arg, value, locale): if spec and isinstance(value, Number): if arg: spec += arg try: pattern = parse_pattern(spec) except ValueError: return spec else: return pattern.apply(value, locale) return str(value) @format_field.register(u'c') @format_field.register(u'C') def format_currency_field(__, prec, number, locale): """Formats a currency field.""" locale = Locale.parse(locale) currency = get_territory_currencies(locale.territory)[0] if prec is None: pattern, currency_digits = None, True else: prec = int(prec) pattern = locale.currency_formats['standard'] pattern = modify_number_pattern(pattern, frac_prec=(prec, prec)) currency_digits = False return format_currency(number, currency, pattern, locale=locale, currency_digits=currency_digits) @format_field.register(u'd') @format_field.register(u'D') def format_decimal_field(__, prec, number, locale): """Formats a decimal field: .. sourcecode:: 1234 ('D') -> 1234 -1234 ('D6') -> -001234 """ prec = 0 if prec is None else int(prec) if number < 0: prec += 1 return format(number, u'0%dd' % prec) @format_field.register(u'e') @format_field.register(u'E') def format_scientific_field(spec, prec, number, locale): prec = SCIENTIFIC_DECIMAL_DIGITS if prec is None else int(prec) format_ = u'0.%sE+000' % (u'#' * prec) pattern = parse_pattern(format_) decimal_symbol = get_decimal_symbol(locale) string = pattern.apply(number, locale).replace(u'.', decimal_symbol) return string.lower() if spec.islower() else string @format_field.register(u'f') @format_field.register(u'F') def format_float_field(__, prec, number, locale): """Formats a fixed-point field.""" format_ = u'0.' if prec is None: format_ += u'#' * NUMBER_DECIMAL_DIGITS else: format_ += u'0' * int(prec) pattern = parse_pattern(format_) return pattern.apply(number, locale) @format_field.register(u'n') @format_field.register(u'N') def format_number_field(__, prec, number, locale): """Formats a number field.""" prec = NUMBER_DECIMAL_DIGITS if prec is None else int(prec) locale = Locale.parse(locale) pattern = locale.decimal_formats.get(None) return pattern.apply(number, locale, force_frac=(prec, prec)) @format_field.register(u'p') @format_field.register(u'P') def format_percent_field(__, prec, number, locale): """Formats a percent field.""" prec = PERCENT_DECIMAL_DIGITS if prec is None else int(prec) locale = Locale.parse(locale) pattern = locale.percent_formats.get(None) return pattern.apply(number, locale, force_frac=(prec, prec)) @format_field.register(u'x') @format_field.register(u'X') def format_hexadecimal_field(spec, prec, number, locale): """Formats a hexadeciaml field.""" if number < 0: # Take two's complement. number &= (1 << (8 * int(math.log(-number, 1 << 8) + 1))) - 1 format_ = u'0%d%s' % (int(prec or 0), spec) return format(number, format_) @format_field.register(u'g') @format_field.register(u'G') @format_field.register(u'r') @format_field.register(u'R') def format_not_implemented_field(spec, *args, **kwargs): raise NotImplementedError('numeric format specifier %r ' 'is not implemented yet' % spec) class DotNetFormatter(LocalFormatter): """A string formatter like `String.Format` in .NET Framework.""" _format_field = staticmethod(format_field) def vformat(self, format_string, args, kwargs): if not format_string: return u'' base = super(DotNetFormatter, self) return base.vformat(format_string, args, kwargs) def get_value(self, key, args, kwargs): if isinstance(key, string_types): key, comma, width = key.partition(u',') if comma: raise NotImplementedError('width specifier after comma ' 'is not implemented yet') return super(DotNetFormatter, self).get_value(key, args, kwargs) def format_field(self, value, format_spec): """Format specifiers are described in :func:`format_field` which is a static function. """ if format_spec: spec, arg = format_spec[0], format_spec[1:] arg = arg or None else: spec = arg = None return self._format_field(spec, arg, value, self.numeric_locale)
what-studio/smartformat
smartformat/dotnet.py
format_currency_field
python
def format_currency_field(__, prec, number, locale): locale = Locale.parse(locale) currency = get_territory_currencies(locale.territory)[0] if prec is None: pattern, currency_digits = None, True else: prec = int(prec) pattern = locale.currency_formats['standard'] pattern = modify_number_pattern(pattern, frac_prec=(prec, prec)) currency_digits = False return format_currency(number, currency, pattern, locale=locale, currency_digits=currency_digits)
Formats a currency field.
train
https://github.com/what-studio/smartformat/blob/5731203cbf29617ab8d42542f9dac03d5e34b217/smartformat/dotnet.py#L58-L70
[ "def modify_number_pattern(number_pattern, **kwargs):\n \"\"\"Modifies a number pattern by specified keyword arguments.\"\"\"\n params = ['pattern', 'prefix', 'suffix', 'grouping',\n 'int_prec', 'frac_prec', 'exp_prec', 'exp_plus']\n for param in params:\n if param in kwargs:\n continue\n kwargs[param] = getattr(number_pattern, param)\n return NumberPattern(**kwargs)\n" ]
# -*- coding: utf-8 -*- """ smartformat.dotnet ~~~~~~~~~~~~~~~~~~ :copyright: (c) 2016 by What! Studio :license: BSD, see LICENSE for more details. """ import math from numbers import Number from babel import Locale from babel.numbers import ( format_currency, get_decimal_symbol, get_territory_currencies, NumberPattern, parse_pattern) from six import string_types, text_type as str from valuedispatch import valuedispatch from .local import LocalFormatter __all__ = ['DotNetFormatter'] NUMBER_DECIMAL_DIGITS = 2 PERCENT_DECIMAL_DIGITS = 2 SCIENTIFIC_DECIMAL_DIGITS = 6 def modify_number_pattern(number_pattern, **kwargs): """Modifies a number pattern by specified keyword arguments.""" params = ['pattern', 'prefix', 'suffix', 'grouping', 'int_prec', 'frac_prec', 'exp_prec', 'exp_plus'] for param in params: if param in kwargs: continue kwargs[param] = getattr(number_pattern, param) return NumberPattern(**kwargs) @valuedispatch def format_field(spec, arg, value, locale): if spec and isinstance(value, Number): if arg: spec += arg try: pattern = parse_pattern(spec) except ValueError: return spec else: return pattern.apply(value, locale) return str(value) @format_field.register(u'c') @format_field.register(u'C') @format_field.register(u'd') @format_field.register(u'D') def format_decimal_field(__, prec, number, locale): """Formats a decimal field: .. sourcecode:: 1234 ('D') -> 1234 -1234 ('D6') -> -001234 """ prec = 0 if prec is None else int(prec) if number < 0: prec += 1 return format(number, u'0%dd' % prec) @format_field.register(u'e') @format_field.register(u'E') def format_scientific_field(spec, prec, number, locale): prec = SCIENTIFIC_DECIMAL_DIGITS if prec is None else int(prec) format_ = u'0.%sE+000' % (u'#' * prec) pattern = parse_pattern(format_) decimal_symbol = get_decimal_symbol(locale) string = pattern.apply(number, locale).replace(u'.', decimal_symbol) return string.lower() if spec.islower() else string @format_field.register(u'f') @format_field.register(u'F') def format_float_field(__, prec, number, locale): """Formats a fixed-point field.""" format_ = u'0.' if prec is None: format_ += u'#' * NUMBER_DECIMAL_DIGITS else: format_ += u'0' * int(prec) pattern = parse_pattern(format_) return pattern.apply(number, locale) @format_field.register(u'n') @format_field.register(u'N') def format_number_field(__, prec, number, locale): """Formats a number field.""" prec = NUMBER_DECIMAL_DIGITS if prec is None else int(prec) locale = Locale.parse(locale) pattern = locale.decimal_formats.get(None) return pattern.apply(number, locale, force_frac=(prec, prec)) @format_field.register(u'p') @format_field.register(u'P') def format_percent_field(__, prec, number, locale): """Formats a percent field.""" prec = PERCENT_DECIMAL_DIGITS if prec is None else int(prec) locale = Locale.parse(locale) pattern = locale.percent_formats.get(None) return pattern.apply(number, locale, force_frac=(prec, prec)) @format_field.register(u'x') @format_field.register(u'X') def format_hexadecimal_field(spec, prec, number, locale): """Formats a hexadeciaml field.""" if number < 0: # Take two's complement. number &= (1 << (8 * int(math.log(-number, 1 << 8) + 1))) - 1 format_ = u'0%d%s' % (int(prec or 0), spec) return format(number, format_) @format_field.register(u'g') @format_field.register(u'G') @format_field.register(u'r') @format_field.register(u'R') def format_not_implemented_field(spec, *args, **kwargs): raise NotImplementedError('numeric format specifier %r ' 'is not implemented yet' % spec) class DotNetFormatter(LocalFormatter): """A string formatter like `String.Format` in .NET Framework.""" _format_field = staticmethod(format_field) def vformat(self, format_string, args, kwargs): if not format_string: return u'' base = super(DotNetFormatter, self) return base.vformat(format_string, args, kwargs) def get_value(self, key, args, kwargs): if isinstance(key, string_types): key, comma, width = key.partition(u',') if comma: raise NotImplementedError('width specifier after comma ' 'is not implemented yet') return super(DotNetFormatter, self).get_value(key, args, kwargs) def format_field(self, value, format_spec): """Format specifiers are described in :func:`format_field` which is a static function. """ if format_spec: spec, arg = format_spec[0], format_spec[1:] arg = arg or None else: spec = arg = None return self._format_field(spec, arg, value, self.numeric_locale)
what-studio/smartformat
smartformat/dotnet.py
format_decimal_field
python
def format_decimal_field(__, prec, number, locale): prec = 0 if prec is None else int(prec) if number < 0: prec += 1 return format(number, u'0%dd' % prec)
Formats a decimal field: .. sourcecode:: 1234 ('D') -> 1234 -1234 ('D6') -> -001234
train
https://github.com/what-studio/smartformat/blob/5731203cbf29617ab8d42542f9dac03d5e34b217/smartformat/dotnet.py#L75-L87
null
# -*- coding: utf-8 -*- """ smartformat.dotnet ~~~~~~~~~~~~~~~~~~ :copyright: (c) 2016 by What! Studio :license: BSD, see LICENSE for more details. """ import math from numbers import Number from babel import Locale from babel.numbers import ( format_currency, get_decimal_symbol, get_territory_currencies, NumberPattern, parse_pattern) from six import string_types, text_type as str from valuedispatch import valuedispatch from .local import LocalFormatter __all__ = ['DotNetFormatter'] NUMBER_DECIMAL_DIGITS = 2 PERCENT_DECIMAL_DIGITS = 2 SCIENTIFIC_DECIMAL_DIGITS = 6 def modify_number_pattern(number_pattern, **kwargs): """Modifies a number pattern by specified keyword arguments.""" params = ['pattern', 'prefix', 'suffix', 'grouping', 'int_prec', 'frac_prec', 'exp_prec', 'exp_plus'] for param in params: if param in kwargs: continue kwargs[param] = getattr(number_pattern, param) return NumberPattern(**kwargs) @valuedispatch def format_field(spec, arg, value, locale): if spec and isinstance(value, Number): if arg: spec += arg try: pattern = parse_pattern(spec) except ValueError: return spec else: return pattern.apply(value, locale) return str(value) @format_field.register(u'c') @format_field.register(u'C') def format_currency_field(__, prec, number, locale): """Formats a currency field.""" locale = Locale.parse(locale) currency = get_territory_currencies(locale.territory)[0] if prec is None: pattern, currency_digits = None, True else: prec = int(prec) pattern = locale.currency_formats['standard'] pattern = modify_number_pattern(pattern, frac_prec=(prec, prec)) currency_digits = False return format_currency(number, currency, pattern, locale=locale, currency_digits=currency_digits) @format_field.register(u'd') @format_field.register(u'D') @format_field.register(u'e') @format_field.register(u'E') def format_scientific_field(spec, prec, number, locale): prec = SCIENTIFIC_DECIMAL_DIGITS if prec is None else int(prec) format_ = u'0.%sE+000' % (u'#' * prec) pattern = parse_pattern(format_) decimal_symbol = get_decimal_symbol(locale) string = pattern.apply(number, locale).replace(u'.', decimal_symbol) return string.lower() if spec.islower() else string @format_field.register(u'f') @format_field.register(u'F') def format_float_field(__, prec, number, locale): """Formats a fixed-point field.""" format_ = u'0.' if prec is None: format_ += u'#' * NUMBER_DECIMAL_DIGITS else: format_ += u'0' * int(prec) pattern = parse_pattern(format_) return pattern.apply(number, locale) @format_field.register(u'n') @format_field.register(u'N') def format_number_field(__, prec, number, locale): """Formats a number field.""" prec = NUMBER_DECIMAL_DIGITS if prec is None else int(prec) locale = Locale.parse(locale) pattern = locale.decimal_formats.get(None) return pattern.apply(number, locale, force_frac=(prec, prec)) @format_field.register(u'p') @format_field.register(u'P') def format_percent_field(__, prec, number, locale): """Formats a percent field.""" prec = PERCENT_DECIMAL_DIGITS if prec is None else int(prec) locale = Locale.parse(locale) pattern = locale.percent_formats.get(None) return pattern.apply(number, locale, force_frac=(prec, prec)) @format_field.register(u'x') @format_field.register(u'X') def format_hexadecimal_field(spec, prec, number, locale): """Formats a hexadeciaml field.""" if number < 0: # Take two's complement. number &= (1 << (8 * int(math.log(-number, 1 << 8) + 1))) - 1 format_ = u'0%d%s' % (int(prec or 0), spec) return format(number, format_) @format_field.register(u'g') @format_field.register(u'G') @format_field.register(u'r') @format_field.register(u'R') def format_not_implemented_field(spec, *args, **kwargs): raise NotImplementedError('numeric format specifier %r ' 'is not implemented yet' % spec) class DotNetFormatter(LocalFormatter): """A string formatter like `String.Format` in .NET Framework.""" _format_field = staticmethod(format_field) def vformat(self, format_string, args, kwargs): if not format_string: return u'' base = super(DotNetFormatter, self) return base.vformat(format_string, args, kwargs) def get_value(self, key, args, kwargs): if isinstance(key, string_types): key, comma, width = key.partition(u',') if comma: raise NotImplementedError('width specifier after comma ' 'is not implemented yet') return super(DotNetFormatter, self).get_value(key, args, kwargs) def format_field(self, value, format_spec): """Format specifiers are described in :func:`format_field` which is a static function. """ if format_spec: spec, arg = format_spec[0], format_spec[1:] arg = arg or None else: spec = arg = None return self._format_field(spec, arg, value, self.numeric_locale)
what-studio/smartformat
smartformat/dotnet.py
format_float_field
python
def format_float_field(__, prec, number, locale): format_ = u'0.' if prec is None: format_ += u'#' * NUMBER_DECIMAL_DIGITS else: format_ += u'0' * int(prec) pattern = parse_pattern(format_) return pattern.apply(number, locale)
Formats a fixed-point field.
train
https://github.com/what-studio/smartformat/blob/5731203cbf29617ab8d42542f9dac03d5e34b217/smartformat/dotnet.py#L103-L111
null
# -*- coding: utf-8 -*- """ smartformat.dotnet ~~~~~~~~~~~~~~~~~~ :copyright: (c) 2016 by What! Studio :license: BSD, see LICENSE for more details. """ import math from numbers import Number from babel import Locale from babel.numbers import ( format_currency, get_decimal_symbol, get_territory_currencies, NumberPattern, parse_pattern) from six import string_types, text_type as str from valuedispatch import valuedispatch from .local import LocalFormatter __all__ = ['DotNetFormatter'] NUMBER_DECIMAL_DIGITS = 2 PERCENT_DECIMAL_DIGITS = 2 SCIENTIFIC_DECIMAL_DIGITS = 6 def modify_number_pattern(number_pattern, **kwargs): """Modifies a number pattern by specified keyword arguments.""" params = ['pattern', 'prefix', 'suffix', 'grouping', 'int_prec', 'frac_prec', 'exp_prec', 'exp_plus'] for param in params: if param in kwargs: continue kwargs[param] = getattr(number_pattern, param) return NumberPattern(**kwargs) @valuedispatch def format_field(spec, arg, value, locale): if spec and isinstance(value, Number): if arg: spec += arg try: pattern = parse_pattern(spec) except ValueError: return spec else: return pattern.apply(value, locale) return str(value) @format_field.register(u'c') @format_field.register(u'C') def format_currency_field(__, prec, number, locale): """Formats a currency field.""" locale = Locale.parse(locale) currency = get_territory_currencies(locale.territory)[0] if prec is None: pattern, currency_digits = None, True else: prec = int(prec) pattern = locale.currency_formats['standard'] pattern = modify_number_pattern(pattern, frac_prec=(prec, prec)) currency_digits = False return format_currency(number, currency, pattern, locale=locale, currency_digits=currency_digits) @format_field.register(u'd') @format_field.register(u'D') def format_decimal_field(__, prec, number, locale): """Formats a decimal field: .. sourcecode:: 1234 ('D') -> 1234 -1234 ('D6') -> -001234 """ prec = 0 if prec is None else int(prec) if number < 0: prec += 1 return format(number, u'0%dd' % prec) @format_field.register(u'e') @format_field.register(u'E') def format_scientific_field(spec, prec, number, locale): prec = SCIENTIFIC_DECIMAL_DIGITS if prec is None else int(prec) format_ = u'0.%sE+000' % (u'#' * prec) pattern = parse_pattern(format_) decimal_symbol = get_decimal_symbol(locale) string = pattern.apply(number, locale).replace(u'.', decimal_symbol) return string.lower() if spec.islower() else string @format_field.register(u'f') @format_field.register(u'F') @format_field.register(u'n') @format_field.register(u'N') def format_number_field(__, prec, number, locale): """Formats a number field.""" prec = NUMBER_DECIMAL_DIGITS if prec is None else int(prec) locale = Locale.parse(locale) pattern = locale.decimal_formats.get(None) return pattern.apply(number, locale, force_frac=(prec, prec)) @format_field.register(u'p') @format_field.register(u'P') def format_percent_field(__, prec, number, locale): """Formats a percent field.""" prec = PERCENT_DECIMAL_DIGITS if prec is None else int(prec) locale = Locale.parse(locale) pattern = locale.percent_formats.get(None) return pattern.apply(number, locale, force_frac=(prec, prec)) @format_field.register(u'x') @format_field.register(u'X') def format_hexadecimal_field(spec, prec, number, locale): """Formats a hexadeciaml field.""" if number < 0: # Take two's complement. number &= (1 << (8 * int(math.log(-number, 1 << 8) + 1))) - 1 format_ = u'0%d%s' % (int(prec or 0), spec) return format(number, format_) @format_field.register(u'g') @format_field.register(u'G') @format_field.register(u'r') @format_field.register(u'R') def format_not_implemented_field(spec, *args, **kwargs): raise NotImplementedError('numeric format specifier %r ' 'is not implemented yet' % spec) class DotNetFormatter(LocalFormatter): """A string formatter like `String.Format` in .NET Framework.""" _format_field = staticmethod(format_field) def vformat(self, format_string, args, kwargs): if not format_string: return u'' base = super(DotNetFormatter, self) return base.vformat(format_string, args, kwargs) def get_value(self, key, args, kwargs): if isinstance(key, string_types): key, comma, width = key.partition(u',') if comma: raise NotImplementedError('width specifier after comma ' 'is not implemented yet') return super(DotNetFormatter, self).get_value(key, args, kwargs) def format_field(self, value, format_spec): """Format specifiers are described in :func:`format_field` which is a static function. """ if format_spec: spec, arg = format_spec[0], format_spec[1:] arg = arg or None else: spec = arg = None return self._format_field(spec, arg, value, self.numeric_locale)
what-studio/smartformat
smartformat/dotnet.py
format_number_field
python
def format_number_field(__, prec, number, locale): prec = NUMBER_DECIMAL_DIGITS if prec is None else int(prec) locale = Locale.parse(locale) pattern = locale.decimal_formats.get(None) return pattern.apply(number, locale, force_frac=(prec, prec))
Formats a number field.
train
https://github.com/what-studio/smartformat/blob/5731203cbf29617ab8d42542f9dac03d5e34b217/smartformat/dotnet.py#L116-L121
null
# -*- coding: utf-8 -*- """ smartformat.dotnet ~~~~~~~~~~~~~~~~~~ :copyright: (c) 2016 by What! Studio :license: BSD, see LICENSE for more details. """ import math from numbers import Number from babel import Locale from babel.numbers import ( format_currency, get_decimal_symbol, get_territory_currencies, NumberPattern, parse_pattern) from six import string_types, text_type as str from valuedispatch import valuedispatch from .local import LocalFormatter __all__ = ['DotNetFormatter'] NUMBER_DECIMAL_DIGITS = 2 PERCENT_DECIMAL_DIGITS = 2 SCIENTIFIC_DECIMAL_DIGITS = 6 def modify_number_pattern(number_pattern, **kwargs): """Modifies a number pattern by specified keyword arguments.""" params = ['pattern', 'prefix', 'suffix', 'grouping', 'int_prec', 'frac_prec', 'exp_prec', 'exp_plus'] for param in params: if param in kwargs: continue kwargs[param] = getattr(number_pattern, param) return NumberPattern(**kwargs) @valuedispatch def format_field(spec, arg, value, locale): if spec and isinstance(value, Number): if arg: spec += arg try: pattern = parse_pattern(spec) except ValueError: return spec else: return pattern.apply(value, locale) return str(value) @format_field.register(u'c') @format_field.register(u'C') def format_currency_field(__, prec, number, locale): """Formats a currency field.""" locale = Locale.parse(locale) currency = get_territory_currencies(locale.territory)[0] if prec is None: pattern, currency_digits = None, True else: prec = int(prec) pattern = locale.currency_formats['standard'] pattern = modify_number_pattern(pattern, frac_prec=(prec, prec)) currency_digits = False return format_currency(number, currency, pattern, locale=locale, currency_digits=currency_digits) @format_field.register(u'd') @format_field.register(u'D') def format_decimal_field(__, prec, number, locale): """Formats a decimal field: .. sourcecode:: 1234 ('D') -> 1234 -1234 ('D6') -> -001234 """ prec = 0 if prec is None else int(prec) if number < 0: prec += 1 return format(number, u'0%dd' % prec) @format_field.register(u'e') @format_field.register(u'E') def format_scientific_field(spec, prec, number, locale): prec = SCIENTIFIC_DECIMAL_DIGITS if prec is None else int(prec) format_ = u'0.%sE+000' % (u'#' * prec) pattern = parse_pattern(format_) decimal_symbol = get_decimal_symbol(locale) string = pattern.apply(number, locale).replace(u'.', decimal_symbol) return string.lower() if spec.islower() else string @format_field.register(u'f') @format_field.register(u'F') def format_float_field(__, prec, number, locale): """Formats a fixed-point field.""" format_ = u'0.' if prec is None: format_ += u'#' * NUMBER_DECIMAL_DIGITS else: format_ += u'0' * int(prec) pattern = parse_pattern(format_) return pattern.apply(number, locale) @format_field.register(u'n') @format_field.register(u'N') @format_field.register(u'p') @format_field.register(u'P') def format_percent_field(__, prec, number, locale): """Formats a percent field.""" prec = PERCENT_DECIMAL_DIGITS if prec is None else int(prec) locale = Locale.parse(locale) pattern = locale.percent_formats.get(None) return pattern.apply(number, locale, force_frac=(prec, prec)) @format_field.register(u'x') @format_field.register(u'X') def format_hexadecimal_field(spec, prec, number, locale): """Formats a hexadeciaml field.""" if number < 0: # Take two's complement. number &= (1 << (8 * int(math.log(-number, 1 << 8) + 1))) - 1 format_ = u'0%d%s' % (int(prec or 0), spec) return format(number, format_) @format_field.register(u'g') @format_field.register(u'G') @format_field.register(u'r') @format_field.register(u'R') def format_not_implemented_field(spec, *args, **kwargs): raise NotImplementedError('numeric format specifier %r ' 'is not implemented yet' % spec) class DotNetFormatter(LocalFormatter): """A string formatter like `String.Format` in .NET Framework.""" _format_field = staticmethod(format_field) def vformat(self, format_string, args, kwargs): if not format_string: return u'' base = super(DotNetFormatter, self) return base.vformat(format_string, args, kwargs) def get_value(self, key, args, kwargs): if isinstance(key, string_types): key, comma, width = key.partition(u',') if comma: raise NotImplementedError('width specifier after comma ' 'is not implemented yet') return super(DotNetFormatter, self).get_value(key, args, kwargs) def format_field(self, value, format_spec): """Format specifiers are described in :func:`format_field` which is a static function. """ if format_spec: spec, arg = format_spec[0], format_spec[1:] arg = arg or None else: spec = arg = None return self._format_field(spec, arg, value, self.numeric_locale)
what-studio/smartformat
smartformat/dotnet.py
format_percent_field
python
def format_percent_field(__, prec, number, locale): prec = PERCENT_DECIMAL_DIGITS if prec is None else int(prec) locale = Locale.parse(locale) pattern = locale.percent_formats.get(None) return pattern.apply(number, locale, force_frac=(prec, prec))
Formats a percent field.
train
https://github.com/what-studio/smartformat/blob/5731203cbf29617ab8d42542f9dac03d5e34b217/smartformat/dotnet.py#L126-L131
null
# -*- coding: utf-8 -*- """ smartformat.dotnet ~~~~~~~~~~~~~~~~~~ :copyright: (c) 2016 by What! Studio :license: BSD, see LICENSE for more details. """ import math from numbers import Number from babel import Locale from babel.numbers import ( format_currency, get_decimal_symbol, get_territory_currencies, NumberPattern, parse_pattern) from six import string_types, text_type as str from valuedispatch import valuedispatch from .local import LocalFormatter __all__ = ['DotNetFormatter'] NUMBER_DECIMAL_DIGITS = 2 PERCENT_DECIMAL_DIGITS = 2 SCIENTIFIC_DECIMAL_DIGITS = 6 def modify_number_pattern(number_pattern, **kwargs): """Modifies a number pattern by specified keyword arguments.""" params = ['pattern', 'prefix', 'suffix', 'grouping', 'int_prec', 'frac_prec', 'exp_prec', 'exp_plus'] for param in params: if param in kwargs: continue kwargs[param] = getattr(number_pattern, param) return NumberPattern(**kwargs) @valuedispatch def format_field(spec, arg, value, locale): if spec and isinstance(value, Number): if arg: spec += arg try: pattern = parse_pattern(spec) except ValueError: return spec else: return pattern.apply(value, locale) return str(value) @format_field.register(u'c') @format_field.register(u'C') def format_currency_field(__, prec, number, locale): """Formats a currency field.""" locale = Locale.parse(locale) currency = get_territory_currencies(locale.territory)[0] if prec is None: pattern, currency_digits = None, True else: prec = int(prec) pattern = locale.currency_formats['standard'] pattern = modify_number_pattern(pattern, frac_prec=(prec, prec)) currency_digits = False return format_currency(number, currency, pattern, locale=locale, currency_digits=currency_digits) @format_field.register(u'd') @format_field.register(u'D') def format_decimal_field(__, prec, number, locale): """Formats a decimal field: .. sourcecode:: 1234 ('D') -> 1234 -1234 ('D6') -> -001234 """ prec = 0 if prec is None else int(prec) if number < 0: prec += 1 return format(number, u'0%dd' % prec) @format_field.register(u'e') @format_field.register(u'E') def format_scientific_field(spec, prec, number, locale): prec = SCIENTIFIC_DECIMAL_DIGITS if prec is None else int(prec) format_ = u'0.%sE+000' % (u'#' * prec) pattern = parse_pattern(format_) decimal_symbol = get_decimal_symbol(locale) string = pattern.apply(number, locale).replace(u'.', decimal_symbol) return string.lower() if spec.islower() else string @format_field.register(u'f') @format_field.register(u'F') def format_float_field(__, prec, number, locale): """Formats a fixed-point field.""" format_ = u'0.' if prec is None: format_ += u'#' * NUMBER_DECIMAL_DIGITS else: format_ += u'0' * int(prec) pattern = parse_pattern(format_) return pattern.apply(number, locale) @format_field.register(u'n') @format_field.register(u'N') def format_number_field(__, prec, number, locale): """Formats a number field.""" prec = NUMBER_DECIMAL_DIGITS if prec is None else int(prec) locale = Locale.parse(locale) pattern = locale.decimal_formats.get(None) return pattern.apply(number, locale, force_frac=(prec, prec)) @format_field.register(u'p') @format_field.register(u'P') @format_field.register(u'x') @format_field.register(u'X') def format_hexadecimal_field(spec, prec, number, locale): """Formats a hexadeciaml field.""" if number < 0: # Take two's complement. number &= (1 << (8 * int(math.log(-number, 1 << 8) + 1))) - 1 format_ = u'0%d%s' % (int(prec or 0), spec) return format(number, format_) @format_field.register(u'g') @format_field.register(u'G') @format_field.register(u'r') @format_field.register(u'R') def format_not_implemented_field(spec, *args, **kwargs): raise NotImplementedError('numeric format specifier %r ' 'is not implemented yet' % spec) class DotNetFormatter(LocalFormatter): """A string formatter like `String.Format` in .NET Framework.""" _format_field = staticmethod(format_field) def vformat(self, format_string, args, kwargs): if not format_string: return u'' base = super(DotNetFormatter, self) return base.vformat(format_string, args, kwargs) def get_value(self, key, args, kwargs): if isinstance(key, string_types): key, comma, width = key.partition(u',') if comma: raise NotImplementedError('width specifier after comma ' 'is not implemented yet') return super(DotNetFormatter, self).get_value(key, args, kwargs) def format_field(self, value, format_spec): """Format specifiers are described in :func:`format_field` which is a static function. """ if format_spec: spec, arg = format_spec[0], format_spec[1:] arg = arg or None else: spec = arg = None return self._format_field(spec, arg, value, self.numeric_locale)
what-studio/smartformat
smartformat/dotnet.py
format_hexadecimal_field
python
def format_hexadecimal_field(spec, prec, number, locale): if number < 0: # Take two's complement. number &= (1 << (8 * int(math.log(-number, 1 << 8) + 1))) - 1 format_ = u'0%d%s' % (int(prec or 0), spec) return format(number, format_)
Formats a hexadeciaml field.
train
https://github.com/what-studio/smartformat/blob/5731203cbf29617ab8d42542f9dac03d5e34b217/smartformat/dotnet.py#L136-L142
null
# -*- coding: utf-8 -*- """ smartformat.dotnet ~~~~~~~~~~~~~~~~~~ :copyright: (c) 2016 by What! Studio :license: BSD, see LICENSE for more details. """ import math from numbers import Number from babel import Locale from babel.numbers import ( format_currency, get_decimal_symbol, get_territory_currencies, NumberPattern, parse_pattern) from six import string_types, text_type as str from valuedispatch import valuedispatch from .local import LocalFormatter __all__ = ['DotNetFormatter'] NUMBER_DECIMAL_DIGITS = 2 PERCENT_DECIMAL_DIGITS = 2 SCIENTIFIC_DECIMAL_DIGITS = 6 def modify_number_pattern(number_pattern, **kwargs): """Modifies a number pattern by specified keyword arguments.""" params = ['pattern', 'prefix', 'suffix', 'grouping', 'int_prec', 'frac_prec', 'exp_prec', 'exp_plus'] for param in params: if param in kwargs: continue kwargs[param] = getattr(number_pattern, param) return NumberPattern(**kwargs) @valuedispatch def format_field(spec, arg, value, locale): if spec and isinstance(value, Number): if arg: spec += arg try: pattern = parse_pattern(spec) except ValueError: return spec else: return pattern.apply(value, locale) return str(value) @format_field.register(u'c') @format_field.register(u'C') def format_currency_field(__, prec, number, locale): """Formats a currency field.""" locale = Locale.parse(locale) currency = get_territory_currencies(locale.territory)[0] if prec is None: pattern, currency_digits = None, True else: prec = int(prec) pattern = locale.currency_formats['standard'] pattern = modify_number_pattern(pattern, frac_prec=(prec, prec)) currency_digits = False return format_currency(number, currency, pattern, locale=locale, currency_digits=currency_digits) @format_field.register(u'd') @format_field.register(u'D') def format_decimal_field(__, prec, number, locale): """Formats a decimal field: .. sourcecode:: 1234 ('D') -> 1234 -1234 ('D6') -> -001234 """ prec = 0 if prec is None else int(prec) if number < 0: prec += 1 return format(number, u'0%dd' % prec) @format_field.register(u'e') @format_field.register(u'E') def format_scientific_field(spec, prec, number, locale): prec = SCIENTIFIC_DECIMAL_DIGITS if prec is None else int(prec) format_ = u'0.%sE+000' % (u'#' * prec) pattern = parse_pattern(format_) decimal_symbol = get_decimal_symbol(locale) string = pattern.apply(number, locale).replace(u'.', decimal_symbol) return string.lower() if spec.islower() else string @format_field.register(u'f') @format_field.register(u'F') def format_float_field(__, prec, number, locale): """Formats a fixed-point field.""" format_ = u'0.' if prec is None: format_ += u'#' * NUMBER_DECIMAL_DIGITS else: format_ += u'0' * int(prec) pattern = parse_pattern(format_) return pattern.apply(number, locale) @format_field.register(u'n') @format_field.register(u'N') def format_number_field(__, prec, number, locale): """Formats a number field.""" prec = NUMBER_DECIMAL_DIGITS if prec is None else int(prec) locale = Locale.parse(locale) pattern = locale.decimal_formats.get(None) return pattern.apply(number, locale, force_frac=(prec, prec)) @format_field.register(u'p') @format_field.register(u'P') def format_percent_field(__, prec, number, locale): """Formats a percent field.""" prec = PERCENT_DECIMAL_DIGITS if prec is None else int(prec) locale = Locale.parse(locale) pattern = locale.percent_formats.get(None) return pattern.apply(number, locale, force_frac=(prec, prec)) @format_field.register(u'x') @format_field.register(u'X') @format_field.register(u'g') @format_field.register(u'G') @format_field.register(u'r') @format_field.register(u'R') def format_not_implemented_field(spec, *args, **kwargs): raise NotImplementedError('numeric format specifier %r ' 'is not implemented yet' % spec) class DotNetFormatter(LocalFormatter): """A string formatter like `String.Format` in .NET Framework.""" _format_field = staticmethod(format_field) def vformat(self, format_string, args, kwargs): if not format_string: return u'' base = super(DotNetFormatter, self) return base.vformat(format_string, args, kwargs) def get_value(self, key, args, kwargs): if isinstance(key, string_types): key, comma, width = key.partition(u',') if comma: raise NotImplementedError('width specifier after comma ' 'is not implemented yet') return super(DotNetFormatter, self).get_value(key, args, kwargs) def format_field(self, value, format_spec): """Format specifiers are described in :func:`format_field` which is a static function. """ if format_spec: spec, arg = format_spec[0], format_spec[1:] arg = arg or None else: spec = arg = None return self._format_field(spec, arg, value, self.numeric_locale)
what-studio/smartformat
smartformat/dotnet.py
DotNetFormatter.format_field
python
def format_field(self, value, format_spec): if format_spec: spec, arg = format_spec[0], format_spec[1:] arg = arg or None else: spec = arg = None return self._format_field(spec, arg, value, self.numeric_locale)
Format specifiers are described in :func:`format_field` which is a static function.
train
https://github.com/what-studio/smartformat/blob/5731203cbf29617ab8d42542f9dac03d5e34b217/smartformat/dotnet.py#L173-L182
null
class DotNetFormatter(LocalFormatter): """A string formatter like `String.Format` in .NET Framework.""" _format_field = staticmethod(format_field) def vformat(self, format_string, args, kwargs): if not format_string: return u'' base = super(DotNetFormatter, self) return base.vformat(format_string, args, kwargs) def get_value(self, key, args, kwargs): if isinstance(key, string_types): key, comma, width = key.partition(u',') if comma: raise NotImplementedError('width specifier after comma ' 'is not implemented yet') return super(DotNetFormatter, self).get_value(key, args, kwargs)
what-studio/smartformat
smartformat/builtin.py
plural
python
def plural(formatter, value, name, option, format): # Extract the plural words from the format string. words = format.split('|') # This extension requires at least two plural words. if not name and len(words) == 1: return # This extension only formats numbers. try: number = decimal.Decimal(value) except (ValueError, decimal.InvalidOperation): return # Get the locale. locale = Locale.parse(option) if option else formatter.locale # Select word based on the plural tag index. index = get_plural_tag_index(number, locale) return formatter.format(words[index], value)
Chooses different textension for locale-specific pluralization rules. Spec: `{:[p[lural]][(locale)]:msgstr0|msgstr1|...}` Example:: >>> smart.format(u'There {num:is an item|are {} items}.', num=1} There is an item. >>> smart.format(u'There {num:is an item|are {} items}.', num=10} There are 10 items.
train
https://github.com/what-studio/smartformat/blob/5731203cbf29617ab8d42542f9dac03d5e34b217/smartformat/builtin.py#L26-L53
[ "def get_plural_tag_index(number, locale):\n \"\"\"Gets the plural tag index of a number on the plural rule of a locale::\n\n >>> get_plural_tag_index(1, 'en_US')\n 0\n >>> get_plural_tag_index(2, 'en_US')\n 1\n >>> get_plural_tag_index(100, 'en_US')\n 1\n\n \"\"\"\n locale = Locale.parse(locale)\n plural_rule = locale.plural_form\n used_tags = plural_rule.tags | set([_fallback_tag])\n tag, index = plural_rule(number), 0\n for _tag in _plural_tags:\n if _tag == tag:\n return index\n if _tag in used_tags:\n index += 1\n" ]
# -*- coding: utf-8 -*- """ smartformat.builtin ~~~~~~~~~~~~~~~~~~~ Built-in extensions from SmartFormat.NET, the original implementation. :copyright: (c) 2016 by What! Studio :license: BSD, see LICENSE for more details. """ import decimal import io from babel import Locale from six import string_types from .smart import default_extensions, extension from .utils import get_plural_tag_index __all__ = ['choose', 'conditional', 'list_', 'plural'] @extension(['plural', 'p', '']) def get_choice(value): """Gets a key to choose a choice from any value.""" if value is None: return 'null' for attr in ['__name__', 'name']: if hasattr(value, attr): return getattr(value, attr) return str(value) @extension(['choose', 'c']) def choose(formatter, value, name, option, format): """Adds simple logic to format strings. Spec: `{:c[hoose](choice1|choice2|...):word1|word2|...[|default]}` Example:: >>> smart.format(u'{num:choose(1|2|3):one|two|three|other}, num=1) u'one' >>> smart.format(u'{num:choose(1|2|3):one|two|three|other}, num=4) u'other' """ if not option: return words = format.split('|') num_words = len(words) if num_words < 2: return choices = option.split('|') num_choices = len(choices) # If the words has 1 more item than the choices, the last word will be # used as a default choice. if num_words not in (num_choices, num_choices + 1): n = num_choices raise ValueError('specify %d or %d choices' % (n, n + 1)) choice = get_choice(value) try: index = choices.index(choice) except ValueError: if num_words == num_choices: raise ValueError('no default choice supplied') index = -1 return formatter.format(words[index], value) @extension(['conditional', 'cond']) def conditional(formatter, value, name, option, format): """SmartFormat for Python doesn't implement it because SmartFormat.NET has deprecated the 'conditional' extension. """ raise NotImplementedError('obsolete extension: conditional') @extension(['list', 'l', '']) def list_(formatter, value, name, option, format): """Repeats the items of an array. Spec: `{:[l[ist]:]item|spacer[|final_spacer[|two_spacer]]}` Example:: >>> fruits = [u'apple', u'banana', u'coconut'] >>> smart.format(u'{fruits:list:{}|, |, and | and }', fruits=fruits) u'apple, banana, and coconut' >>> smart.format(u'{fruits:list:{}|, |, and | and }', fruits=fruits[:2]) u'apple and banana' """ if not format: return if not hasattr(value, '__getitem__') or isinstance(value, string_types): return words = format.split(u'|', 4) num_words = len(words) if num_words < 2: # Require at least two words for item format and spacer. return num_items = len(value) item_format = words[0] # NOTE: SmartFormat.NET treats a not nested item format as the format # string to format each items. For example, `x` will be treated as `{:x}`. # But the original tells us this behavior has been deprecated so that # should be removed. So SmartFormat for Python doesn't implement the # behavior. spacer = u'' if num_words < 2 else words[1] final_spacer = spacer if num_words < 3 else words[2] two_spacer = final_spacer if num_words < 4 else words[3] buf = io.StringIO() for x, item in enumerate(value): if x == 0: pass elif x < num_items - 1: buf.write(spacer) elif x == 1: buf.write(two_spacer) else: buf.write(final_spacer) buf.write(formatter.format(item_format, item, index=x)) return buf.getvalue() # Register to the default extensions registry. default_extensions.extend([plural, choose, conditional, list_])
what-studio/smartformat
smartformat/builtin.py
get_choice
python
def get_choice(value): if value is None: return 'null' for attr in ['__name__', 'name']: if hasattr(value, attr): return getattr(value, attr) return str(value)
Gets a key to choose a choice from any value.
train
https://github.com/what-studio/smartformat/blob/5731203cbf29617ab8d42542f9dac03d5e34b217/smartformat/builtin.py#L56-L63
null
# -*- coding: utf-8 -*- """ smartformat.builtin ~~~~~~~~~~~~~~~~~~~ Built-in extensions from SmartFormat.NET, the original implementation. :copyright: (c) 2016 by What! Studio :license: BSD, see LICENSE for more details. """ import decimal import io from babel import Locale from six import string_types from .smart import default_extensions, extension from .utils import get_plural_tag_index __all__ = ['choose', 'conditional', 'list_', 'plural'] @extension(['plural', 'p', '']) def plural(formatter, value, name, option, format): """Chooses different textension for locale-specific pluralization rules. Spec: `{:[p[lural]][(locale)]:msgstr0|msgstr1|...}` Example:: >>> smart.format(u'There {num:is an item|are {} items}.', num=1} There is an item. >>> smart.format(u'There {num:is an item|are {} items}.', num=10} There are 10 items. """ # Extract the plural words from the format string. words = format.split('|') # This extension requires at least two plural words. if not name and len(words) == 1: return # This extension only formats numbers. try: number = decimal.Decimal(value) except (ValueError, decimal.InvalidOperation): return # Get the locale. locale = Locale.parse(option) if option else formatter.locale # Select word based on the plural tag index. index = get_plural_tag_index(number, locale) return formatter.format(words[index], value) @extension(['choose', 'c']) def choose(formatter, value, name, option, format): """Adds simple logic to format strings. Spec: `{:c[hoose](choice1|choice2|...):word1|word2|...[|default]}` Example:: >>> smart.format(u'{num:choose(1|2|3):one|two|three|other}, num=1) u'one' >>> smart.format(u'{num:choose(1|2|3):one|two|three|other}, num=4) u'other' """ if not option: return words = format.split('|') num_words = len(words) if num_words < 2: return choices = option.split('|') num_choices = len(choices) # If the words has 1 more item than the choices, the last word will be # used as a default choice. if num_words not in (num_choices, num_choices + 1): n = num_choices raise ValueError('specify %d or %d choices' % (n, n + 1)) choice = get_choice(value) try: index = choices.index(choice) except ValueError: if num_words == num_choices: raise ValueError('no default choice supplied') index = -1 return formatter.format(words[index], value) @extension(['conditional', 'cond']) def conditional(formatter, value, name, option, format): """SmartFormat for Python doesn't implement it because SmartFormat.NET has deprecated the 'conditional' extension. """ raise NotImplementedError('obsolete extension: conditional') @extension(['list', 'l', '']) def list_(formatter, value, name, option, format): """Repeats the items of an array. Spec: `{:[l[ist]:]item|spacer[|final_spacer[|two_spacer]]}` Example:: >>> fruits = [u'apple', u'banana', u'coconut'] >>> smart.format(u'{fruits:list:{}|, |, and | and }', fruits=fruits) u'apple, banana, and coconut' >>> smart.format(u'{fruits:list:{}|, |, and | and }', fruits=fruits[:2]) u'apple and banana' """ if not format: return if not hasattr(value, '__getitem__') or isinstance(value, string_types): return words = format.split(u'|', 4) num_words = len(words) if num_words < 2: # Require at least two words for item format and spacer. return num_items = len(value) item_format = words[0] # NOTE: SmartFormat.NET treats a not nested item format as the format # string to format each items. For example, `x` will be treated as `{:x}`. # But the original tells us this behavior has been deprecated so that # should be removed. So SmartFormat for Python doesn't implement the # behavior. spacer = u'' if num_words < 2 else words[1] final_spacer = spacer if num_words < 3 else words[2] two_spacer = final_spacer if num_words < 4 else words[3] buf = io.StringIO() for x, item in enumerate(value): if x == 0: pass elif x < num_items - 1: buf.write(spacer) elif x == 1: buf.write(two_spacer) else: buf.write(final_spacer) buf.write(formatter.format(item_format, item, index=x)) return buf.getvalue() # Register to the default extensions registry. default_extensions.extend([plural, choose, conditional, list_])
what-studio/smartformat
smartformat/builtin.py
choose
python
def choose(formatter, value, name, option, format): if not option: return words = format.split('|') num_words = len(words) if num_words < 2: return choices = option.split('|') num_choices = len(choices) # If the words has 1 more item than the choices, the last word will be # used as a default choice. if num_words not in (num_choices, num_choices + 1): n = num_choices raise ValueError('specify %d or %d choices' % (n, n + 1)) choice = get_choice(value) try: index = choices.index(choice) except ValueError: if num_words == num_choices: raise ValueError('no default choice supplied') index = -1 return formatter.format(words[index], value)
Adds simple logic to format strings. Spec: `{:c[hoose](choice1|choice2|...):word1|word2|...[|default]}` Example:: >>> smart.format(u'{num:choose(1|2|3):one|two|three|other}, num=1) u'one' >>> smart.format(u'{num:choose(1|2|3):one|two|three|other}, num=4) u'other'
train
https://github.com/what-studio/smartformat/blob/5731203cbf29617ab8d42542f9dac03d5e34b217/smartformat/builtin.py#L67-L100
[ "def get_choice(value):\n \"\"\"Gets a key to choose a choice from any value.\"\"\"\n if value is None:\n return 'null'\n for attr in ['__name__', 'name']:\n if hasattr(value, attr):\n return getattr(value, attr)\n return str(value)\n" ]
# -*- coding: utf-8 -*- """ smartformat.builtin ~~~~~~~~~~~~~~~~~~~ Built-in extensions from SmartFormat.NET, the original implementation. :copyright: (c) 2016 by What! Studio :license: BSD, see LICENSE for more details. """ import decimal import io from babel import Locale from six import string_types from .smart import default_extensions, extension from .utils import get_plural_tag_index __all__ = ['choose', 'conditional', 'list_', 'plural'] @extension(['plural', 'p', '']) def plural(formatter, value, name, option, format): """Chooses different textension for locale-specific pluralization rules. Spec: `{:[p[lural]][(locale)]:msgstr0|msgstr1|...}` Example:: >>> smart.format(u'There {num:is an item|are {} items}.', num=1} There is an item. >>> smart.format(u'There {num:is an item|are {} items}.', num=10} There are 10 items. """ # Extract the plural words from the format string. words = format.split('|') # This extension requires at least two plural words. if not name and len(words) == 1: return # This extension only formats numbers. try: number = decimal.Decimal(value) except (ValueError, decimal.InvalidOperation): return # Get the locale. locale = Locale.parse(option) if option else formatter.locale # Select word based on the plural tag index. index = get_plural_tag_index(number, locale) return formatter.format(words[index], value) def get_choice(value): """Gets a key to choose a choice from any value.""" if value is None: return 'null' for attr in ['__name__', 'name']: if hasattr(value, attr): return getattr(value, attr) return str(value) @extension(['choose', 'c']) @extension(['conditional', 'cond']) def conditional(formatter, value, name, option, format): """SmartFormat for Python doesn't implement it because SmartFormat.NET has deprecated the 'conditional' extension. """ raise NotImplementedError('obsolete extension: conditional') @extension(['list', 'l', '']) def list_(formatter, value, name, option, format): """Repeats the items of an array. Spec: `{:[l[ist]:]item|spacer[|final_spacer[|two_spacer]]}` Example:: >>> fruits = [u'apple', u'banana', u'coconut'] >>> smart.format(u'{fruits:list:{}|, |, and | and }', fruits=fruits) u'apple, banana, and coconut' >>> smart.format(u'{fruits:list:{}|, |, and | and }', fruits=fruits[:2]) u'apple and banana' """ if not format: return if not hasattr(value, '__getitem__') or isinstance(value, string_types): return words = format.split(u'|', 4) num_words = len(words) if num_words < 2: # Require at least two words for item format and spacer. return num_items = len(value) item_format = words[0] # NOTE: SmartFormat.NET treats a not nested item format as the format # string to format each items. For example, `x` will be treated as `{:x}`. # But the original tells us this behavior has been deprecated so that # should be removed. So SmartFormat for Python doesn't implement the # behavior. spacer = u'' if num_words < 2 else words[1] final_spacer = spacer if num_words < 3 else words[2] two_spacer = final_spacer if num_words < 4 else words[3] buf = io.StringIO() for x, item in enumerate(value): if x == 0: pass elif x < num_items - 1: buf.write(spacer) elif x == 1: buf.write(two_spacer) else: buf.write(final_spacer) buf.write(formatter.format(item_format, item, index=x)) return buf.getvalue() # Register to the default extensions registry. default_extensions.extend([plural, choose, conditional, list_])
what-studio/smartformat
smartformat/builtin.py
list_
python
def list_(formatter, value, name, option, format): if not format: return if not hasattr(value, '__getitem__') or isinstance(value, string_types): return words = format.split(u'|', 4) num_words = len(words) if num_words < 2: # Require at least two words for item format and spacer. return num_items = len(value) item_format = words[0] # NOTE: SmartFormat.NET treats a not nested item format as the format # string to format each items. For example, `x` will be treated as `{:x}`. # But the original tells us this behavior has been deprecated so that # should be removed. So SmartFormat for Python doesn't implement the # behavior. spacer = u'' if num_words < 2 else words[1] final_spacer = spacer if num_words < 3 else words[2] two_spacer = final_spacer if num_words < 4 else words[3] buf = io.StringIO() for x, item in enumerate(value): if x == 0: pass elif x < num_items - 1: buf.write(spacer) elif x == 1: buf.write(two_spacer) else: buf.write(final_spacer) buf.write(formatter.format(item_format, item, index=x)) return buf.getvalue()
Repeats the items of an array. Spec: `{:[l[ist]:]item|spacer[|final_spacer[|two_spacer]]}` Example:: >>> fruits = [u'apple', u'banana', u'coconut'] >>> smart.format(u'{fruits:list:{}|, |, and | and }', fruits=fruits) u'apple, banana, and coconut' >>> smart.format(u'{fruits:list:{}|, |, and | and }', fruits=fruits[:2]) u'apple and banana'
train
https://github.com/what-studio/smartformat/blob/5731203cbf29617ab8d42542f9dac03d5e34b217/smartformat/builtin.py#L112-L156
null
# -*- coding: utf-8 -*- """ smartformat.builtin ~~~~~~~~~~~~~~~~~~~ Built-in extensions from SmartFormat.NET, the original implementation. :copyright: (c) 2016 by What! Studio :license: BSD, see LICENSE for more details. """ import decimal import io from babel import Locale from six import string_types from .smart import default_extensions, extension from .utils import get_plural_tag_index __all__ = ['choose', 'conditional', 'list_', 'plural'] @extension(['plural', 'p', '']) def plural(formatter, value, name, option, format): """Chooses different textension for locale-specific pluralization rules. Spec: `{:[p[lural]][(locale)]:msgstr0|msgstr1|...}` Example:: >>> smart.format(u'There {num:is an item|are {} items}.', num=1} There is an item. >>> smart.format(u'There {num:is an item|are {} items}.', num=10} There are 10 items. """ # Extract the plural words from the format string. words = format.split('|') # This extension requires at least two plural words. if not name and len(words) == 1: return # This extension only formats numbers. try: number = decimal.Decimal(value) except (ValueError, decimal.InvalidOperation): return # Get the locale. locale = Locale.parse(option) if option else formatter.locale # Select word based on the plural tag index. index = get_plural_tag_index(number, locale) return formatter.format(words[index], value) def get_choice(value): """Gets a key to choose a choice from any value.""" if value is None: return 'null' for attr in ['__name__', 'name']: if hasattr(value, attr): return getattr(value, attr) return str(value) @extension(['choose', 'c']) def choose(formatter, value, name, option, format): """Adds simple logic to format strings. Spec: `{:c[hoose](choice1|choice2|...):word1|word2|...[|default]}` Example:: >>> smart.format(u'{num:choose(1|2|3):one|two|three|other}, num=1) u'one' >>> smart.format(u'{num:choose(1|2|3):one|two|three|other}, num=4) u'other' """ if not option: return words = format.split('|') num_words = len(words) if num_words < 2: return choices = option.split('|') num_choices = len(choices) # If the words has 1 more item than the choices, the last word will be # used as a default choice. if num_words not in (num_choices, num_choices + 1): n = num_choices raise ValueError('specify %d or %d choices' % (n, n + 1)) choice = get_choice(value) try: index = choices.index(choice) except ValueError: if num_words == num_choices: raise ValueError('no default choice supplied') index = -1 return formatter.format(words[index], value) @extension(['conditional', 'cond']) def conditional(formatter, value, name, option, format): """SmartFormat for Python doesn't implement it because SmartFormat.NET has deprecated the 'conditional' extension. """ raise NotImplementedError('obsolete extension: conditional') @extension(['list', 'l', '']) # Register to the default extensions registry. default_extensions.extend([plural, choose, conditional, list_])
what-studio/smartformat
smartformat/utils.py
get_plural_tag_index
python
def get_plural_tag_index(number, locale): locale = Locale.parse(locale) plural_rule = locale.plural_form used_tags = plural_rule.tags | set([_fallback_tag]) tag, index = plural_rule(number), 0 for _tag in _plural_tags: if _tag == tag: return index if _tag in used_tags: index += 1
Gets the plural tag index of a number on the plural rule of a locale:: >>> get_plural_tag_index(1, 'en_US') 0 >>> get_plural_tag_index(2, 'en_US') 1 >>> get_plural_tag_index(100, 'en_US') 1
train
https://github.com/what-studio/smartformat/blob/5731203cbf29617ab8d42542f9dac03d5e34b217/smartformat/utils.py#L17-L36
null
# -*- coding: utf-8 -*- """ smartformat.utils ~~~~~~~~~~~~~~~~~ :copyright: (c) 2016 by What! Studio :license: BSD, see LICENSE for more details. """ from babel import Locale from babel.plural import _fallback_tag, _plural_tags __all__ = ['get_plural_tag_index']
what-studio/smartformat
smartformat/smart.py
extension
python
def extension(names): for name in names: if not NAME_PATTERN.match(name): raise ValueError('invalid extension name: %s' % name) def decorator(f, names=names): return Extension(f, names=names) return decorator
Makes a function to be an extension.
train
https://github.com/what-studio/smartformat/blob/5731203cbf29617ab8d42542f9dac03d5e34b217/smartformat/smart.py#L190-L197
null
# -*- coding: utf-8 -*- """ smartformat.smart ~~~~~~~~~~~~~~~~~ :copyright: (c) 2016 by What! Studio :license: BSD, see LICENSE for more details. """ from collections import deque import io import re import string import sys from types import MethodType from six import reraise, text_type from .dotnet import DotNetFormatter __all__ = ['default_extensions', 'extension', 'SmartFormatter'] #: The extensions to be registered by default. default_extensions = deque() NAME_PATTERN = re.compile(r'[a-zA-Z_]*') FORMAT_SPEC_PATTERN = re.compile(r''' (?: (?P<name>[a-zA-Z_]+) (?: \((?P<option>.*)\) )? : )? (?P<format>.*) ''', re.VERBOSE | re.UNICODE) # :meth:`string.Formatter._vformat` on Python 3.5.1 returns a pair # `(format_spec, auto_arg_index)`. The method is not public but we should # override it to keep nested format specs. f = string.Formatter() VFORMAT_RETURNS_TUPLE = isinstance(f._vformat('', (), {}, [], 0), tuple) del f def parse_format_spec(format_spec): m = FORMAT_SPEC_PATTERN.match(format_spec) return m.group('name') or u'', m.group('option'), m.group('format') class SmartFormatter(DotNetFormatter): def __init__(self, locale=None, extensions=(), register_default=True, errors='strict'): super(SmartFormatter, self).__init__(locale) # Set error action. try: _format_error = self._error_formatters[errors] except KeyError: raise LookupError('unknown error action name %s' % errors) self.format_error = MethodType(_format_error, self) if errors == 'skip': self.parse = self._parse_for_skip_error_action self.errors = errors # Currently implemented only formatter extensions. self._extensions = {} if register_default: self.register(default_extensions) self.register(extensions) def register(self, extensions): """Registers extensions.""" for ext in reversed(extensions): for name in ext.names: try: self._extensions[name].appendleft(ext) except KeyError: self._extensions[name] = deque([ext]) def format_field(self, value, format_spec): name, option, format = parse_format_spec(format_spec) try: rv = self.eval_extensions(value, name, option, format) if rv is not None: return rv base = super(SmartFormatter, self) return base.format_field(value, format_spec) except: return self.format_error(sys.exc_info()) def eval_extensions(self, value, name, option, format): """Evaluates extensions in the registry. If some extension handles the format string, it returns a string. Otherwise, returns ``None``. """ try: exts = self._extensions[name] except KeyError: raise ValueError('no suitable extension: %s' % name) for ext in exts: rv = ext(self, value, name, option, format) if rv is not None: return rv def get_value(self, field_name, args, kwargs): if not field_name: # `{}` is same with `{0}`. field_name = 0 return super(SmartFormatter, self).get_value(field_name, args, kwargs) def _vformat(self, format_string, _1, _2, _3, recursion_depth, *args, **kwargs): if recursion_depth != 2: # Don't format recursive format strings such as `{:12{this}34}`. if VFORMAT_RETURNS_TUPLE: return (format_string, False) else: return format_string base = super(SmartFormatter, self) return base._vformat(format_string, _1, _2, _3, 1, *args, **kwargs) def format_error(self, exc_info): raise NotImplementedError('will be set by __init__') def _format_error_for_strict_error_action(self, exc_info): reraise(*exc_info) def _format_error_for_errmsg_error_action(self, exc_info): __, exc, __ = exc_info return text_type(exc) def _format_error_for_ignore_error_action(self, exc_info): return u'' def _format_error_for_skip_error_action(self, exc_info): __, field_name, format_spec, conversion = self._parsed buf = io.StringIO() buf.write(u'{%s' % field_name) if conversion: buf.write(u'!%s' % conversion) if format_spec: buf.write(u':%s' % format_spec) buf.write(u'}') return buf.getvalue() _error_formatters = { # ErrorAction.ThrowError in C# SmartFormat. 'strict': _format_error_for_strict_error_action, # ErrorAction.OutputErrorInResult in C# SmartFormat. 'errmsg': _format_error_for_errmsg_error_action, # ErrorAction.Ignore in C# SmartFormat. 'ignore': _format_error_for_ignore_error_action, # ErrorAction.MaintainTokens in C# SmartFormat. 'skip': _format_error_for_skip_error_action, } def _parse_for_skip_error_action(self, format_string): for parsed in super(SmartFormatter, self).parse(format_string): self._parsed = parsed yield parsed del self._parsed ERROR_ACTIONS = list(SmartFormatter._error_formatters.keys()) class Extension(object): """A formatter extension which wraps a function. It works like a wrapped function but has several specific attributes and methods. A funciton to be an extension takes `(name, option, format)`. The funcion should return a string as the result or ``None`` to pass to format a string. To make an extension, use `@extension` decorator. """ def __init__(self, function, names): self.function = function self.names = names def __call__(self, *args, **kwargs): return self.function(*args, **kwargs) # Register built-in extensions. from . import builtin # noqa del builtin
what-studio/smartformat
smartformat/smart.py
SmartFormatter.register
python
def register(self, extensions): for ext in reversed(extensions): for name in ext.names: try: self._extensions[name].appendleft(ext) except KeyError: self._extensions[name] = deque([ext])
Registers extensions.
train
https://github.com/what-studio/smartformat/blob/5731203cbf29617ab8d42542f9dac03d5e34b217/smartformat/smart.py#L75-L82
null
class SmartFormatter(DotNetFormatter): def __init__(self, locale=None, extensions=(), register_default=True, errors='strict'): super(SmartFormatter, self).__init__(locale) # Set error action. try: _format_error = self._error_formatters[errors] except KeyError: raise LookupError('unknown error action name %s' % errors) self.format_error = MethodType(_format_error, self) if errors == 'skip': self.parse = self._parse_for_skip_error_action self.errors = errors # Currently implemented only formatter extensions. self._extensions = {} if register_default: self.register(default_extensions) self.register(extensions) def format_field(self, value, format_spec): name, option, format = parse_format_spec(format_spec) try: rv = self.eval_extensions(value, name, option, format) if rv is not None: return rv base = super(SmartFormatter, self) return base.format_field(value, format_spec) except: return self.format_error(sys.exc_info()) def eval_extensions(self, value, name, option, format): """Evaluates extensions in the registry. If some extension handles the format string, it returns a string. Otherwise, returns ``None``. """ try: exts = self._extensions[name] except KeyError: raise ValueError('no suitable extension: %s' % name) for ext in exts: rv = ext(self, value, name, option, format) if rv is not None: return rv def get_value(self, field_name, args, kwargs): if not field_name: # `{}` is same with `{0}`. field_name = 0 return super(SmartFormatter, self).get_value(field_name, args, kwargs) def _vformat(self, format_string, _1, _2, _3, recursion_depth, *args, **kwargs): if recursion_depth != 2: # Don't format recursive format strings such as `{:12{this}34}`. if VFORMAT_RETURNS_TUPLE: return (format_string, False) else: return format_string base = super(SmartFormatter, self) return base._vformat(format_string, _1, _2, _3, 1, *args, **kwargs) def format_error(self, exc_info): raise NotImplementedError('will be set by __init__') def _format_error_for_strict_error_action(self, exc_info): reraise(*exc_info) def _format_error_for_errmsg_error_action(self, exc_info): __, exc, __ = exc_info return text_type(exc) def _format_error_for_ignore_error_action(self, exc_info): return u'' def _format_error_for_skip_error_action(self, exc_info): __, field_name, format_spec, conversion = self._parsed buf = io.StringIO() buf.write(u'{%s' % field_name) if conversion: buf.write(u'!%s' % conversion) if format_spec: buf.write(u':%s' % format_spec) buf.write(u'}') return buf.getvalue() _error_formatters = { # ErrorAction.ThrowError in C# SmartFormat. 'strict': _format_error_for_strict_error_action, # ErrorAction.OutputErrorInResult in C# SmartFormat. 'errmsg': _format_error_for_errmsg_error_action, # ErrorAction.Ignore in C# SmartFormat. 'ignore': _format_error_for_ignore_error_action, # ErrorAction.MaintainTokens in C# SmartFormat. 'skip': _format_error_for_skip_error_action, } def _parse_for_skip_error_action(self, format_string): for parsed in super(SmartFormatter, self).parse(format_string): self._parsed = parsed yield parsed del self._parsed
what-studio/smartformat
smartformat/smart.py
SmartFormatter.eval_extensions
python
def eval_extensions(self, value, name, option, format): try: exts = self._extensions[name] except KeyError: raise ValueError('no suitable extension: %s' % name) for ext in exts: rv = ext(self, value, name, option, format) if rv is not None: return rv
Evaluates extensions in the registry. If some extension handles the format string, it returns a string. Otherwise, returns ``None``.
train
https://github.com/what-studio/smartformat/blob/5731203cbf29617ab8d42542f9dac03d5e34b217/smartformat/smart.py#L95-L106
null
class SmartFormatter(DotNetFormatter): def __init__(self, locale=None, extensions=(), register_default=True, errors='strict'): super(SmartFormatter, self).__init__(locale) # Set error action. try: _format_error = self._error_formatters[errors] except KeyError: raise LookupError('unknown error action name %s' % errors) self.format_error = MethodType(_format_error, self) if errors == 'skip': self.parse = self._parse_for_skip_error_action self.errors = errors # Currently implemented only formatter extensions. self._extensions = {} if register_default: self.register(default_extensions) self.register(extensions) def register(self, extensions): """Registers extensions.""" for ext in reversed(extensions): for name in ext.names: try: self._extensions[name].appendleft(ext) except KeyError: self._extensions[name] = deque([ext]) def format_field(self, value, format_spec): name, option, format = parse_format_spec(format_spec) try: rv = self.eval_extensions(value, name, option, format) if rv is not None: return rv base = super(SmartFormatter, self) return base.format_field(value, format_spec) except: return self.format_error(sys.exc_info()) def get_value(self, field_name, args, kwargs): if not field_name: # `{}` is same with `{0}`. field_name = 0 return super(SmartFormatter, self).get_value(field_name, args, kwargs) def _vformat(self, format_string, _1, _2, _3, recursion_depth, *args, **kwargs): if recursion_depth != 2: # Don't format recursive format strings such as `{:12{this}34}`. if VFORMAT_RETURNS_TUPLE: return (format_string, False) else: return format_string base = super(SmartFormatter, self) return base._vformat(format_string, _1, _2, _3, 1, *args, **kwargs) def format_error(self, exc_info): raise NotImplementedError('will be set by __init__') def _format_error_for_strict_error_action(self, exc_info): reraise(*exc_info) def _format_error_for_errmsg_error_action(self, exc_info): __, exc, __ = exc_info return text_type(exc) def _format_error_for_ignore_error_action(self, exc_info): return u'' def _format_error_for_skip_error_action(self, exc_info): __, field_name, format_spec, conversion = self._parsed buf = io.StringIO() buf.write(u'{%s' % field_name) if conversion: buf.write(u'!%s' % conversion) if format_spec: buf.write(u':%s' % format_spec) buf.write(u'}') return buf.getvalue() _error_formatters = { # ErrorAction.ThrowError in C# SmartFormat. 'strict': _format_error_for_strict_error_action, # ErrorAction.OutputErrorInResult in C# SmartFormat. 'errmsg': _format_error_for_errmsg_error_action, # ErrorAction.Ignore in C# SmartFormat. 'ignore': _format_error_for_ignore_error_action, # ErrorAction.MaintainTokens in C# SmartFormat. 'skip': _format_error_for_skip_error_action, } def _parse_for_skip_error_action(self, format_string): for parsed in super(SmartFormatter, self).parse(format_string): self._parsed = parsed yield parsed del self._parsed
what-studio/smartformat
smartformat/local.py
LocalFormatter.format_field_by_match
python
def format_field_by_match(self, value, match): groups = match.groups() fill, align, sign, sharp, zero, width, comma, prec, type_ = groups if not comma and not prec and type_ not in list('fF%'): return None if math.isnan(value) or math.isinf(value): return None locale = self.numeric_locale # Format number value. prefix = get_prefix(sign) if type_ == 'd': if prec is not None: raise ValueError('precision not allowed in ' 'integer format specifier') string = format_number(value, 0, prefix, locale) elif type_ in 'fF%': format_ = format_percent if type_ == '%' else format_number string = format_(value, int(prec or DEFAULT_PREC), prefix, locale) else: # Don't handle otherwise. return None if not comma: # Formatted number always contains group symbols. # Remove the symbols if not required. string = remove_group_symbols(string, locale) if not (fill or align or zero or width): return string # Fix a layout. spec = ''.join([fill or u'', align or u'>', zero or u'', width or u'']) return format(string, spec)
Formats a field by a Regex match of the format spec pattern.
train
https://github.com/what-studio/smartformat/blob/5731203cbf29617ab8d42542f9dac03d5e34b217/smartformat/local.py#L102-L133
null
class LocalFormatter(string.Formatter): """A formatter which keeps a locale.""" def __init__(self, locale): self.locale = Locale.parse(locale) @property def numeric_locale(self): return self.locale or LC_NUMERIC def format_field(self, value, format_spec): match = FORMAT_SPEC_PATTERN.match(format_spec) if match is not None: rv = self.format_field_by_match(value, match) if rv is not None: return rv base = super(LocalFormatter, self) return base.format_field(value, format_spec)
BrianHicks/emit
examples/regex/graph.py
parse_querystring
python
def parse_querystring(msg): 'parse a querystring into keys and values' for part in msg.querystring.strip().lstrip('?').split('&'): key, value = part.split('=') yield key, value
parse a querystring into keys and values
train
https://github.com/BrianHicks/emit/blob/19a86c2392b136c9e857000798ccaa525aa0ed84/examples/regex/graph.py#L14-L18
null
from emit import Router from emit.message import NoResult from redis import Redis router = Router() redis = Redis() def prefix(name): return '%s.%s' % (__name__, name) @router.node(('key', 'value'), entry_point=True) @router.node(('key', 'value', 'count'), prefix('parse_querystring')) def count_keyval(msg): count = redis.zincrby('querystring_count.%s' % msg.key, msg.value, 1) return msg.key, msg.value, count @router.node(tuple(), '.+') def notify_on_emit(msg): redis.publish('notify_on_emit.%s' % msg._origin, msg.as_json()) return NoResult
BrianHicks/emit
emit/router/core.py
Router.wrap_as_node
python
def wrap_as_node(self, func): 'wrap a function as a node' name = self.get_name(func) @wraps(func) def wrapped(*args, **kwargs): 'wrapped version of func' message = self.get_message_from_call(*args, **kwargs) self.logger.info('calling "%s" with %r', name, message) result = func(message) # functions can return multiple values ("emit" multiple times) # by yielding instead of returning. Handle this case by making # a list of the results and processing them all after the # generator successfully exits. If we were to process them as # they came out of the generator, we might get a partially # processed input sent down the graph. This may be possible in # the future via a flag. if isinstance(result, GeneratorType): results = [ self.wrap_result(name, item) for item in result if item is not NoResult ] self.logger.debug( '%s returned generator yielding %d items', func, len(results) ) [self.route(name, item) for item in results] return tuple(results) # the case of a direct return is simpler. wrap, route, and # return the value. else: if result is NoResult: return result result = self.wrap_result(name, result) self.logger.debug( '%s returned single value %s', func, result ) self.route(name, result) return result return wrapped
wrap a function as a node
train
https://github.com/BrianHicks/emit/blob/19a86c2392b136c9e857000798ccaa525aa0ed84/emit/router/core.py#L61-L105
[ "def get_name(self, func):\n '''\n Get the name to reference a function by\n\n :param func: function to get the name of\n :type func: callable\n '''\n if hasattr(func, 'name'):\n return func.name\n\n return '%s.%s' % (\n func.__module__,\n func.__name__\n )\n" ]
class Router(object): 'A router object. Holds routes and references to functions for dispatch' def __init__(self, message_class=None, node_modules=None, node_package=None): '''\ Create a new router object. All parameters are optional. :param message_class: wrapper class for messages passed to nodes :type message_class: :py:class:`emit.message.Message` or subclass :param node_modules: a list of modules that contain nodes :type node_modules: a list of :py:class:`str`, or ``None``. :param node_package: if any node_modules are relative, the path to base off of. :type node_package: :py:class:`str`, or ``None``. :exceptions: None :returns: None ''' self.routes = {} self.names = set() self.regexes = {} self.ignore_regexes = {} self.fields = {} self.functions = {} self.message_class = message_class or Message # manage imported packages, lazily importing before the first message # is routed. self.resolved_node_modules = [] self.node_modules = node_modules or [] self.node_package = node_package self.logger = logging.getLogger(__name__ + '.Router') self.logger.debug('Initialized Router') self.routing_enabled = True def __call__(self, **kwargs): '''\ Route a message to all nodes marked as entry points. .. note:: This function does not optionally accept a single argument (dictionary) as other points in this API do - it must be expanded to keyword arguments in this case. ''' self.logger.info('Calling entry point with %r', kwargs) self.route('__entry_point', kwargs) def node(self, fields, subscribe_to=None, entry_point=False, ignore=None, **wrapper_options): '''\ Decorate a function to make it a node. .. note:: decorating as a node changes the function signature. Nodes should accept a single argument, which will be a :py:class:`emit.message.Message`. Nodes can be called directly by providing a dictionary argument or a set of keyword arguments. Other uses will raise a ``TypeError``. :param fields: fields that this function returns :type fields: ordered iterable of :py:class:`str` :param subscribe_to: functions in the graph to subscribe to. These indicators can be regular expressions. :type subscribe_to: :py:class:`str` or iterable of :py:class:`str` :param ignore: functions in the graph to ignore (also uses regular expressions.) Useful for ignoring specific functions in a broad regex. :type ignore: :py:class:`str` or iterable of :py:class:`str` :param entry_point: Set to ``True`` to mark this as an entry point - that is, this function will be called when the router is called directly. :type entry_point: :py:class:`bool` In addition to all of the above, you can define a ``wrap_node`` function on a subclass of Router, which will need to receive node and an options dictionary. Any extra options passed to node will be passed down to the options dictionary. See :py:class:`emit.router.CeleryRouter.wrap_node` as an example. :returns: decorated and wrapped function, or decorator if called directly ''' def outer(func): 'outer level function' # create a wrapper function self.logger.debug('wrapping %s', func) wrapped = self.wrap_as_node(func) if hasattr(self, 'wrap_node'): self.logger.debug('wrapping node "%s" in custom wrapper', wrapped) wrapped = self.wrap_node(wrapped, wrapper_options) # register the task in the graph name = self.get_name(func) self.register( name, wrapped, fields, subscribe_to, entry_point, ignore ) return wrapped return outer def resolve_node_modules(self): 'import the modules specified in init' if not self.resolved_node_modules: try: self.resolved_node_modules = [ importlib.import_module(mod, self.node_package) for mod in self.node_modules ] except ImportError: self.resolved_node_modules = [] raise return self.resolved_node_modules def get_message_from_call(self, *args, **kwargs): '''\ Get message object from a call. :raises: :py:exc:`TypeError` (if the format is not what we expect) This is where arguments to nodes are turned into Messages. Arguments are parsed in the following order: - A single positional argument (a :py:class:`dict`) - No positional arguments and a number of keyword arguments ''' if len(args) == 1 and isinstance(args[0], dict): # then it's a message self.logger.debug('called with arg dictionary') result = args[0] elif len(args) == 0 and kwargs != {}: # then it's a set of kwargs self.logger.debug('called with kwargs') result = kwargs else: # it's neither, and we don't handle that self.logger.error( 'get_message_from_call could not handle "%r", "%r"', args, kwargs ) raise TypeError('Pass either keyword arguments or a dictionary argument') return self.message_class(result) def register(self, name, func, fields, subscribe_to, entry_point, ignore): ''' Register a named function in the graph :param name: name to register :type name: :py:class:`str` :param func: function to remember and call :type func: callable ``fields``, ``subscribe_to`` and ``entry_point`` are the same as in :py:meth:`Router.node`. ''' self.fields[name] = fields self.functions[name] = func self.register_route(subscribe_to, name) if ignore: self.register_ignore(ignore, name) if entry_point: self.add_entry_point(name) self.logger.info('registered %s', name) def add_entry_point(self, destination): '''\ Add an entry point :param destination: node to route to initially :type destination: str ''' self.routes.setdefault('__entry_point', set()).add(destination) return self.routes['__entry_point'] def register_route(self, origins, destination): ''' Add routes to the routing dictionary :param origins: a number of origins to register :type origins: :py:class:`str` or iterable of :py:class:`str` or None :param destination: where the origins should point to :type destination: :py:class:`str` Routing dictionary takes the following form:: {'node_a': set(['node_b', 'node_c']), 'node_b': set(['node_d'])} ''' self.names.add(destination) self.logger.debug('added "%s" to names', destination) origins = origins or [] # remove None if not isinstance(origins, list): origins = [origins] self.regexes.setdefault(destination, [re.compile(origin) for origin in origins]) self.regenerate_routes() return self.regexes[destination] def register_ignore(self, origins, destination): ''' Add routes to the ignore dictionary :param origins: a number of origins to register :type origins: :py:class:`str` or iterable of :py:class:`str` :param destination: where the origins should point to :type destination: :py:class:`str` Ignore dictionary takes the following form:: {'node_a': set(['node_b', 'node_c']), 'node_b': set(['node_d'])} ''' if not isinstance(origins, list): origins = [origins] self.ignore_regexes.setdefault(destination, [re.compile(origin) for origin in origins]) self.regenerate_routes() return self.ignore_regexes[destination] def regenerate_routes(self): 'regenerate the routes after a new route is added' for destination, origins in self.regexes.items(): # we want only the names that match the destination regexes. resolved = [ name for name in self.names if name is not destination and any(origin.search(name) for origin in origins) ] ignores = self.ignore_regexes.get(destination, []) for origin in resolved: destinations = self.routes.setdefault(origin, set()) if any(ignore.search(origin) for ignore in ignores): self.logger.info('ignoring route "%s" -> "%s"', origin, destination) try: destinations.remove(destination) self.logger.debug('removed "%s" -> "%s"', origin, destination) except KeyError: pass continue if destination not in destinations: self.logger.info('added route "%s" -> "%s"', origin, destination) destinations.add(destination) def disable_routing(self): 'disable routing (usually for testing purposes)' self.routing_enabled = False def enable_routing(self): 'enable routing (after calling ``disable_routing``)' self.routing_enabled = True def route(self, origin, message): '''\ Using the routing dictionary, dispatch a message to all subscribers :param origin: name of the origin node :type origin: :py:class:`str` :param message: message to dispatch :type message: :py:class:`emit.message.Message` or subclass ''' # side-effect: we have to know all the routes before we can route. But # we can't resolve them while the object is initializing, so we have to # do it just in time to route. self.resolve_node_modules() if not self.routing_enabled: return subs = self.routes.get(origin, set()) for destination in subs: self.logger.debug('routing "%s" -> "%s"', origin, destination) self.dispatch(origin, destination, message) def dispatch(self, origin, destination, message): '''\ dispatch a message to a named function :param destination: destination to dispatch to :type destination: :py:class:`str` :param message: message to dispatch :type message: :py:class:`emit.message.Message` or subclass ''' func = self.functions[destination] self.logger.debug('calling %r directly', func) return func(_origin=origin, **message) def wrap_result(self, name, result): ''' Wrap a result from a function with it's stated fields :param name: fields to look up :type name: :py:class:`str` :param result: return value from function. Will be converted to tuple. :type result: anything :raises: :py:exc:`ValueError` if name has no associated fields :returns: :py:class:`dict` ''' if not isinstance(result, tuple): result = tuple([result]) try: return dict(zip(self.fields[name], result)) except KeyError: msg = '"%s" has no associated fields' self.logger.exception(msg, name) raise ValueError(msg % name) def get_name(self, func): ''' Get the name to reference a function by :param func: function to get the name of :type func: callable ''' if hasattr(func, 'name'): return func.name return '%s.%s' % ( func.__module__, func.__name__ )
BrianHicks/emit
emit/router/core.py
Router.node
python
def node(self, fields, subscribe_to=None, entry_point=False, ignore=None, **wrapper_options): '''\ Decorate a function to make it a node. .. note:: decorating as a node changes the function signature. Nodes should accept a single argument, which will be a :py:class:`emit.message.Message`. Nodes can be called directly by providing a dictionary argument or a set of keyword arguments. Other uses will raise a ``TypeError``. :param fields: fields that this function returns :type fields: ordered iterable of :py:class:`str` :param subscribe_to: functions in the graph to subscribe to. These indicators can be regular expressions. :type subscribe_to: :py:class:`str` or iterable of :py:class:`str` :param ignore: functions in the graph to ignore (also uses regular expressions.) Useful for ignoring specific functions in a broad regex. :type ignore: :py:class:`str` or iterable of :py:class:`str` :param entry_point: Set to ``True`` to mark this as an entry point - that is, this function will be called when the router is called directly. :type entry_point: :py:class:`bool` In addition to all of the above, you can define a ``wrap_node`` function on a subclass of Router, which will need to receive node and an options dictionary. Any extra options passed to node will be passed down to the options dictionary. See :py:class:`emit.router.CeleryRouter.wrap_node` as an example. :returns: decorated and wrapped function, or decorator if called directly ''' def outer(func): 'outer level function' # create a wrapper function self.logger.debug('wrapping %s', func) wrapped = self.wrap_as_node(func) if hasattr(self, 'wrap_node'): self.logger.debug('wrapping node "%s" in custom wrapper', wrapped) wrapped = self.wrap_node(wrapped, wrapper_options) # register the task in the graph name = self.get_name(func) self.register( name, wrapped, fields, subscribe_to, entry_point, ignore ) return wrapped return outer
\ Decorate a function to make it a node. .. note:: decorating as a node changes the function signature. Nodes should accept a single argument, which will be a :py:class:`emit.message.Message`. Nodes can be called directly by providing a dictionary argument or a set of keyword arguments. Other uses will raise a ``TypeError``. :param fields: fields that this function returns :type fields: ordered iterable of :py:class:`str` :param subscribe_to: functions in the graph to subscribe to. These indicators can be regular expressions. :type subscribe_to: :py:class:`str` or iterable of :py:class:`str` :param ignore: functions in the graph to ignore (also uses regular expressions.) Useful for ignoring specific functions in a broad regex. :type ignore: :py:class:`str` or iterable of :py:class:`str` :param entry_point: Set to ``True`` to mark this as an entry point - that is, this function will be called when the router is called directly. :type entry_point: :py:class:`bool` In addition to all of the above, you can define a ``wrap_node`` function on a subclass of Router, which will need to receive node and an options dictionary. Any extra options passed to node will be passed down to the options dictionary. See :py:class:`emit.router.CeleryRouter.wrap_node` as an example. :returns: decorated and wrapped function, or decorator if called directly
train
https://github.com/BrianHicks/emit/blob/19a86c2392b136c9e857000798ccaa525aa0ed84/emit/router/core.py#L107-L159
null
class Router(object): 'A router object. Holds routes and references to functions for dispatch' def __init__(self, message_class=None, node_modules=None, node_package=None): '''\ Create a new router object. All parameters are optional. :param message_class: wrapper class for messages passed to nodes :type message_class: :py:class:`emit.message.Message` or subclass :param node_modules: a list of modules that contain nodes :type node_modules: a list of :py:class:`str`, or ``None``. :param node_package: if any node_modules are relative, the path to base off of. :type node_package: :py:class:`str`, or ``None``. :exceptions: None :returns: None ''' self.routes = {} self.names = set() self.regexes = {} self.ignore_regexes = {} self.fields = {} self.functions = {} self.message_class = message_class or Message # manage imported packages, lazily importing before the first message # is routed. self.resolved_node_modules = [] self.node_modules = node_modules or [] self.node_package = node_package self.logger = logging.getLogger(__name__ + '.Router') self.logger.debug('Initialized Router') self.routing_enabled = True def __call__(self, **kwargs): '''\ Route a message to all nodes marked as entry points. .. note:: This function does not optionally accept a single argument (dictionary) as other points in this API do - it must be expanded to keyword arguments in this case. ''' self.logger.info('Calling entry point with %r', kwargs) self.route('__entry_point', kwargs) def wrap_as_node(self, func): 'wrap a function as a node' name = self.get_name(func) @wraps(func) def wrapped(*args, **kwargs): 'wrapped version of func' message = self.get_message_from_call(*args, **kwargs) self.logger.info('calling "%s" with %r', name, message) result = func(message) # functions can return multiple values ("emit" multiple times) # by yielding instead of returning. Handle this case by making # a list of the results and processing them all after the # generator successfully exits. If we were to process them as # they came out of the generator, we might get a partially # processed input sent down the graph. This may be possible in # the future via a flag. if isinstance(result, GeneratorType): results = [ self.wrap_result(name, item) for item in result if item is not NoResult ] self.logger.debug( '%s returned generator yielding %d items', func, len(results) ) [self.route(name, item) for item in results] return tuple(results) # the case of a direct return is simpler. wrap, route, and # return the value. else: if result is NoResult: return result result = self.wrap_result(name, result) self.logger.debug( '%s returned single value %s', func, result ) self.route(name, result) return result return wrapped def resolve_node_modules(self): 'import the modules specified in init' if not self.resolved_node_modules: try: self.resolved_node_modules = [ importlib.import_module(mod, self.node_package) for mod in self.node_modules ] except ImportError: self.resolved_node_modules = [] raise return self.resolved_node_modules def get_message_from_call(self, *args, **kwargs): '''\ Get message object from a call. :raises: :py:exc:`TypeError` (if the format is not what we expect) This is where arguments to nodes are turned into Messages. Arguments are parsed in the following order: - A single positional argument (a :py:class:`dict`) - No positional arguments and a number of keyword arguments ''' if len(args) == 1 and isinstance(args[0], dict): # then it's a message self.logger.debug('called with arg dictionary') result = args[0] elif len(args) == 0 and kwargs != {}: # then it's a set of kwargs self.logger.debug('called with kwargs') result = kwargs else: # it's neither, and we don't handle that self.logger.error( 'get_message_from_call could not handle "%r", "%r"', args, kwargs ) raise TypeError('Pass either keyword arguments or a dictionary argument') return self.message_class(result) def register(self, name, func, fields, subscribe_to, entry_point, ignore): ''' Register a named function in the graph :param name: name to register :type name: :py:class:`str` :param func: function to remember and call :type func: callable ``fields``, ``subscribe_to`` and ``entry_point`` are the same as in :py:meth:`Router.node`. ''' self.fields[name] = fields self.functions[name] = func self.register_route(subscribe_to, name) if ignore: self.register_ignore(ignore, name) if entry_point: self.add_entry_point(name) self.logger.info('registered %s', name) def add_entry_point(self, destination): '''\ Add an entry point :param destination: node to route to initially :type destination: str ''' self.routes.setdefault('__entry_point', set()).add(destination) return self.routes['__entry_point'] def register_route(self, origins, destination): ''' Add routes to the routing dictionary :param origins: a number of origins to register :type origins: :py:class:`str` or iterable of :py:class:`str` or None :param destination: where the origins should point to :type destination: :py:class:`str` Routing dictionary takes the following form:: {'node_a': set(['node_b', 'node_c']), 'node_b': set(['node_d'])} ''' self.names.add(destination) self.logger.debug('added "%s" to names', destination) origins = origins or [] # remove None if not isinstance(origins, list): origins = [origins] self.regexes.setdefault(destination, [re.compile(origin) for origin in origins]) self.regenerate_routes() return self.regexes[destination] def register_ignore(self, origins, destination): ''' Add routes to the ignore dictionary :param origins: a number of origins to register :type origins: :py:class:`str` or iterable of :py:class:`str` :param destination: where the origins should point to :type destination: :py:class:`str` Ignore dictionary takes the following form:: {'node_a': set(['node_b', 'node_c']), 'node_b': set(['node_d'])} ''' if not isinstance(origins, list): origins = [origins] self.ignore_regexes.setdefault(destination, [re.compile(origin) for origin in origins]) self.regenerate_routes() return self.ignore_regexes[destination] def regenerate_routes(self): 'regenerate the routes after a new route is added' for destination, origins in self.regexes.items(): # we want only the names that match the destination regexes. resolved = [ name for name in self.names if name is not destination and any(origin.search(name) for origin in origins) ] ignores = self.ignore_regexes.get(destination, []) for origin in resolved: destinations = self.routes.setdefault(origin, set()) if any(ignore.search(origin) for ignore in ignores): self.logger.info('ignoring route "%s" -> "%s"', origin, destination) try: destinations.remove(destination) self.logger.debug('removed "%s" -> "%s"', origin, destination) except KeyError: pass continue if destination not in destinations: self.logger.info('added route "%s" -> "%s"', origin, destination) destinations.add(destination) def disable_routing(self): 'disable routing (usually for testing purposes)' self.routing_enabled = False def enable_routing(self): 'enable routing (after calling ``disable_routing``)' self.routing_enabled = True def route(self, origin, message): '''\ Using the routing dictionary, dispatch a message to all subscribers :param origin: name of the origin node :type origin: :py:class:`str` :param message: message to dispatch :type message: :py:class:`emit.message.Message` or subclass ''' # side-effect: we have to know all the routes before we can route. But # we can't resolve them while the object is initializing, so we have to # do it just in time to route. self.resolve_node_modules() if not self.routing_enabled: return subs = self.routes.get(origin, set()) for destination in subs: self.logger.debug('routing "%s" -> "%s"', origin, destination) self.dispatch(origin, destination, message) def dispatch(self, origin, destination, message): '''\ dispatch a message to a named function :param destination: destination to dispatch to :type destination: :py:class:`str` :param message: message to dispatch :type message: :py:class:`emit.message.Message` or subclass ''' func = self.functions[destination] self.logger.debug('calling %r directly', func) return func(_origin=origin, **message) def wrap_result(self, name, result): ''' Wrap a result from a function with it's stated fields :param name: fields to look up :type name: :py:class:`str` :param result: return value from function. Will be converted to tuple. :type result: anything :raises: :py:exc:`ValueError` if name has no associated fields :returns: :py:class:`dict` ''' if not isinstance(result, tuple): result = tuple([result]) try: return dict(zip(self.fields[name], result)) except KeyError: msg = '"%s" has no associated fields' self.logger.exception(msg, name) raise ValueError(msg % name) def get_name(self, func): ''' Get the name to reference a function by :param func: function to get the name of :type func: callable ''' if hasattr(func, 'name'): return func.name return '%s.%s' % ( func.__module__, func.__name__ )
BrianHicks/emit
emit/router/core.py
Router.resolve_node_modules
python
def resolve_node_modules(self): 'import the modules specified in init' if not self.resolved_node_modules: try: self.resolved_node_modules = [ importlib.import_module(mod, self.node_package) for mod in self.node_modules ] except ImportError: self.resolved_node_modules = [] raise return self.resolved_node_modules
import the modules specified in init
train
https://github.com/BrianHicks/emit/blob/19a86c2392b136c9e857000798ccaa525aa0ed84/emit/router/core.py#L161-L173
null
class Router(object): 'A router object. Holds routes and references to functions for dispatch' def __init__(self, message_class=None, node_modules=None, node_package=None): '''\ Create a new router object. All parameters are optional. :param message_class: wrapper class for messages passed to nodes :type message_class: :py:class:`emit.message.Message` or subclass :param node_modules: a list of modules that contain nodes :type node_modules: a list of :py:class:`str`, or ``None``. :param node_package: if any node_modules are relative, the path to base off of. :type node_package: :py:class:`str`, or ``None``. :exceptions: None :returns: None ''' self.routes = {} self.names = set() self.regexes = {} self.ignore_regexes = {} self.fields = {} self.functions = {} self.message_class = message_class or Message # manage imported packages, lazily importing before the first message # is routed. self.resolved_node_modules = [] self.node_modules = node_modules or [] self.node_package = node_package self.logger = logging.getLogger(__name__ + '.Router') self.logger.debug('Initialized Router') self.routing_enabled = True def __call__(self, **kwargs): '''\ Route a message to all nodes marked as entry points. .. note:: This function does not optionally accept a single argument (dictionary) as other points in this API do - it must be expanded to keyword arguments in this case. ''' self.logger.info('Calling entry point with %r', kwargs) self.route('__entry_point', kwargs) def wrap_as_node(self, func): 'wrap a function as a node' name = self.get_name(func) @wraps(func) def wrapped(*args, **kwargs): 'wrapped version of func' message = self.get_message_from_call(*args, **kwargs) self.logger.info('calling "%s" with %r', name, message) result = func(message) # functions can return multiple values ("emit" multiple times) # by yielding instead of returning. Handle this case by making # a list of the results and processing them all after the # generator successfully exits. If we were to process them as # they came out of the generator, we might get a partially # processed input sent down the graph. This may be possible in # the future via a flag. if isinstance(result, GeneratorType): results = [ self.wrap_result(name, item) for item in result if item is not NoResult ] self.logger.debug( '%s returned generator yielding %d items', func, len(results) ) [self.route(name, item) for item in results] return tuple(results) # the case of a direct return is simpler. wrap, route, and # return the value. else: if result is NoResult: return result result = self.wrap_result(name, result) self.logger.debug( '%s returned single value %s', func, result ) self.route(name, result) return result return wrapped def node(self, fields, subscribe_to=None, entry_point=False, ignore=None, **wrapper_options): '''\ Decorate a function to make it a node. .. note:: decorating as a node changes the function signature. Nodes should accept a single argument, which will be a :py:class:`emit.message.Message`. Nodes can be called directly by providing a dictionary argument or a set of keyword arguments. Other uses will raise a ``TypeError``. :param fields: fields that this function returns :type fields: ordered iterable of :py:class:`str` :param subscribe_to: functions in the graph to subscribe to. These indicators can be regular expressions. :type subscribe_to: :py:class:`str` or iterable of :py:class:`str` :param ignore: functions in the graph to ignore (also uses regular expressions.) Useful for ignoring specific functions in a broad regex. :type ignore: :py:class:`str` or iterable of :py:class:`str` :param entry_point: Set to ``True`` to mark this as an entry point - that is, this function will be called when the router is called directly. :type entry_point: :py:class:`bool` In addition to all of the above, you can define a ``wrap_node`` function on a subclass of Router, which will need to receive node and an options dictionary. Any extra options passed to node will be passed down to the options dictionary. See :py:class:`emit.router.CeleryRouter.wrap_node` as an example. :returns: decorated and wrapped function, or decorator if called directly ''' def outer(func): 'outer level function' # create a wrapper function self.logger.debug('wrapping %s', func) wrapped = self.wrap_as_node(func) if hasattr(self, 'wrap_node'): self.logger.debug('wrapping node "%s" in custom wrapper', wrapped) wrapped = self.wrap_node(wrapped, wrapper_options) # register the task in the graph name = self.get_name(func) self.register( name, wrapped, fields, subscribe_to, entry_point, ignore ) return wrapped return outer def get_message_from_call(self, *args, **kwargs): '''\ Get message object from a call. :raises: :py:exc:`TypeError` (if the format is not what we expect) This is where arguments to nodes are turned into Messages. Arguments are parsed in the following order: - A single positional argument (a :py:class:`dict`) - No positional arguments and a number of keyword arguments ''' if len(args) == 1 and isinstance(args[0], dict): # then it's a message self.logger.debug('called with arg dictionary') result = args[0] elif len(args) == 0 and kwargs != {}: # then it's a set of kwargs self.logger.debug('called with kwargs') result = kwargs else: # it's neither, and we don't handle that self.logger.error( 'get_message_from_call could not handle "%r", "%r"', args, kwargs ) raise TypeError('Pass either keyword arguments or a dictionary argument') return self.message_class(result) def register(self, name, func, fields, subscribe_to, entry_point, ignore): ''' Register a named function in the graph :param name: name to register :type name: :py:class:`str` :param func: function to remember and call :type func: callable ``fields``, ``subscribe_to`` and ``entry_point`` are the same as in :py:meth:`Router.node`. ''' self.fields[name] = fields self.functions[name] = func self.register_route(subscribe_to, name) if ignore: self.register_ignore(ignore, name) if entry_point: self.add_entry_point(name) self.logger.info('registered %s', name) def add_entry_point(self, destination): '''\ Add an entry point :param destination: node to route to initially :type destination: str ''' self.routes.setdefault('__entry_point', set()).add(destination) return self.routes['__entry_point'] def register_route(self, origins, destination): ''' Add routes to the routing dictionary :param origins: a number of origins to register :type origins: :py:class:`str` or iterable of :py:class:`str` or None :param destination: where the origins should point to :type destination: :py:class:`str` Routing dictionary takes the following form:: {'node_a': set(['node_b', 'node_c']), 'node_b': set(['node_d'])} ''' self.names.add(destination) self.logger.debug('added "%s" to names', destination) origins = origins or [] # remove None if not isinstance(origins, list): origins = [origins] self.regexes.setdefault(destination, [re.compile(origin) for origin in origins]) self.regenerate_routes() return self.regexes[destination] def register_ignore(self, origins, destination): ''' Add routes to the ignore dictionary :param origins: a number of origins to register :type origins: :py:class:`str` or iterable of :py:class:`str` :param destination: where the origins should point to :type destination: :py:class:`str` Ignore dictionary takes the following form:: {'node_a': set(['node_b', 'node_c']), 'node_b': set(['node_d'])} ''' if not isinstance(origins, list): origins = [origins] self.ignore_regexes.setdefault(destination, [re.compile(origin) for origin in origins]) self.regenerate_routes() return self.ignore_regexes[destination] def regenerate_routes(self): 'regenerate the routes after a new route is added' for destination, origins in self.regexes.items(): # we want only the names that match the destination regexes. resolved = [ name for name in self.names if name is not destination and any(origin.search(name) for origin in origins) ] ignores = self.ignore_regexes.get(destination, []) for origin in resolved: destinations = self.routes.setdefault(origin, set()) if any(ignore.search(origin) for ignore in ignores): self.logger.info('ignoring route "%s" -> "%s"', origin, destination) try: destinations.remove(destination) self.logger.debug('removed "%s" -> "%s"', origin, destination) except KeyError: pass continue if destination not in destinations: self.logger.info('added route "%s" -> "%s"', origin, destination) destinations.add(destination) def disable_routing(self): 'disable routing (usually for testing purposes)' self.routing_enabled = False def enable_routing(self): 'enable routing (after calling ``disable_routing``)' self.routing_enabled = True def route(self, origin, message): '''\ Using the routing dictionary, dispatch a message to all subscribers :param origin: name of the origin node :type origin: :py:class:`str` :param message: message to dispatch :type message: :py:class:`emit.message.Message` or subclass ''' # side-effect: we have to know all the routes before we can route. But # we can't resolve them while the object is initializing, so we have to # do it just in time to route. self.resolve_node_modules() if not self.routing_enabled: return subs = self.routes.get(origin, set()) for destination in subs: self.logger.debug('routing "%s" -> "%s"', origin, destination) self.dispatch(origin, destination, message) def dispatch(self, origin, destination, message): '''\ dispatch a message to a named function :param destination: destination to dispatch to :type destination: :py:class:`str` :param message: message to dispatch :type message: :py:class:`emit.message.Message` or subclass ''' func = self.functions[destination] self.logger.debug('calling %r directly', func) return func(_origin=origin, **message) def wrap_result(self, name, result): ''' Wrap a result from a function with it's stated fields :param name: fields to look up :type name: :py:class:`str` :param result: return value from function. Will be converted to tuple. :type result: anything :raises: :py:exc:`ValueError` if name has no associated fields :returns: :py:class:`dict` ''' if not isinstance(result, tuple): result = tuple([result]) try: return dict(zip(self.fields[name], result)) except KeyError: msg = '"%s" has no associated fields' self.logger.exception(msg, name) raise ValueError(msg % name) def get_name(self, func): ''' Get the name to reference a function by :param func: function to get the name of :type func: callable ''' if hasattr(func, 'name'): return func.name return '%s.%s' % ( func.__module__, func.__name__ )
BrianHicks/emit
emit/router/core.py
Router.get_message_from_call
python
def get_message_from_call(self, *args, **kwargs): '''\ Get message object from a call. :raises: :py:exc:`TypeError` (if the format is not what we expect) This is where arguments to nodes are turned into Messages. Arguments are parsed in the following order: - A single positional argument (a :py:class:`dict`) - No positional arguments and a number of keyword arguments ''' if len(args) == 1 and isinstance(args[0], dict): # then it's a message self.logger.debug('called with arg dictionary') result = args[0] elif len(args) == 0 and kwargs != {}: # then it's a set of kwargs self.logger.debug('called with kwargs') result = kwargs else: # it's neither, and we don't handle that self.logger.error( 'get_message_from_call could not handle "%r", "%r"', args, kwargs ) raise TypeError('Pass either keyword arguments or a dictionary argument') return self.message_class(result)
\ Get message object from a call. :raises: :py:exc:`TypeError` (if the format is not what we expect) This is where arguments to nodes are turned into Messages. Arguments are parsed in the following order: - A single positional argument (a :py:class:`dict`) - No positional arguments and a number of keyword arguments
train
https://github.com/BrianHicks/emit/blob/19a86c2392b136c9e857000798ccaa525aa0ed84/emit/router/core.py#L175-L203
null
class Router(object): 'A router object. Holds routes and references to functions for dispatch' def __init__(self, message_class=None, node_modules=None, node_package=None): '''\ Create a new router object. All parameters are optional. :param message_class: wrapper class for messages passed to nodes :type message_class: :py:class:`emit.message.Message` or subclass :param node_modules: a list of modules that contain nodes :type node_modules: a list of :py:class:`str`, or ``None``. :param node_package: if any node_modules are relative, the path to base off of. :type node_package: :py:class:`str`, or ``None``. :exceptions: None :returns: None ''' self.routes = {} self.names = set() self.regexes = {} self.ignore_regexes = {} self.fields = {} self.functions = {} self.message_class = message_class or Message # manage imported packages, lazily importing before the first message # is routed. self.resolved_node_modules = [] self.node_modules = node_modules or [] self.node_package = node_package self.logger = logging.getLogger(__name__ + '.Router') self.logger.debug('Initialized Router') self.routing_enabled = True def __call__(self, **kwargs): '''\ Route a message to all nodes marked as entry points. .. note:: This function does not optionally accept a single argument (dictionary) as other points in this API do - it must be expanded to keyword arguments in this case. ''' self.logger.info('Calling entry point with %r', kwargs) self.route('__entry_point', kwargs) def wrap_as_node(self, func): 'wrap a function as a node' name = self.get_name(func) @wraps(func) def wrapped(*args, **kwargs): 'wrapped version of func' message = self.get_message_from_call(*args, **kwargs) self.logger.info('calling "%s" with %r', name, message) result = func(message) # functions can return multiple values ("emit" multiple times) # by yielding instead of returning. Handle this case by making # a list of the results and processing them all after the # generator successfully exits. If we were to process them as # they came out of the generator, we might get a partially # processed input sent down the graph. This may be possible in # the future via a flag. if isinstance(result, GeneratorType): results = [ self.wrap_result(name, item) for item in result if item is not NoResult ] self.logger.debug( '%s returned generator yielding %d items', func, len(results) ) [self.route(name, item) for item in results] return tuple(results) # the case of a direct return is simpler. wrap, route, and # return the value. else: if result is NoResult: return result result = self.wrap_result(name, result) self.logger.debug( '%s returned single value %s', func, result ) self.route(name, result) return result return wrapped def node(self, fields, subscribe_to=None, entry_point=False, ignore=None, **wrapper_options): '''\ Decorate a function to make it a node. .. note:: decorating as a node changes the function signature. Nodes should accept a single argument, which will be a :py:class:`emit.message.Message`. Nodes can be called directly by providing a dictionary argument or a set of keyword arguments. Other uses will raise a ``TypeError``. :param fields: fields that this function returns :type fields: ordered iterable of :py:class:`str` :param subscribe_to: functions in the graph to subscribe to. These indicators can be regular expressions. :type subscribe_to: :py:class:`str` or iterable of :py:class:`str` :param ignore: functions in the graph to ignore (also uses regular expressions.) Useful for ignoring specific functions in a broad regex. :type ignore: :py:class:`str` or iterable of :py:class:`str` :param entry_point: Set to ``True`` to mark this as an entry point - that is, this function will be called when the router is called directly. :type entry_point: :py:class:`bool` In addition to all of the above, you can define a ``wrap_node`` function on a subclass of Router, which will need to receive node and an options dictionary. Any extra options passed to node will be passed down to the options dictionary. See :py:class:`emit.router.CeleryRouter.wrap_node` as an example. :returns: decorated and wrapped function, or decorator if called directly ''' def outer(func): 'outer level function' # create a wrapper function self.logger.debug('wrapping %s', func) wrapped = self.wrap_as_node(func) if hasattr(self, 'wrap_node'): self.logger.debug('wrapping node "%s" in custom wrapper', wrapped) wrapped = self.wrap_node(wrapped, wrapper_options) # register the task in the graph name = self.get_name(func) self.register( name, wrapped, fields, subscribe_to, entry_point, ignore ) return wrapped return outer def resolve_node_modules(self): 'import the modules specified in init' if not self.resolved_node_modules: try: self.resolved_node_modules = [ importlib.import_module(mod, self.node_package) for mod in self.node_modules ] except ImportError: self.resolved_node_modules = [] raise return self.resolved_node_modules def register(self, name, func, fields, subscribe_to, entry_point, ignore): ''' Register a named function in the graph :param name: name to register :type name: :py:class:`str` :param func: function to remember and call :type func: callable ``fields``, ``subscribe_to`` and ``entry_point`` are the same as in :py:meth:`Router.node`. ''' self.fields[name] = fields self.functions[name] = func self.register_route(subscribe_to, name) if ignore: self.register_ignore(ignore, name) if entry_point: self.add_entry_point(name) self.logger.info('registered %s', name) def add_entry_point(self, destination): '''\ Add an entry point :param destination: node to route to initially :type destination: str ''' self.routes.setdefault('__entry_point', set()).add(destination) return self.routes['__entry_point'] def register_route(self, origins, destination): ''' Add routes to the routing dictionary :param origins: a number of origins to register :type origins: :py:class:`str` or iterable of :py:class:`str` or None :param destination: where the origins should point to :type destination: :py:class:`str` Routing dictionary takes the following form:: {'node_a': set(['node_b', 'node_c']), 'node_b': set(['node_d'])} ''' self.names.add(destination) self.logger.debug('added "%s" to names', destination) origins = origins or [] # remove None if not isinstance(origins, list): origins = [origins] self.regexes.setdefault(destination, [re.compile(origin) for origin in origins]) self.regenerate_routes() return self.regexes[destination] def register_ignore(self, origins, destination): ''' Add routes to the ignore dictionary :param origins: a number of origins to register :type origins: :py:class:`str` or iterable of :py:class:`str` :param destination: where the origins should point to :type destination: :py:class:`str` Ignore dictionary takes the following form:: {'node_a': set(['node_b', 'node_c']), 'node_b': set(['node_d'])} ''' if not isinstance(origins, list): origins = [origins] self.ignore_regexes.setdefault(destination, [re.compile(origin) for origin in origins]) self.regenerate_routes() return self.ignore_regexes[destination] def regenerate_routes(self): 'regenerate the routes after a new route is added' for destination, origins in self.regexes.items(): # we want only the names that match the destination regexes. resolved = [ name for name in self.names if name is not destination and any(origin.search(name) for origin in origins) ] ignores = self.ignore_regexes.get(destination, []) for origin in resolved: destinations = self.routes.setdefault(origin, set()) if any(ignore.search(origin) for ignore in ignores): self.logger.info('ignoring route "%s" -> "%s"', origin, destination) try: destinations.remove(destination) self.logger.debug('removed "%s" -> "%s"', origin, destination) except KeyError: pass continue if destination not in destinations: self.logger.info('added route "%s" -> "%s"', origin, destination) destinations.add(destination) def disable_routing(self): 'disable routing (usually for testing purposes)' self.routing_enabled = False def enable_routing(self): 'enable routing (after calling ``disable_routing``)' self.routing_enabled = True def route(self, origin, message): '''\ Using the routing dictionary, dispatch a message to all subscribers :param origin: name of the origin node :type origin: :py:class:`str` :param message: message to dispatch :type message: :py:class:`emit.message.Message` or subclass ''' # side-effect: we have to know all the routes before we can route. But # we can't resolve them while the object is initializing, so we have to # do it just in time to route. self.resolve_node_modules() if not self.routing_enabled: return subs = self.routes.get(origin, set()) for destination in subs: self.logger.debug('routing "%s" -> "%s"', origin, destination) self.dispatch(origin, destination, message) def dispatch(self, origin, destination, message): '''\ dispatch a message to a named function :param destination: destination to dispatch to :type destination: :py:class:`str` :param message: message to dispatch :type message: :py:class:`emit.message.Message` or subclass ''' func = self.functions[destination] self.logger.debug('calling %r directly', func) return func(_origin=origin, **message) def wrap_result(self, name, result): ''' Wrap a result from a function with it's stated fields :param name: fields to look up :type name: :py:class:`str` :param result: return value from function. Will be converted to tuple. :type result: anything :raises: :py:exc:`ValueError` if name has no associated fields :returns: :py:class:`dict` ''' if not isinstance(result, tuple): result = tuple([result]) try: return dict(zip(self.fields[name], result)) except KeyError: msg = '"%s" has no associated fields' self.logger.exception(msg, name) raise ValueError(msg % name) def get_name(self, func): ''' Get the name to reference a function by :param func: function to get the name of :type func: callable ''' if hasattr(func, 'name'): return func.name return '%s.%s' % ( func.__module__, func.__name__ )
BrianHicks/emit
emit/router/core.py
Router.register
python
def register(self, name, func, fields, subscribe_to, entry_point, ignore): ''' Register a named function in the graph :param name: name to register :type name: :py:class:`str` :param func: function to remember and call :type func: callable ``fields``, ``subscribe_to`` and ``entry_point`` are the same as in :py:meth:`Router.node`. ''' self.fields[name] = fields self.functions[name] = func self.register_route(subscribe_to, name) if ignore: self.register_ignore(ignore, name) if entry_point: self.add_entry_point(name) self.logger.info('registered %s', name)
Register a named function in the graph :param name: name to register :type name: :py:class:`str` :param func: function to remember and call :type func: callable ``fields``, ``subscribe_to`` and ``entry_point`` are the same as in :py:meth:`Router.node`.
train
https://github.com/BrianHicks/emit/blob/19a86c2392b136c9e857000798ccaa525aa0ed84/emit/router/core.py#L205-L228
[ "def add_entry_point(self, destination):\n '''\\\n Add an entry point\n\n :param destination: node to route to initially\n :type destination: str\n '''\n self.routes.setdefault('__entry_point', set()).add(destination)\n return self.routes['__entry_point']\n", "def register_route(self, origins, destination):\n '''\n Add routes to the routing dictionary\n\n :param origins: a number of origins to register\n :type origins: :py:class:`str` or iterable of :py:class:`str` or None\n :param destination: where the origins should point to\n :type destination: :py:class:`str`\n\n Routing dictionary takes the following form::\n\n {'node_a': set(['node_b', 'node_c']),\n 'node_b': set(['node_d'])}\n\n '''\n self.names.add(destination)\n self.logger.debug('added \"%s\" to names', destination)\n\n origins = origins or [] # remove None\n if not isinstance(origins, list):\n origins = [origins]\n\n self.regexes.setdefault(destination, [re.compile(origin) for origin in origins])\n\n self.regenerate_routes()\n return self.regexes[destination]\n", "def register_ignore(self, origins, destination):\n '''\n Add routes to the ignore dictionary\n\n :param origins: a number of origins to register\n :type origins: :py:class:`str` or iterable of :py:class:`str`\n :param destination: where the origins should point to\n :type destination: :py:class:`str`\n\n Ignore dictionary takes the following form::\n\n {'node_a': set(['node_b', 'node_c']),\n 'node_b': set(['node_d'])}\n\n '''\n if not isinstance(origins, list):\n origins = [origins]\n\n self.ignore_regexes.setdefault(destination, [re.compile(origin) for origin in origins])\n self.regenerate_routes()\n\n return self.ignore_regexes[destination]\n" ]
class Router(object): 'A router object. Holds routes and references to functions for dispatch' def __init__(self, message_class=None, node_modules=None, node_package=None): '''\ Create a new router object. All parameters are optional. :param message_class: wrapper class for messages passed to nodes :type message_class: :py:class:`emit.message.Message` or subclass :param node_modules: a list of modules that contain nodes :type node_modules: a list of :py:class:`str`, or ``None``. :param node_package: if any node_modules are relative, the path to base off of. :type node_package: :py:class:`str`, or ``None``. :exceptions: None :returns: None ''' self.routes = {} self.names = set() self.regexes = {} self.ignore_regexes = {} self.fields = {} self.functions = {} self.message_class = message_class or Message # manage imported packages, lazily importing before the first message # is routed. self.resolved_node_modules = [] self.node_modules = node_modules or [] self.node_package = node_package self.logger = logging.getLogger(__name__ + '.Router') self.logger.debug('Initialized Router') self.routing_enabled = True def __call__(self, **kwargs): '''\ Route a message to all nodes marked as entry points. .. note:: This function does not optionally accept a single argument (dictionary) as other points in this API do - it must be expanded to keyword arguments in this case. ''' self.logger.info('Calling entry point with %r', kwargs) self.route('__entry_point', kwargs) def wrap_as_node(self, func): 'wrap a function as a node' name = self.get_name(func) @wraps(func) def wrapped(*args, **kwargs): 'wrapped version of func' message = self.get_message_from_call(*args, **kwargs) self.logger.info('calling "%s" with %r', name, message) result = func(message) # functions can return multiple values ("emit" multiple times) # by yielding instead of returning. Handle this case by making # a list of the results and processing them all after the # generator successfully exits. If we were to process them as # they came out of the generator, we might get a partially # processed input sent down the graph. This may be possible in # the future via a flag. if isinstance(result, GeneratorType): results = [ self.wrap_result(name, item) for item in result if item is not NoResult ] self.logger.debug( '%s returned generator yielding %d items', func, len(results) ) [self.route(name, item) for item in results] return tuple(results) # the case of a direct return is simpler. wrap, route, and # return the value. else: if result is NoResult: return result result = self.wrap_result(name, result) self.logger.debug( '%s returned single value %s', func, result ) self.route(name, result) return result return wrapped def node(self, fields, subscribe_to=None, entry_point=False, ignore=None, **wrapper_options): '''\ Decorate a function to make it a node. .. note:: decorating as a node changes the function signature. Nodes should accept a single argument, which will be a :py:class:`emit.message.Message`. Nodes can be called directly by providing a dictionary argument or a set of keyword arguments. Other uses will raise a ``TypeError``. :param fields: fields that this function returns :type fields: ordered iterable of :py:class:`str` :param subscribe_to: functions in the graph to subscribe to. These indicators can be regular expressions. :type subscribe_to: :py:class:`str` or iterable of :py:class:`str` :param ignore: functions in the graph to ignore (also uses regular expressions.) Useful for ignoring specific functions in a broad regex. :type ignore: :py:class:`str` or iterable of :py:class:`str` :param entry_point: Set to ``True`` to mark this as an entry point - that is, this function will be called when the router is called directly. :type entry_point: :py:class:`bool` In addition to all of the above, you can define a ``wrap_node`` function on a subclass of Router, which will need to receive node and an options dictionary. Any extra options passed to node will be passed down to the options dictionary. See :py:class:`emit.router.CeleryRouter.wrap_node` as an example. :returns: decorated and wrapped function, or decorator if called directly ''' def outer(func): 'outer level function' # create a wrapper function self.logger.debug('wrapping %s', func) wrapped = self.wrap_as_node(func) if hasattr(self, 'wrap_node'): self.logger.debug('wrapping node "%s" in custom wrapper', wrapped) wrapped = self.wrap_node(wrapped, wrapper_options) # register the task in the graph name = self.get_name(func) self.register( name, wrapped, fields, subscribe_to, entry_point, ignore ) return wrapped return outer def resolve_node_modules(self): 'import the modules specified in init' if not self.resolved_node_modules: try: self.resolved_node_modules = [ importlib.import_module(mod, self.node_package) for mod in self.node_modules ] except ImportError: self.resolved_node_modules = [] raise return self.resolved_node_modules def get_message_from_call(self, *args, **kwargs): '''\ Get message object from a call. :raises: :py:exc:`TypeError` (if the format is not what we expect) This is where arguments to nodes are turned into Messages. Arguments are parsed in the following order: - A single positional argument (a :py:class:`dict`) - No positional arguments and a number of keyword arguments ''' if len(args) == 1 and isinstance(args[0], dict): # then it's a message self.logger.debug('called with arg dictionary') result = args[0] elif len(args) == 0 and kwargs != {}: # then it's a set of kwargs self.logger.debug('called with kwargs') result = kwargs else: # it's neither, and we don't handle that self.logger.error( 'get_message_from_call could not handle "%r", "%r"', args, kwargs ) raise TypeError('Pass either keyword arguments or a dictionary argument') return self.message_class(result) def add_entry_point(self, destination): '''\ Add an entry point :param destination: node to route to initially :type destination: str ''' self.routes.setdefault('__entry_point', set()).add(destination) return self.routes['__entry_point'] def register_route(self, origins, destination): ''' Add routes to the routing dictionary :param origins: a number of origins to register :type origins: :py:class:`str` or iterable of :py:class:`str` or None :param destination: where the origins should point to :type destination: :py:class:`str` Routing dictionary takes the following form:: {'node_a': set(['node_b', 'node_c']), 'node_b': set(['node_d'])} ''' self.names.add(destination) self.logger.debug('added "%s" to names', destination) origins = origins or [] # remove None if not isinstance(origins, list): origins = [origins] self.regexes.setdefault(destination, [re.compile(origin) for origin in origins]) self.regenerate_routes() return self.regexes[destination] def register_ignore(self, origins, destination): ''' Add routes to the ignore dictionary :param origins: a number of origins to register :type origins: :py:class:`str` or iterable of :py:class:`str` :param destination: where the origins should point to :type destination: :py:class:`str` Ignore dictionary takes the following form:: {'node_a': set(['node_b', 'node_c']), 'node_b': set(['node_d'])} ''' if not isinstance(origins, list): origins = [origins] self.ignore_regexes.setdefault(destination, [re.compile(origin) for origin in origins]) self.regenerate_routes() return self.ignore_regexes[destination] def regenerate_routes(self): 'regenerate the routes after a new route is added' for destination, origins in self.regexes.items(): # we want only the names that match the destination regexes. resolved = [ name for name in self.names if name is not destination and any(origin.search(name) for origin in origins) ] ignores = self.ignore_regexes.get(destination, []) for origin in resolved: destinations = self.routes.setdefault(origin, set()) if any(ignore.search(origin) for ignore in ignores): self.logger.info('ignoring route "%s" -> "%s"', origin, destination) try: destinations.remove(destination) self.logger.debug('removed "%s" -> "%s"', origin, destination) except KeyError: pass continue if destination not in destinations: self.logger.info('added route "%s" -> "%s"', origin, destination) destinations.add(destination) def disable_routing(self): 'disable routing (usually for testing purposes)' self.routing_enabled = False def enable_routing(self): 'enable routing (after calling ``disable_routing``)' self.routing_enabled = True def route(self, origin, message): '''\ Using the routing dictionary, dispatch a message to all subscribers :param origin: name of the origin node :type origin: :py:class:`str` :param message: message to dispatch :type message: :py:class:`emit.message.Message` or subclass ''' # side-effect: we have to know all the routes before we can route. But # we can't resolve them while the object is initializing, so we have to # do it just in time to route. self.resolve_node_modules() if not self.routing_enabled: return subs = self.routes.get(origin, set()) for destination in subs: self.logger.debug('routing "%s" -> "%s"', origin, destination) self.dispatch(origin, destination, message) def dispatch(self, origin, destination, message): '''\ dispatch a message to a named function :param destination: destination to dispatch to :type destination: :py:class:`str` :param message: message to dispatch :type message: :py:class:`emit.message.Message` or subclass ''' func = self.functions[destination] self.logger.debug('calling %r directly', func) return func(_origin=origin, **message) def wrap_result(self, name, result): ''' Wrap a result from a function with it's stated fields :param name: fields to look up :type name: :py:class:`str` :param result: return value from function. Will be converted to tuple. :type result: anything :raises: :py:exc:`ValueError` if name has no associated fields :returns: :py:class:`dict` ''' if not isinstance(result, tuple): result = tuple([result]) try: return dict(zip(self.fields[name], result)) except KeyError: msg = '"%s" has no associated fields' self.logger.exception(msg, name) raise ValueError(msg % name) def get_name(self, func): ''' Get the name to reference a function by :param func: function to get the name of :type func: callable ''' if hasattr(func, 'name'): return func.name return '%s.%s' % ( func.__module__, func.__name__ )
BrianHicks/emit
emit/router/core.py
Router.add_entry_point
python
def add_entry_point(self, destination): '''\ Add an entry point :param destination: node to route to initially :type destination: str ''' self.routes.setdefault('__entry_point', set()).add(destination) return self.routes['__entry_point']
\ Add an entry point :param destination: node to route to initially :type destination: str
train
https://github.com/BrianHicks/emit/blob/19a86c2392b136c9e857000798ccaa525aa0ed84/emit/router/core.py#L230-L238
null
class Router(object): 'A router object. Holds routes and references to functions for dispatch' def __init__(self, message_class=None, node_modules=None, node_package=None): '''\ Create a new router object. All parameters are optional. :param message_class: wrapper class for messages passed to nodes :type message_class: :py:class:`emit.message.Message` or subclass :param node_modules: a list of modules that contain nodes :type node_modules: a list of :py:class:`str`, or ``None``. :param node_package: if any node_modules are relative, the path to base off of. :type node_package: :py:class:`str`, or ``None``. :exceptions: None :returns: None ''' self.routes = {} self.names = set() self.regexes = {} self.ignore_regexes = {} self.fields = {} self.functions = {} self.message_class = message_class or Message # manage imported packages, lazily importing before the first message # is routed. self.resolved_node_modules = [] self.node_modules = node_modules or [] self.node_package = node_package self.logger = logging.getLogger(__name__ + '.Router') self.logger.debug('Initialized Router') self.routing_enabled = True def __call__(self, **kwargs): '''\ Route a message to all nodes marked as entry points. .. note:: This function does not optionally accept a single argument (dictionary) as other points in this API do - it must be expanded to keyword arguments in this case. ''' self.logger.info('Calling entry point with %r', kwargs) self.route('__entry_point', kwargs) def wrap_as_node(self, func): 'wrap a function as a node' name = self.get_name(func) @wraps(func) def wrapped(*args, **kwargs): 'wrapped version of func' message = self.get_message_from_call(*args, **kwargs) self.logger.info('calling "%s" with %r', name, message) result = func(message) # functions can return multiple values ("emit" multiple times) # by yielding instead of returning. Handle this case by making # a list of the results and processing them all after the # generator successfully exits. If we were to process them as # they came out of the generator, we might get a partially # processed input sent down the graph. This may be possible in # the future via a flag. if isinstance(result, GeneratorType): results = [ self.wrap_result(name, item) for item in result if item is not NoResult ] self.logger.debug( '%s returned generator yielding %d items', func, len(results) ) [self.route(name, item) for item in results] return tuple(results) # the case of a direct return is simpler. wrap, route, and # return the value. else: if result is NoResult: return result result = self.wrap_result(name, result) self.logger.debug( '%s returned single value %s', func, result ) self.route(name, result) return result return wrapped def node(self, fields, subscribe_to=None, entry_point=False, ignore=None, **wrapper_options): '''\ Decorate a function to make it a node. .. note:: decorating as a node changes the function signature. Nodes should accept a single argument, which will be a :py:class:`emit.message.Message`. Nodes can be called directly by providing a dictionary argument or a set of keyword arguments. Other uses will raise a ``TypeError``. :param fields: fields that this function returns :type fields: ordered iterable of :py:class:`str` :param subscribe_to: functions in the graph to subscribe to. These indicators can be regular expressions. :type subscribe_to: :py:class:`str` or iterable of :py:class:`str` :param ignore: functions in the graph to ignore (also uses regular expressions.) Useful for ignoring specific functions in a broad regex. :type ignore: :py:class:`str` or iterable of :py:class:`str` :param entry_point: Set to ``True`` to mark this as an entry point - that is, this function will be called when the router is called directly. :type entry_point: :py:class:`bool` In addition to all of the above, you can define a ``wrap_node`` function on a subclass of Router, which will need to receive node and an options dictionary. Any extra options passed to node will be passed down to the options dictionary. See :py:class:`emit.router.CeleryRouter.wrap_node` as an example. :returns: decorated and wrapped function, or decorator if called directly ''' def outer(func): 'outer level function' # create a wrapper function self.logger.debug('wrapping %s', func) wrapped = self.wrap_as_node(func) if hasattr(self, 'wrap_node'): self.logger.debug('wrapping node "%s" in custom wrapper', wrapped) wrapped = self.wrap_node(wrapped, wrapper_options) # register the task in the graph name = self.get_name(func) self.register( name, wrapped, fields, subscribe_to, entry_point, ignore ) return wrapped return outer def resolve_node_modules(self): 'import the modules specified in init' if not self.resolved_node_modules: try: self.resolved_node_modules = [ importlib.import_module(mod, self.node_package) for mod in self.node_modules ] except ImportError: self.resolved_node_modules = [] raise return self.resolved_node_modules def get_message_from_call(self, *args, **kwargs): '''\ Get message object from a call. :raises: :py:exc:`TypeError` (if the format is not what we expect) This is where arguments to nodes are turned into Messages. Arguments are parsed in the following order: - A single positional argument (a :py:class:`dict`) - No positional arguments and a number of keyword arguments ''' if len(args) == 1 and isinstance(args[0], dict): # then it's a message self.logger.debug('called with arg dictionary') result = args[0] elif len(args) == 0 and kwargs != {}: # then it's a set of kwargs self.logger.debug('called with kwargs') result = kwargs else: # it's neither, and we don't handle that self.logger.error( 'get_message_from_call could not handle "%r", "%r"', args, kwargs ) raise TypeError('Pass either keyword arguments or a dictionary argument') return self.message_class(result) def register(self, name, func, fields, subscribe_to, entry_point, ignore): ''' Register a named function in the graph :param name: name to register :type name: :py:class:`str` :param func: function to remember and call :type func: callable ``fields``, ``subscribe_to`` and ``entry_point`` are the same as in :py:meth:`Router.node`. ''' self.fields[name] = fields self.functions[name] = func self.register_route(subscribe_to, name) if ignore: self.register_ignore(ignore, name) if entry_point: self.add_entry_point(name) self.logger.info('registered %s', name) def register_route(self, origins, destination): ''' Add routes to the routing dictionary :param origins: a number of origins to register :type origins: :py:class:`str` or iterable of :py:class:`str` or None :param destination: where the origins should point to :type destination: :py:class:`str` Routing dictionary takes the following form:: {'node_a': set(['node_b', 'node_c']), 'node_b': set(['node_d'])} ''' self.names.add(destination) self.logger.debug('added "%s" to names', destination) origins = origins or [] # remove None if not isinstance(origins, list): origins = [origins] self.regexes.setdefault(destination, [re.compile(origin) for origin in origins]) self.regenerate_routes() return self.regexes[destination] def register_ignore(self, origins, destination): ''' Add routes to the ignore dictionary :param origins: a number of origins to register :type origins: :py:class:`str` or iterable of :py:class:`str` :param destination: where the origins should point to :type destination: :py:class:`str` Ignore dictionary takes the following form:: {'node_a': set(['node_b', 'node_c']), 'node_b': set(['node_d'])} ''' if not isinstance(origins, list): origins = [origins] self.ignore_regexes.setdefault(destination, [re.compile(origin) for origin in origins]) self.regenerate_routes() return self.ignore_regexes[destination] def regenerate_routes(self): 'regenerate the routes after a new route is added' for destination, origins in self.regexes.items(): # we want only the names that match the destination regexes. resolved = [ name for name in self.names if name is not destination and any(origin.search(name) for origin in origins) ] ignores = self.ignore_regexes.get(destination, []) for origin in resolved: destinations = self.routes.setdefault(origin, set()) if any(ignore.search(origin) for ignore in ignores): self.logger.info('ignoring route "%s" -> "%s"', origin, destination) try: destinations.remove(destination) self.logger.debug('removed "%s" -> "%s"', origin, destination) except KeyError: pass continue if destination not in destinations: self.logger.info('added route "%s" -> "%s"', origin, destination) destinations.add(destination) def disable_routing(self): 'disable routing (usually for testing purposes)' self.routing_enabled = False def enable_routing(self): 'enable routing (after calling ``disable_routing``)' self.routing_enabled = True def route(self, origin, message): '''\ Using the routing dictionary, dispatch a message to all subscribers :param origin: name of the origin node :type origin: :py:class:`str` :param message: message to dispatch :type message: :py:class:`emit.message.Message` or subclass ''' # side-effect: we have to know all the routes before we can route. But # we can't resolve them while the object is initializing, so we have to # do it just in time to route. self.resolve_node_modules() if not self.routing_enabled: return subs = self.routes.get(origin, set()) for destination in subs: self.logger.debug('routing "%s" -> "%s"', origin, destination) self.dispatch(origin, destination, message) def dispatch(self, origin, destination, message): '''\ dispatch a message to a named function :param destination: destination to dispatch to :type destination: :py:class:`str` :param message: message to dispatch :type message: :py:class:`emit.message.Message` or subclass ''' func = self.functions[destination] self.logger.debug('calling %r directly', func) return func(_origin=origin, **message) def wrap_result(self, name, result): ''' Wrap a result from a function with it's stated fields :param name: fields to look up :type name: :py:class:`str` :param result: return value from function. Will be converted to tuple. :type result: anything :raises: :py:exc:`ValueError` if name has no associated fields :returns: :py:class:`dict` ''' if not isinstance(result, tuple): result = tuple([result]) try: return dict(zip(self.fields[name], result)) except KeyError: msg = '"%s" has no associated fields' self.logger.exception(msg, name) raise ValueError(msg % name) def get_name(self, func): ''' Get the name to reference a function by :param func: function to get the name of :type func: callable ''' if hasattr(func, 'name'): return func.name return '%s.%s' % ( func.__module__, func.__name__ )
BrianHicks/emit
emit/router/core.py
Router.register_route
python
def register_route(self, origins, destination): ''' Add routes to the routing dictionary :param origins: a number of origins to register :type origins: :py:class:`str` or iterable of :py:class:`str` or None :param destination: where the origins should point to :type destination: :py:class:`str` Routing dictionary takes the following form:: {'node_a': set(['node_b', 'node_c']), 'node_b': set(['node_d'])} ''' self.names.add(destination) self.logger.debug('added "%s" to names', destination) origins = origins or [] # remove None if not isinstance(origins, list): origins = [origins] self.regexes.setdefault(destination, [re.compile(origin) for origin in origins]) self.regenerate_routes() return self.regexes[destination]
Add routes to the routing dictionary :param origins: a number of origins to register :type origins: :py:class:`str` or iterable of :py:class:`str` or None :param destination: where the origins should point to :type destination: :py:class:`str` Routing dictionary takes the following form:: {'node_a': set(['node_b', 'node_c']), 'node_b': set(['node_d'])}
train
https://github.com/BrianHicks/emit/blob/19a86c2392b136c9e857000798ccaa525aa0ed84/emit/router/core.py#L240-L265
[ "def regenerate_routes(self):\n 'regenerate the routes after a new route is added'\n for destination, origins in self.regexes.items():\n # we want only the names that match the destination regexes.\n resolved = [\n name for name in self.names\n if name is not destination\n and any(origin.search(name) for origin in origins)\n ]\n\n ignores = self.ignore_regexes.get(destination, [])\n for origin in resolved:\n destinations = self.routes.setdefault(origin, set())\n\n if any(ignore.search(origin) for ignore in ignores):\n self.logger.info('ignoring route \"%s\" -> \"%s\"', origin, destination)\n try:\n destinations.remove(destination)\n self.logger.debug('removed \"%s\" -> \"%s\"', origin, destination)\n except KeyError:\n pass\n\n continue\n\n if destination not in destinations:\n self.logger.info('added route \"%s\" -> \"%s\"', origin, destination)\n\n destinations.add(destination)\n" ]
class Router(object): 'A router object. Holds routes and references to functions for dispatch' def __init__(self, message_class=None, node_modules=None, node_package=None): '''\ Create a new router object. All parameters are optional. :param message_class: wrapper class for messages passed to nodes :type message_class: :py:class:`emit.message.Message` or subclass :param node_modules: a list of modules that contain nodes :type node_modules: a list of :py:class:`str`, or ``None``. :param node_package: if any node_modules are relative, the path to base off of. :type node_package: :py:class:`str`, or ``None``. :exceptions: None :returns: None ''' self.routes = {} self.names = set() self.regexes = {} self.ignore_regexes = {} self.fields = {} self.functions = {} self.message_class = message_class or Message # manage imported packages, lazily importing before the first message # is routed. self.resolved_node_modules = [] self.node_modules = node_modules or [] self.node_package = node_package self.logger = logging.getLogger(__name__ + '.Router') self.logger.debug('Initialized Router') self.routing_enabled = True def __call__(self, **kwargs): '''\ Route a message to all nodes marked as entry points. .. note:: This function does not optionally accept a single argument (dictionary) as other points in this API do - it must be expanded to keyword arguments in this case. ''' self.logger.info('Calling entry point with %r', kwargs) self.route('__entry_point', kwargs) def wrap_as_node(self, func): 'wrap a function as a node' name = self.get_name(func) @wraps(func) def wrapped(*args, **kwargs): 'wrapped version of func' message = self.get_message_from_call(*args, **kwargs) self.logger.info('calling "%s" with %r', name, message) result = func(message) # functions can return multiple values ("emit" multiple times) # by yielding instead of returning. Handle this case by making # a list of the results and processing them all after the # generator successfully exits. If we were to process them as # they came out of the generator, we might get a partially # processed input sent down the graph. This may be possible in # the future via a flag. if isinstance(result, GeneratorType): results = [ self.wrap_result(name, item) for item in result if item is not NoResult ] self.logger.debug( '%s returned generator yielding %d items', func, len(results) ) [self.route(name, item) for item in results] return tuple(results) # the case of a direct return is simpler. wrap, route, and # return the value. else: if result is NoResult: return result result = self.wrap_result(name, result) self.logger.debug( '%s returned single value %s', func, result ) self.route(name, result) return result return wrapped def node(self, fields, subscribe_to=None, entry_point=False, ignore=None, **wrapper_options): '''\ Decorate a function to make it a node. .. note:: decorating as a node changes the function signature. Nodes should accept a single argument, which will be a :py:class:`emit.message.Message`. Nodes can be called directly by providing a dictionary argument or a set of keyword arguments. Other uses will raise a ``TypeError``. :param fields: fields that this function returns :type fields: ordered iterable of :py:class:`str` :param subscribe_to: functions in the graph to subscribe to. These indicators can be regular expressions. :type subscribe_to: :py:class:`str` or iterable of :py:class:`str` :param ignore: functions in the graph to ignore (also uses regular expressions.) Useful for ignoring specific functions in a broad regex. :type ignore: :py:class:`str` or iterable of :py:class:`str` :param entry_point: Set to ``True`` to mark this as an entry point - that is, this function will be called when the router is called directly. :type entry_point: :py:class:`bool` In addition to all of the above, you can define a ``wrap_node`` function on a subclass of Router, which will need to receive node and an options dictionary. Any extra options passed to node will be passed down to the options dictionary. See :py:class:`emit.router.CeleryRouter.wrap_node` as an example. :returns: decorated and wrapped function, or decorator if called directly ''' def outer(func): 'outer level function' # create a wrapper function self.logger.debug('wrapping %s', func) wrapped = self.wrap_as_node(func) if hasattr(self, 'wrap_node'): self.logger.debug('wrapping node "%s" in custom wrapper', wrapped) wrapped = self.wrap_node(wrapped, wrapper_options) # register the task in the graph name = self.get_name(func) self.register( name, wrapped, fields, subscribe_to, entry_point, ignore ) return wrapped return outer def resolve_node_modules(self): 'import the modules specified in init' if not self.resolved_node_modules: try: self.resolved_node_modules = [ importlib.import_module(mod, self.node_package) for mod in self.node_modules ] except ImportError: self.resolved_node_modules = [] raise return self.resolved_node_modules def get_message_from_call(self, *args, **kwargs): '''\ Get message object from a call. :raises: :py:exc:`TypeError` (if the format is not what we expect) This is where arguments to nodes are turned into Messages. Arguments are parsed in the following order: - A single positional argument (a :py:class:`dict`) - No positional arguments and a number of keyword arguments ''' if len(args) == 1 and isinstance(args[0], dict): # then it's a message self.logger.debug('called with arg dictionary') result = args[0] elif len(args) == 0 and kwargs != {}: # then it's a set of kwargs self.logger.debug('called with kwargs') result = kwargs else: # it's neither, and we don't handle that self.logger.error( 'get_message_from_call could not handle "%r", "%r"', args, kwargs ) raise TypeError('Pass either keyword arguments or a dictionary argument') return self.message_class(result) def register(self, name, func, fields, subscribe_to, entry_point, ignore): ''' Register a named function in the graph :param name: name to register :type name: :py:class:`str` :param func: function to remember and call :type func: callable ``fields``, ``subscribe_to`` and ``entry_point`` are the same as in :py:meth:`Router.node`. ''' self.fields[name] = fields self.functions[name] = func self.register_route(subscribe_to, name) if ignore: self.register_ignore(ignore, name) if entry_point: self.add_entry_point(name) self.logger.info('registered %s', name) def add_entry_point(self, destination): '''\ Add an entry point :param destination: node to route to initially :type destination: str ''' self.routes.setdefault('__entry_point', set()).add(destination) return self.routes['__entry_point'] def register_ignore(self, origins, destination): ''' Add routes to the ignore dictionary :param origins: a number of origins to register :type origins: :py:class:`str` or iterable of :py:class:`str` :param destination: where the origins should point to :type destination: :py:class:`str` Ignore dictionary takes the following form:: {'node_a': set(['node_b', 'node_c']), 'node_b': set(['node_d'])} ''' if not isinstance(origins, list): origins = [origins] self.ignore_regexes.setdefault(destination, [re.compile(origin) for origin in origins]) self.regenerate_routes() return self.ignore_regexes[destination] def regenerate_routes(self): 'regenerate the routes after a new route is added' for destination, origins in self.regexes.items(): # we want only the names that match the destination regexes. resolved = [ name for name in self.names if name is not destination and any(origin.search(name) for origin in origins) ] ignores = self.ignore_regexes.get(destination, []) for origin in resolved: destinations = self.routes.setdefault(origin, set()) if any(ignore.search(origin) for ignore in ignores): self.logger.info('ignoring route "%s" -> "%s"', origin, destination) try: destinations.remove(destination) self.logger.debug('removed "%s" -> "%s"', origin, destination) except KeyError: pass continue if destination not in destinations: self.logger.info('added route "%s" -> "%s"', origin, destination) destinations.add(destination) def disable_routing(self): 'disable routing (usually for testing purposes)' self.routing_enabled = False def enable_routing(self): 'enable routing (after calling ``disable_routing``)' self.routing_enabled = True def route(self, origin, message): '''\ Using the routing dictionary, dispatch a message to all subscribers :param origin: name of the origin node :type origin: :py:class:`str` :param message: message to dispatch :type message: :py:class:`emit.message.Message` or subclass ''' # side-effect: we have to know all the routes before we can route. But # we can't resolve them while the object is initializing, so we have to # do it just in time to route. self.resolve_node_modules() if not self.routing_enabled: return subs = self.routes.get(origin, set()) for destination in subs: self.logger.debug('routing "%s" -> "%s"', origin, destination) self.dispatch(origin, destination, message) def dispatch(self, origin, destination, message): '''\ dispatch a message to a named function :param destination: destination to dispatch to :type destination: :py:class:`str` :param message: message to dispatch :type message: :py:class:`emit.message.Message` or subclass ''' func = self.functions[destination] self.logger.debug('calling %r directly', func) return func(_origin=origin, **message) def wrap_result(self, name, result): ''' Wrap a result from a function with it's stated fields :param name: fields to look up :type name: :py:class:`str` :param result: return value from function. Will be converted to tuple. :type result: anything :raises: :py:exc:`ValueError` if name has no associated fields :returns: :py:class:`dict` ''' if not isinstance(result, tuple): result = tuple([result]) try: return dict(zip(self.fields[name], result)) except KeyError: msg = '"%s" has no associated fields' self.logger.exception(msg, name) raise ValueError(msg % name) def get_name(self, func): ''' Get the name to reference a function by :param func: function to get the name of :type func: callable ''' if hasattr(func, 'name'): return func.name return '%s.%s' % ( func.__module__, func.__name__ )
BrianHicks/emit
emit/router/core.py
Router.register_ignore
python
def register_ignore(self, origins, destination): ''' Add routes to the ignore dictionary :param origins: a number of origins to register :type origins: :py:class:`str` or iterable of :py:class:`str` :param destination: where the origins should point to :type destination: :py:class:`str` Ignore dictionary takes the following form:: {'node_a': set(['node_b', 'node_c']), 'node_b': set(['node_d'])} ''' if not isinstance(origins, list): origins = [origins] self.ignore_regexes.setdefault(destination, [re.compile(origin) for origin in origins]) self.regenerate_routes() return self.ignore_regexes[destination]
Add routes to the ignore dictionary :param origins: a number of origins to register :type origins: :py:class:`str` or iterable of :py:class:`str` :param destination: where the origins should point to :type destination: :py:class:`str` Ignore dictionary takes the following form:: {'node_a': set(['node_b', 'node_c']), 'node_b': set(['node_d'])}
train
https://github.com/BrianHicks/emit/blob/19a86c2392b136c9e857000798ccaa525aa0ed84/emit/router/core.py#L267-L288
[ "def regenerate_routes(self):\n 'regenerate the routes after a new route is added'\n for destination, origins in self.regexes.items():\n # we want only the names that match the destination regexes.\n resolved = [\n name for name in self.names\n if name is not destination\n and any(origin.search(name) for origin in origins)\n ]\n\n ignores = self.ignore_regexes.get(destination, [])\n for origin in resolved:\n destinations = self.routes.setdefault(origin, set())\n\n if any(ignore.search(origin) for ignore in ignores):\n self.logger.info('ignoring route \"%s\" -> \"%s\"', origin, destination)\n try:\n destinations.remove(destination)\n self.logger.debug('removed \"%s\" -> \"%s\"', origin, destination)\n except KeyError:\n pass\n\n continue\n\n if destination not in destinations:\n self.logger.info('added route \"%s\" -> \"%s\"', origin, destination)\n\n destinations.add(destination)\n" ]
class Router(object): 'A router object. Holds routes and references to functions for dispatch' def __init__(self, message_class=None, node_modules=None, node_package=None): '''\ Create a new router object. All parameters are optional. :param message_class: wrapper class for messages passed to nodes :type message_class: :py:class:`emit.message.Message` or subclass :param node_modules: a list of modules that contain nodes :type node_modules: a list of :py:class:`str`, or ``None``. :param node_package: if any node_modules are relative, the path to base off of. :type node_package: :py:class:`str`, or ``None``. :exceptions: None :returns: None ''' self.routes = {} self.names = set() self.regexes = {} self.ignore_regexes = {} self.fields = {} self.functions = {} self.message_class = message_class or Message # manage imported packages, lazily importing before the first message # is routed. self.resolved_node_modules = [] self.node_modules = node_modules or [] self.node_package = node_package self.logger = logging.getLogger(__name__ + '.Router') self.logger.debug('Initialized Router') self.routing_enabled = True def __call__(self, **kwargs): '''\ Route a message to all nodes marked as entry points. .. note:: This function does not optionally accept a single argument (dictionary) as other points in this API do - it must be expanded to keyword arguments in this case. ''' self.logger.info('Calling entry point with %r', kwargs) self.route('__entry_point', kwargs) def wrap_as_node(self, func): 'wrap a function as a node' name = self.get_name(func) @wraps(func) def wrapped(*args, **kwargs): 'wrapped version of func' message = self.get_message_from_call(*args, **kwargs) self.logger.info('calling "%s" with %r', name, message) result = func(message) # functions can return multiple values ("emit" multiple times) # by yielding instead of returning. Handle this case by making # a list of the results and processing them all after the # generator successfully exits. If we were to process them as # they came out of the generator, we might get a partially # processed input sent down the graph. This may be possible in # the future via a flag. if isinstance(result, GeneratorType): results = [ self.wrap_result(name, item) for item in result if item is not NoResult ] self.logger.debug( '%s returned generator yielding %d items', func, len(results) ) [self.route(name, item) for item in results] return tuple(results) # the case of a direct return is simpler. wrap, route, and # return the value. else: if result is NoResult: return result result = self.wrap_result(name, result) self.logger.debug( '%s returned single value %s', func, result ) self.route(name, result) return result return wrapped def node(self, fields, subscribe_to=None, entry_point=False, ignore=None, **wrapper_options): '''\ Decorate a function to make it a node. .. note:: decorating as a node changes the function signature. Nodes should accept a single argument, which will be a :py:class:`emit.message.Message`. Nodes can be called directly by providing a dictionary argument or a set of keyword arguments. Other uses will raise a ``TypeError``. :param fields: fields that this function returns :type fields: ordered iterable of :py:class:`str` :param subscribe_to: functions in the graph to subscribe to. These indicators can be regular expressions. :type subscribe_to: :py:class:`str` or iterable of :py:class:`str` :param ignore: functions in the graph to ignore (also uses regular expressions.) Useful for ignoring specific functions in a broad regex. :type ignore: :py:class:`str` or iterable of :py:class:`str` :param entry_point: Set to ``True`` to mark this as an entry point - that is, this function will be called when the router is called directly. :type entry_point: :py:class:`bool` In addition to all of the above, you can define a ``wrap_node`` function on a subclass of Router, which will need to receive node and an options dictionary. Any extra options passed to node will be passed down to the options dictionary. See :py:class:`emit.router.CeleryRouter.wrap_node` as an example. :returns: decorated and wrapped function, or decorator if called directly ''' def outer(func): 'outer level function' # create a wrapper function self.logger.debug('wrapping %s', func) wrapped = self.wrap_as_node(func) if hasattr(self, 'wrap_node'): self.logger.debug('wrapping node "%s" in custom wrapper', wrapped) wrapped = self.wrap_node(wrapped, wrapper_options) # register the task in the graph name = self.get_name(func) self.register( name, wrapped, fields, subscribe_to, entry_point, ignore ) return wrapped return outer def resolve_node_modules(self): 'import the modules specified in init' if not self.resolved_node_modules: try: self.resolved_node_modules = [ importlib.import_module(mod, self.node_package) for mod in self.node_modules ] except ImportError: self.resolved_node_modules = [] raise return self.resolved_node_modules def get_message_from_call(self, *args, **kwargs): '''\ Get message object from a call. :raises: :py:exc:`TypeError` (if the format is not what we expect) This is where arguments to nodes are turned into Messages. Arguments are parsed in the following order: - A single positional argument (a :py:class:`dict`) - No positional arguments and a number of keyword arguments ''' if len(args) == 1 and isinstance(args[0], dict): # then it's a message self.logger.debug('called with arg dictionary') result = args[0] elif len(args) == 0 and kwargs != {}: # then it's a set of kwargs self.logger.debug('called with kwargs') result = kwargs else: # it's neither, and we don't handle that self.logger.error( 'get_message_from_call could not handle "%r", "%r"', args, kwargs ) raise TypeError('Pass either keyword arguments or a dictionary argument') return self.message_class(result) def register(self, name, func, fields, subscribe_to, entry_point, ignore): ''' Register a named function in the graph :param name: name to register :type name: :py:class:`str` :param func: function to remember and call :type func: callable ``fields``, ``subscribe_to`` and ``entry_point`` are the same as in :py:meth:`Router.node`. ''' self.fields[name] = fields self.functions[name] = func self.register_route(subscribe_to, name) if ignore: self.register_ignore(ignore, name) if entry_point: self.add_entry_point(name) self.logger.info('registered %s', name) def add_entry_point(self, destination): '''\ Add an entry point :param destination: node to route to initially :type destination: str ''' self.routes.setdefault('__entry_point', set()).add(destination) return self.routes['__entry_point'] def register_route(self, origins, destination): ''' Add routes to the routing dictionary :param origins: a number of origins to register :type origins: :py:class:`str` or iterable of :py:class:`str` or None :param destination: where the origins should point to :type destination: :py:class:`str` Routing dictionary takes the following form:: {'node_a': set(['node_b', 'node_c']), 'node_b': set(['node_d'])} ''' self.names.add(destination) self.logger.debug('added "%s" to names', destination) origins = origins or [] # remove None if not isinstance(origins, list): origins = [origins] self.regexes.setdefault(destination, [re.compile(origin) for origin in origins]) self.regenerate_routes() return self.regexes[destination] def regenerate_routes(self): 'regenerate the routes after a new route is added' for destination, origins in self.regexes.items(): # we want only the names that match the destination regexes. resolved = [ name for name in self.names if name is not destination and any(origin.search(name) for origin in origins) ] ignores = self.ignore_regexes.get(destination, []) for origin in resolved: destinations = self.routes.setdefault(origin, set()) if any(ignore.search(origin) for ignore in ignores): self.logger.info('ignoring route "%s" -> "%s"', origin, destination) try: destinations.remove(destination) self.logger.debug('removed "%s" -> "%s"', origin, destination) except KeyError: pass continue if destination not in destinations: self.logger.info('added route "%s" -> "%s"', origin, destination) destinations.add(destination) def disable_routing(self): 'disable routing (usually for testing purposes)' self.routing_enabled = False def enable_routing(self): 'enable routing (after calling ``disable_routing``)' self.routing_enabled = True def route(self, origin, message): '''\ Using the routing dictionary, dispatch a message to all subscribers :param origin: name of the origin node :type origin: :py:class:`str` :param message: message to dispatch :type message: :py:class:`emit.message.Message` or subclass ''' # side-effect: we have to know all the routes before we can route. But # we can't resolve them while the object is initializing, so we have to # do it just in time to route. self.resolve_node_modules() if not self.routing_enabled: return subs = self.routes.get(origin, set()) for destination in subs: self.logger.debug('routing "%s" -> "%s"', origin, destination) self.dispatch(origin, destination, message) def dispatch(self, origin, destination, message): '''\ dispatch a message to a named function :param destination: destination to dispatch to :type destination: :py:class:`str` :param message: message to dispatch :type message: :py:class:`emit.message.Message` or subclass ''' func = self.functions[destination] self.logger.debug('calling %r directly', func) return func(_origin=origin, **message) def wrap_result(self, name, result): ''' Wrap a result from a function with it's stated fields :param name: fields to look up :type name: :py:class:`str` :param result: return value from function. Will be converted to tuple. :type result: anything :raises: :py:exc:`ValueError` if name has no associated fields :returns: :py:class:`dict` ''' if not isinstance(result, tuple): result = tuple([result]) try: return dict(zip(self.fields[name], result)) except KeyError: msg = '"%s" has no associated fields' self.logger.exception(msg, name) raise ValueError(msg % name) def get_name(self, func): ''' Get the name to reference a function by :param func: function to get the name of :type func: callable ''' if hasattr(func, 'name'): return func.name return '%s.%s' % ( func.__module__, func.__name__ )