nwo
stringlengths
6
76
sha
stringlengths
40
40
path
stringlengths
5
118
language
stringclasses
1 value
identifier
stringlengths
1
89
parameters
stringlengths
2
5.4k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
51.1k
docstring
stringlengths
1
17.6k
docstring_summary
stringlengths
0
7.02k
docstring_tokens
sequence
function
stringlengths
30
51.1k
function_tokens
sequence
url
stringlengths
85
218
9miao/G-Firefly
8fbeeb3ef9782600560be48228c91cfb8f5ff87d
gfirefly/gfirefly/distributed/node.py
python
BilateralClientProtocol.getRemoteMethod
(self, _name)
return method
重写获取接口对象的方法,从代理接口提供对象中获取
重写获取接口对象的方法,从代理接口提供对象中获取
[ "重写获取接口对象的方法,从代理接口提供对象中获取" ]
def getRemoteMethod(self, _name): """重写获取接口对象的方法,从代理接口提供对象中获取 """ method = getattr(self.reference, "remote_%s"%_name) return method
[ "def", "getRemoteMethod", "(", "self", ",", "_name", ")", ":", "method", "=", "getattr", "(", "self", ".", "reference", ",", "\"remote_%s\"", "%", "_name", ")", "return", "method" ]
https://github.com/9miao/G-Firefly/blob/8fbeeb3ef9782600560be48228c91cfb8f5ff87d/gfirefly/gfirefly/distributed/node.py#L23-L27
9miao/G-Firefly
8fbeeb3ef9782600560be48228c91cfb8f5ff87d
gfirefly/gfirefly/distributed/node.py
python
BilateralClientFactory.doconnectionLost
(self)
node节点端开后的处理
node节点端开后的处理
[ "node节点端开后的处理" ]
def doconnectionLost(self): """node节点端开后的处理 """ if self.ro: self.ro.reconnect()
[ "def", "doconnectionLost", "(", "self", ")", ":", "if", "self", ".", "ro", ":", "self", ".", "ro", ".", "reconnect", "(", ")" ]
https://github.com/9miao/G-Firefly/blob/8fbeeb3ef9782600560be48228c91cfb8f5ff87d/gfirefly/gfirefly/distributed/node.py#L42-L46
9miao/G-Firefly
8fbeeb3ef9782600560be48228c91cfb8f5ff87d
gfirefly/gfirefly/distributed/node.py
python
RemoteObject.__init__
(self,name,timeout=600)
初始化远程调用对象 @param port: int 远程分布服的端口号 @param rootaddr: 根节点服务器地址
初始化远程调用对象
[ "初始化远程调用对象" ]
def __init__(self,name,timeout=600): '''初始化远程调用对象 @param port: int 远程分布服的端口号 @param rootaddr: 根节点服务器地址 ''' self._name = name self._factory = BilateralClientFactory(self) self._reference = ProxyReference() self._addr = None self._timeout = timeout
[ "def", "__init__", "(", "self", ",", "name", ",", "timeout", "=", "600", ")", ":", "self", ".", "_name", "=", "name", "self", ".", "_factory", "=", "BilateralClientFactory", "(", "self", ")", "self", ".", "_reference", "=", "ProxyReference", "(", ")", "self", ".", "_addr", "=", "None", "self", ".", "_timeout", "=", "timeout" ]
https://github.com/9miao/G-Firefly/blob/8fbeeb3ef9782600560be48228c91cfb8f5ff87d/gfirefly/gfirefly/distributed/node.py#L53-L62
9miao/G-Firefly
8fbeeb3ef9782600560be48228c91cfb8f5ff87d
gfirefly/gfirefly/distributed/node.py
python
RemoteObject.setName
(self,name)
设置节点的名称
设置节点的名称
[ "设置节点的名称" ]
def setName(self,name): '''设置节点的名称''' self._name = name
[ "def", "setName", "(", "self", ",", "name", ")", ":", "self", ".", "_name", "=", "name" ]
https://github.com/9miao/G-Firefly/blob/8fbeeb3ef9782600560be48228c91cfb8f5ff87d/gfirefly/gfirefly/distributed/node.py#L64-L66
9miao/G-Firefly
8fbeeb3ef9782600560be48228c91cfb8f5ff87d
gfirefly/gfirefly/distributed/node.py
python
RemoteObject.getName
(self)
return self._name
获取节点的名称
获取节点的名称
[ "获取节点的名称" ]
def getName(self): '''获取节点的名称''' return self._name
[ "def", "getName", "(", "self", ")", ":", "return", "self", ".", "_name" ]
https://github.com/9miao/G-Firefly/blob/8fbeeb3ef9782600560be48228c91cfb8f5ff87d/gfirefly/gfirefly/distributed/node.py#L68-L70
9miao/G-Firefly
8fbeeb3ef9782600560be48228c91cfb8f5ff87d
gfirefly/gfirefly/distributed/node.py
python
RemoteObject.connect
(self,addr)
初始化远程调用对象
初始化远程调用对象
[ "初始化远程调用对象" ]
def connect(self,addr): '''初始化远程调用对象''' self._addr = addr reactor.connectTCP(addr[0], addr[1], self._factory) self.takeProxy()
[ "def", "connect", "(", "self", ",", "addr", ")", ":", "self", ".", "_addr", "=", "addr", "reactor", ".", "connectTCP", "(", "addr", "[", "0", "]", ",", "addr", "[", "1", "]", ",", "self", ".", "_factory", ")", "self", ".", "takeProxy", "(", ")" ]
https://github.com/9miao/G-Firefly/blob/8fbeeb3ef9782600560be48228c91cfb8f5ff87d/gfirefly/gfirefly/distributed/node.py#L72-L76
9miao/G-Firefly
8fbeeb3ef9782600560be48228c91cfb8f5ff87d
gfirefly/gfirefly/distributed/node.py
python
RemoteObject.reconnect
(self,addr=())
重新连接
重新连接
[ "重新连接" ]
def reconnect(self,addr=()): '''重新连接''' if addr: self.connect(addr) else: self.connect(self._addr)
[ "def", "reconnect", "(", "self", ",", "addr", "=", "(", ")", ")", ":", "if", "addr", ":", "self", ".", "connect", "(", "addr", ")", "else", ":", "self", ".", "connect", "(", "self", ".", "_addr", ")" ]
https://github.com/9miao/G-Firefly/blob/8fbeeb3ef9782600560be48228c91cfb8f5ff87d/gfirefly/gfirefly/distributed/node.py#L78-L83
9miao/G-Firefly
8fbeeb3ef9782600560be48228c91cfb8f5ff87d
gfirefly/gfirefly/distributed/node.py
python
RemoteObject.addServiceChannel
(self,service)
设置引用对象
设置引用对象
[ "设置引用对象" ]
def addServiceChannel(self,service): '''设置引用对象''' self._reference.addService(service)
[ "def", "addServiceChannel", "(", "self", ",", "service", ")", ":", "self", ".", "_reference", ".", "addService", "(", "service", ")" ]
https://github.com/9miao/G-Firefly/blob/8fbeeb3ef9782600560be48228c91cfb8f5ff87d/gfirefly/gfirefly/distributed/node.py#L85-L87
9miao/G-Firefly
8fbeeb3ef9782600560be48228c91cfb8f5ff87d
gfirefly/gfirefly/distributed/node.py
python
RemoteObject.takeProxy
(self)
像远程服务端发送代理通道对象
像远程服务端发送代理通道对象
[ "像远程服务端发送代理通道对象" ]
def takeProxy(self): '''像远程服务端发送代理通道对象 ''' self._factory._protocol.setProxyReference(self._reference) deferedRemote = self._factory.getRootObject(timeout=self._timeout) deferedRemote.callRemoteNotForResult('takeProxy',self._name)
[ "def", "takeProxy", "(", "self", ")", ":", "self", ".", "_factory", ".", "_protocol", ".", "setProxyReference", "(", "self", ".", "_reference", ")", "deferedRemote", "=", "self", ".", "_factory", ".", "getRootObject", "(", "timeout", "=", "self", ".", "_timeout", ")", "deferedRemote", ".", "callRemoteNotForResult", "(", "'takeProxy'", ",", "self", ".", "_name", ")" ]
https://github.com/9miao/G-Firefly/blob/8fbeeb3ef9782600560be48228c91cfb8f5ff87d/gfirefly/gfirefly/distributed/node.py#L89-L94
9miao/G-Firefly
8fbeeb3ef9782600560be48228c91cfb8f5ff87d
gfirefly/gfirefly/distributed/node.py
python
RemoteObject.callRemote
(self,commandId,*args,**kw)
return deferedRemote.callRemoteForResult('callTarget',commandId,*args,**kw)
默认远程调用,等待结果放回
默认远程调用,等待结果放回
[ "默认远程调用,等待结果放回" ]
def callRemote(self,commandId,*args,**kw): """默认远程调用,等待结果放回 """ deferedRemote = self._factory.getRootObject(timeout=self._timeout) return deferedRemote.callRemoteForResult('callTarget',commandId,*args,**kw)
[ "def", "callRemote", "(", "self", ",", "commandId", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "deferedRemote", "=", "self", ".", "_factory", ".", "getRootObject", "(", "timeout", "=", "self", ".", "_timeout", ")", "return", "deferedRemote", ".", "callRemoteForResult", "(", "'callTarget'", ",", "commandId", ",", "*", "args", ",", "*", "*", "kw", ")" ]
https://github.com/9miao/G-Firefly/blob/8fbeeb3ef9782600560be48228c91cfb8f5ff87d/gfirefly/gfirefly/distributed/node.py#L96-L100
9miao/G-Firefly
8fbeeb3ef9782600560be48228c91cfb8f5ff87d
gfirefly/gfirefly/distributed/node.py
python
RemoteObject.callRemoteForResult
(self,commandId,*args,**kw)
return deferedRemote.callRemoteForResult('callTarget',commandId,*args,**kw)
远程调用,并等待结果放回
远程调用,并等待结果放回
[ "远程调用,并等待结果放回" ]
def callRemoteForResult(self,commandId,*args,**kw): '''远程调用,并等待结果放回 ''' deferedRemote = self._factory.getRootObject(timeout=self._timeout) return deferedRemote.callRemoteForResult('callTarget',commandId,*args,**kw)
[ "def", "callRemoteForResult", "(", "self", ",", "commandId", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "deferedRemote", "=", "self", ".", "_factory", ".", "getRootObject", "(", "timeout", "=", "self", ".", "_timeout", ")", "return", "deferedRemote", ".", "callRemoteForResult", "(", "'callTarget'", ",", "commandId", ",", "*", "args", ",", "*", "*", "kw", ")" ]
https://github.com/9miao/G-Firefly/blob/8fbeeb3ef9782600560be48228c91cfb8f5ff87d/gfirefly/gfirefly/distributed/node.py#L102-L106
9miao/G-Firefly
8fbeeb3ef9782600560be48228c91cfb8f5ff87d
gfirefly/gfirefly/distributed/node.py
python
RemoteObject.callRemoteNotForResult
(self,commandId,*args,**kw)
return deferedRemote.callRemoteNotForResult('callTarget',commandId,*args,**kw)
远程调用,不需要结果放回
远程调用,不需要结果放回
[ "远程调用", "不需要结果放回" ]
def callRemoteNotForResult(self,commandId,*args,**kw): '''远程调用,不需要结果放回 ''' deferedRemote = self._factory.getRootObject(timeout=self._timeout) return deferedRemote.callRemoteNotForResult('callTarget',commandId,*args,**kw)
[ "def", "callRemoteNotForResult", "(", "self", ",", "commandId", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "deferedRemote", "=", "self", ".", "_factory", ".", "getRootObject", "(", "timeout", "=", "self", ".", "_timeout", ")", "return", "deferedRemote", ".", "callRemoteNotForResult", "(", "'callTarget'", ",", "commandId", ",", "*", "args", ",", "*", "*", "kw", ")" ]
https://github.com/9miao/G-Firefly/blob/8fbeeb3ef9782600560be48228c91cfb8f5ff87d/gfirefly/gfirefly/distributed/node.py#L108-L112
9miao/G-Firefly
8fbeeb3ef9782600560be48228c91cfb8f5ff87d
gfirefly/gfirefly/netconnect/connection.py
python
Connection.__init__
(self, _conn)
id 连接的ID transport 连接的通道
id 连接的ID transport 连接的通道
[ "id", "连接的ID", "transport", "连接的通道" ]
def __init__(self, _conn): ''' id 连接的ID transport 连接的通道 ''' self.id = _conn.transport.sessionno self.instance = _conn
[ "def", "__init__", "(", "self", ",", "_conn", ")", ":", "self", ".", "id", "=", "_conn", ".", "transport", ".", "sessionno", "self", ".", "instance", "=", "_conn" ]
https://github.com/9miao/G-Firefly/blob/8fbeeb3ef9782600560be48228c91cfb8f5ff87d/gfirefly/gfirefly/netconnect/connection.py#L11-L17
9miao/G-Firefly
8fbeeb3ef9782600560be48228c91cfb8f5ff87d
gfirefly/gfirefly/netconnect/connection.py
python
Connection.loseConnection
(self)
断开与客户端的连接
断开与客户端的连接
[ "断开与客户端的连接" ]
def loseConnection(self): '''断开与客户端的连接 ''' self.instance.transport.close()
[ "def", "loseConnection", "(", "self", ")", ":", "self", ".", "instance", ".", "transport", ".", "close", "(", ")" ]
https://github.com/9miao/G-Firefly/blob/8fbeeb3ef9782600560be48228c91cfb8f5ff87d/gfirefly/gfirefly/netconnect/connection.py#L19-L22
9miao/G-Firefly
8fbeeb3ef9782600560be48228c91cfb8f5ff87d
gfirefly/gfirefly/netconnect/connection.py
python
Connection.safeToWriteData
(self,topicID,msg)
发送消息
发送消息
[ "发送消息" ]
def safeToWriteData(self,topicID,msg): """发送消息 """ self.instance.safeToWriteData(msg,topicID)
[ "def", "safeToWriteData", "(", "self", ",", "topicID", ",", "msg", ")", ":", "self", ".", "instance", ".", "safeToWriteData", "(", "msg", ",", "topicID", ")" ]
https://github.com/9miao/G-Firefly/blob/8fbeeb3ef9782600560be48228c91cfb8f5ff87d/gfirefly/gfirefly/netconnect/connection.py#L24-L27
9miao/G-Firefly
8fbeeb3ef9782600560be48228c91cfb8f5ff87d
gfirefly/gfirefly/netconnect/datapack.py
python
DataPackProtoc.__init__
(self,HEAD_0 = 0,HEAD_1=0,HEAD_2=0,HEAD_3=0,protoVersion= 0,serverVersion=0)
初始化 @param HEAD_0: int 协议头0 @param HEAD_1: int 协议头1 @param HEAD_2: int 协议头2 @param HEAD_3: int 协议头3 @param protoVersion: int 协议头版本号 @param serverVersion: int 服务版本号
初始化
[ "初始化" ]
def __init__(self,HEAD_0 = 0,HEAD_1=0,HEAD_2=0,HEAD_3=0,protoVersion= 0,serverVersion=0): '''初始化 @param HEAD_0: int 协议头0 @param HEAD_1: int 协议头1 @param HEAD_2: int 协议头2 @param HEAD_3: int 协议头3 @param protoVersion: int 协议头版本号 @param serverVersion: int 服务版本号 ''' self.HEAD_0 = HEAD_0 self.HEAD_1 = HEAD_1 self.HEAD_2 = HEAD_2 self.HEAD_3 = HEAD_3 self.protoVersion = protoVersion self.serverVersion = serverVersion
[ "def", "__init__", "(", "self", ",", "HEAD_0", "=", "0", ",", "HEAD_1", "=", "0", ",", "HEAD_2", "=", "0", ",", "HEAD_3", "=", "0", ",", "protoVersion", "=", "0", ",", "serverVersion", "=", "0", ")", ":", "self", ".", "HEAD_0", "=", "HEAD_0", "self", ".", "HEAD_1", "=", "HEAD_1", "self", ".", "HEAD_2", "=", "HEAD_2", "self", ".", "HEAD_3", "=", "HEAD_3", "self", ".", "protoVersion", "=", "protoVersion", "self", ".", "serverVersion", "=", "serverVersion" ]
https://github.com/9miao/G-Firefly/blob/8fbeeb3ef9782600560be48228c91cfb8f5ff87d/gfirefly/gfirefly/netconnect/datapack.py#L24-L38
9miao/G-Firefly
8fbeeb3ef9782600560be48228c91cfb8f5ff87d
gfirefly/gfirefly/netconnect/datapack.py
python
DataPackProtoc.getHeadlength
(self)
return 17
获取数据包的长度
获取数据包的长度
[ "获取数据包的长度" ]
def getHeadlength(self): """获取数据包的长度 """ return 17
[ "def", "getHeadlength", "(", "self", ")", ":", "return", "17" ]
https://github.com/9miao/G-Firefly/blob/8fbeeb3ef9782600560be48228c91cfb8f5ff87d/gfirefly/gfirefly/netconnect/datapack.py#L58-L61
9miao/G-Firefly
8fbeeb3ef9782600560be48228c91cfb8f5ff87d
gfirefly/gfirefly/netconnect/datapack.py
python
DataPackProtoc.unpack
(self,dpack)
return {'result':True,'command':command,'length':length}
解包
解包
[ "解包" ]
def unpack(self,dpack): '''解包 ''' try: ud = struct.unpack('!sssss3I',dpack) except struct.error,de: log.err(de,traceback.format_exc()) return {'result':False,'command':0,'length':0} HEAD_0 = ord(ud[0]) HEAD_1 = ord(ud[1]) HEAD_2 = ord(ud[2]) HEAD_3 = ord(ud[3]) protoVersion = ord(ud[4]) serverVersion = ud[5] length = ud[6]-4 command = ud[7] if HEAD_0 <>self.HEAD_0 or HEAD_1<>self.HEAD_1 or\ HEAD_2<>self.HEAD_2 or HEAD_3<>self.HEAD_3 or\ protoVersion<>self.protoVersion or serverVersion<>self.serverVersion: return {'result':False,'command':0,'length':0} return {'result':True,'command':command,'length':length}
[ "def", "unpack", "(", "self", ",", "dpack", ")", ":", "try", ":", "ud", "=", "struct", ".", "unpack", "(", "'!sssss3I'", ",", "dpack", ")", "except", "struct", ".", "error", ",", "de", ":", "log", ".", "err", "(", "de", ",", "traceback", ".", "format_exc", "(", ")", ")", "return", "{", "'result'", ":", "False", ",", "'command'", ":", "0", ",", "'length'", ":", "0", "}", "HEAD_0", "=", "ord", "(", "ud", "[", "0", "]", ")", "HEAD_1", "=", "ord", "(", "ud", "[", "1", "]", ")", "HEAD_2", "=", "ord", "(", "ud", "[", "2", "]", ")", "HEAD_3", "=", "ord", "(", "ud", "[", "3", "]", ")", "protoVersion", "=", "ord", "(", "ud", "[", "4", "]", ")", "serverVersion", "=", "ud", "[", "5", "]", "length", "=", "ud", "[", "6", "]", "-", "4", "command", "=", "ud", "[", "7", "]", "if", "HEAD_0", "<>", "self", ".", "HEAD_0", "or", "HEAD_1", "<>", "self", ".", "HEAD_1", "or", "HEAD_2", "<>", "self", ".", "HEAD_2", "or", "HEAD_3", "<>", "self", ".", "HEAD_3", "or", "protoVersion", "<>", "self", ".", "protoVersion", "or", "serverVersion", "<>", "self", ".", "serverVersion", ":", "return", "{", "'result'", ":", "False", ",", "'command'", ":", "0", ",", "'length'", ":", "0", "}", "return", "{", "'result'", ":", "True", ",", "'command'", ":", "command", ",", "'length'", ":", "length", "}" ]
https://github.com/9miao/G-Firefly/blob/8fbeeb3ef9782600560be48228c91cfb8f5ff87d/gfirefly/gfirefly/netconnect/datapack.py#L63-L83
9miao/G-Firefly
8fbeeb3ef9782600560be48228c91cfb8f5ff87d
gfirefly/gfirefly/netconnect/datapack.py
python
DataPackProtoc.pack
(self,command,response)
return data
打包数据包
打包数据包
[ "打包数据包" ]
def pack(self,command,response): '''打包数据包 ''' HEAD_0 = chr(self.HEAD_0) HEAD_1 = chr(self.HEAD_1) HEAD_2 = chr(self.HEAD_2) HEAD_3 = chr(self.HEAD_3) protoVersion = chr(self.protoVersion) serverVersion = self.serverVersion length = response.__len__()+4 commandID = command data = struct.pack('!sssss3I',HEAD_0,HEAD_1,HEAD_2,HEAD_3,\ protoVersion,serverVersion,length,commandID) data = data + response return data
[ "def", "pack", "(", "self", ",", "command", ",", "response", ")", ":", "HEAD_0", "=", "chr", "(", "self", ".", "HEAD_0", ")", "HEAD_1", "=", "chr", "(", "self", ".", "HEAD_1", ")", "HEAD_2", "=", "chr", "(", "self", ".", "HEAD_2", ")", "HEAD_3", "=", "chr", "(", "self", ".", "HEAD_3", ")", "protoVersion", "=", "chr", "(", "self", ".", "protoVersion", ")", "serverVersion", "=", "self", ".", "serverVersion", "length", "=", "response", ".", "__len__", "(", ")", "+", "4", "commandID", "=", "command", "data", "=", "struct", ".", "pack", "(", "'!sssss3I'", ",", "HEAD_0", ",", "HEAD_1", ",", "HEAD_2", ",", "HEAD_3", ",", "protoVersion", ",", "serverVersion", ",", "length", ",", "commandID", ")", "data", "=", "data", "+", "response", "return", "data" ]
https://github.com/9miao/G-Firefly/blob/8fbeeb3ef9782600560be48228c91cfb8f5ff87d/gfirefly/gfirefly/netconnect/datapack.py#L85-L99
9miao/G-Firefly
8fbeeb3ef9782600560be48228c91cfb8f5ff87d
gfirefly/gfirefly/netconnect/manager.py
python
ConnectionManager.__init__
(self)
初始化 @param _connections: dict {connID:conn Object}
初始化
[ "初始化" ]
def __init__(self): '''初始化 @param _connections: dict {connID:conn Object} ''' self._connections = {}
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "_connections", "=", "{", "}" ]
https://github.com/9miao/G-Firefly/blob/8fbeeb3ef9782600560be48228c91cfb8f5ff87d/gfirefly/gfirefly/netconnect/manager.py#L17-L21
9miao/G-Firefly
8fbeeb3ef9782600560be48228c91cfb8f5ff87d
gfirefly/gfirefly/netconnect/manager.py
python
ConnectionManager.getNowConnCnt
(self)
return len(self._connections.items())
获取当前连接数量
获取当前连接数量
[ "获取当前连接数量" ]
def getNowConnCnt(self): '''获取当前连接数量''' return len(self._connections.items())
[ "def", "getNowConnCnt", "(", "self", ")", ":", "return", "len", "(", "self", ".", "_connections", ".", "items", "(", ")", ")" ]
https://github.com/9miao/G-Firefly/blob/8fbeeb3ef9782600560be48228c91cfb8f5ff87d/gfirefly/gfirefly/netconnect/manager.py#L23-L25
9miao/G-Firefly
8fbeeb3ef9782600560be48228c91cfb8f5ff87d
gfirefly/gfirefly/netconnect/manager.py
python
ConnectionManager.addConnection
(self, conn)
加入一条连接 @param _conn: Conn object
加入一条连接
[ "加入一条连接" ]
def addConnection(self, conn): '''加入一条连接 @param _conn: Conn object ''' _conn = Connection(conn) if self._connections.has_key(_conn.id): raise Exception("系统记录冲突") self._connections[_conn.id] = _conn
[ "def", "addConnection", "(", "self", ",", "conn", ")", ":", "_conn", "=", "Connection", "(", "conn", ")", "if", "self", ".", "_connections", ".", "has_key", "(", "_conn", ".", "id", ")", ":", "raise", "Exception", "(", "\"系统记录冲突\")", "", "self", ".", "_connections", "[", "_conn", ".", "id", "]", "=", "_conn" ]
https://github.com/9miao/G-Firefly/blob/8fbeeb3ef9782600560be48228c91cfb8f5ff87d/gfirefly/gfirefly/netconnect/manager.py#L27-L34
9miao/G-Firefly
8fbeeb3ef9782600560be48228c91cfb8f5ff87d
gfirefly/gfirefly/netconnect/manager.py
python
ConnectionManager.dropConnectionByID
(self, connID)
更加连接的id删除连接实例 @param connID: int 连接的id
更加连接的id删除连接实例
[ "更加连接的id删除连接实例" ]
def dropConnectionByID(self, connID): '''更加连接的id删除连接实例 @param connID: int 连接的id ''' try: del self._connections[connID] except Exception as e: log.msg(str(e))
[ "def", "dropConnectionByID", "(", "self", ",", "connID", ")", ":", "try", ":", "del", "self", ".", "_connections", "[", "connID", "]", "except", "Exception", "as", "e", ":", "log", ".", "msg", "(", "str", "(", "e", ")", ")" ]
https://github.com/9miao/G-Firefly/blob/8fbeeb3ef9782600560be48228c91cfb8f5ff87d/gfirefly/gfirefly/netconnect/manager.py#L36-L43
9miao/G-Firefly
8fbeeb3ef9782600560be48228c91cfb8f5ff87d
gfirefly/gfirefly/netconnect/manager.py
python
ConnectionManager.getConnectionByID
(self, connID)
return self._connections.get(connID,None)
根据ID获取一条连接 @param connID: int 连接的id
根据ID获取一条连接
[ "根据ID获取一条连接" ]
def getConnectionByID(self, connID): """根据ID获取一条连接 @param connID: int 连接的id """ return self._connections.get(connID,None)
[ "def", "getConnectionByID", "(", "self", ",", "connID", ")", ":", "return", "self", ".", "_connections", ".", "get", "(", "connID", ",", "None", ")" ]
https://github.com/9miao/G-Firefly/blob/8fbeeb3ef9782600560be48228c91cfb8f5ff87d/gfirefly/gfirefly/netconnect/manager.py#L45-L49
9miao/G-Firefly
8fbeeb3ef9782600560be48228c91cfb8f5ff87d
gfirefly/gfirefly/netconnect/manager.py
python
ConnectionManager.loseConnection
(self,connID)
根据连接ID主动端口与客户端的连接
根据连接ID主动端口与客户端的连接
[ "根据连接ID主动端口与客户端的连接" ]
def loseConnection(self,connID): """根据连接ID主动端口与客户端的连接 """ conn = self.getConnectionByID(connID) if conn: conn.loseConnection() self.dropConnectionByID(connID)
[ "def", "loseConnection", "(", "self", ",", "connID", ")", ":", "conn", "=", "self", ".", "getConnectionByID", "(", "connID", ")", "if", "conn", ":", "conn", ".", "loseConnection", "(", ")", "self", ".", "dropConnectionByID", "(", "connID", ")" ]
https://github.com/9miao/G-Firefly/blob/8fbeeb3ef9782600560be48228c91cfb8f5ff87d/gfirefly/gfirefly/netconnect/manager.py#L51-L57
9miao/G-Firefly
8fbeeb3ef9782600560be48228c91cfb8f5ff87d
gfirefly/gfirefly/netconnect/manager.py
python
ConnectionManager.pushObject
(self,topicID , msg, sendList)
主动推送消息
主动推送消息
[ "主动推送消息" ]
def pushObject(self,topicID , msg, sendList): """主动推送消息 """ for target in sendList: try: conn = self.getConnectionByID(target) if conn: conn.safeToWriteData(topicID,msg) except Exception,e: log.err(e,traceback.format_exc())
[ "def", "pushObject", "(", "self", ",", "topicID", ",", "msg", ",", "sendList", ")", ":", "for", "target", "in", "sendList", ":", "try", ":", "conn", "=", "self", ".", "getConnectionByID", "(", "target", ")", "if", "conn", ":", "conn", ".", "safeToWriteData", "(", "topicID", ",", "msg", ")", "except", "Exception", ",", "e", ":", "log", ".", "err", "(", "e", ",", "traceback", ".", "format_exc", "(", ")", ")" ]
https://github.com/9miao/G-Firefly/blob/8fbeeb3ef9782600560be48228c91cfb8f5ff87d/gfirefly/gfirefly/netconnect/manager.py#L59-L68
9miao/G-Firefly
8fbeeb3ef9782600560be48228c91cfb8f5ff87d
gfirefly/gfirefly/netconnect/protoc.py
python
LiberateProtocol.connectionMade
(self)
连接建立处理
连接建立处理
[ "连接建立处理" ]
def connectionMade(self): '''连接建立处理 ''' address = self.transport.getAddress() log.msg('Client %d login in.[%s,%d]'%(self.transport.sessionno,\ address[0],address[1])) self.factory.connmanager.addConnection(self) self.factory.doConnectionMade(self)
[ "def", "connectionMade", "(", "self", ")", ":", "address", "=", "self", ".", "transport", ".", "getAddress", "(", ")", "log", ".", "msg", "(", "'Client %d login in.[%s,%d]'", "%", "(", "self", ".", "transport", ".", "sessionno", ",", "address", "[", "0", "]", ",", "address", "[", "1", "]", ")", ")", "self", ".", "factory", ".", "connmanager", ".", "addConnection", "(", "self", ")", "self", ".", "factory", ".", "doConnectionMade", "(", "self", ")" ]
https://github.com/9miao/G-Firefly/blob/8fbeeb3ef9782600560be48228c91cfb8f5ff87d/gfirefly/gfirefly/netconnect/protoc.py#L18-L25
9miao/G-Firefly
8fbeeb3ef9782600560be48228c91cfb8f5ff87d
gfirefly/gfirefly/netconnect/protoc.py
python
LiberateProtocol.connectionLost
(self,reason)
连接断开处理
连接断开处理
[ "连接断开处理" ]
def connectionLost(self,reason): '''连接断开处理 ''' log.msg('Client %d login out.'%(self.transport.sessionno)) self.factory.doConnectionLost(self) self.factory.connmanager.dropConnectionByID(self.transport.sessionno)
[ "def", "connectionLost", "(", "self", ",", "reason", ")", ":", "log", ".", "msg", "(", "'Client %d login out.'", "%", "(", "self", ".", "transport", ".", "sessionno", ")", ")", "self", ".", "factory", ".", "doConnectionLost", "(", "self", ")", "self", ".", "factory", ".", "connmanager", ".", "dropConnectionByID", "(", "self", ".", "transport", ".", "sessionno", ")" ]
https://github.com/9miao/G-Firefly/blob/8fbeeb3ef9782600560be48228c91cfb8f5ff87d/gfirefly/gfirefly/netconnect/protoc.py#L27-L32
9miao/G-Firefly
8fbeeb3ef9782600560be48228c91cfb8f5ff87d
gfirefly/gfirefly/netconnect/protoc.py
python
LiberateProtocol.safeToWriteData
(self,data,command)
线程安全的向客户端发送数据 @param data: str 要向客户端写的数据
线程安全的向客户端发送数据
[ "线程安全的向客户端发送数据" ]
def safeToWriteData(self,data,command): '''线程安全的向客户端发送数据 @param data: str 要向客户端写的数据 ''' if data is None: return senddata = self.factory.produceResult(command,data) self.transport.sendall(senddata)
[ "def", "safeToWriteData", "(", "self", ",", "data", ",", "command", ")", ":", "if", "data", "is", "None", ":", "return", "senddata", "=", "self", ".", "factory", ".", "produceResult", "(", "command", ",", "data", ")", "self", ".", "transport", ".", "sendall", "(", "senddata", ")" ]
https://github.com/9miao/G-Firefly/blob/8fbeeb3ef9782600560be48228c91cfb8f5ff87d/gfirefly/gfirefly/netconnect/protoc.py#L34-L41
9miao/G-Firefly
8fbeeb3ef9782600560be48228c91cfb8f5ff87d
gfirefly/gfirefly/netconnect/protoc.py
python
LiberateProtocol.dataReceived
(self, data)
数据到达处理 @param data: str 客户端传送过来的数据
数据到达处理
[ "数据到达处理" ]
def dataReceived(self, data): '''数据到达处理 @param data: str 客户端传送过来的数据 ''' length = self.factory.dataprotocl.getHeadlength()#获取协议头的长度 self.buff += data while self.buff.__len__() >= length: unpackdata = self.factory.dataprotocl.unpack(self.buff[:length]) if not unpackdata.get('result'): log.msg('illegal data package --') self.factory.connmanager.loseConnection(self.transport.sessionno) break command = unpackdata.get('command') rlength = unpackdata.get('length') request = self.buff[length:length+rlength] if request.__len__()< rlength: log.msg('some data lose') break self.buff = self.buff[length+rlength:] response = self.factory.doDataReceived(self,command,request) if not response: continue self.safeToWriteData(response, command)
[ "def", "dataReceived", "(", "self", ",", "data", ")", ":", "length", "=", "self", ".", "factory", ".", "dataprotocl", ".", "getHeadlength", "(", ")", "#获取协议头的长度", "self", ".", "buff", "+=", "data", "while", "self", ".", "buff", ".", "__len__", "(", ")", ">=", "length", ":", "unpackdata", "=", "self", ".", "factory", ".", "dataprotocl", ".", "unpack", "(", "self", ".", "buff", "[", ":", "length", "]", ")", "if", "not", "unpackdata", ".", "get", "(", "'result'", ")", ":", "log", ".", "msg", "(", "'illegal data package --'", ")", "self", ".", "factory", ".", "connmanager", ".", "loseConnection", "(", "self", ".", "transport", ".", "sessionno", ")", "break", "command", "=", "unpackdata", ".", "get", "(", "'command'", ")", "rlength", "=", "unpackdata", ".", "get", "(", "'length'", ")", "request", "=", "self", ".", "buff", "[", "length", ":", "length", "+", "rlength", "]", "if", "request", ".", "__len__", "(", ")", "<", "rlength", ":", "log", ".", "msg", "(", "'some data lose'", ")", "break", "self", ".", "buff", "=", "self", ".", "buff", "[", "length", "+", "rlength", ":", "]", "response", "=", "self", ".", "factory", ".", "doDataReceived", "(", "self", ",", "command", ",", "request", ")", "if", "not", "response", ":", "continue", "self", ".", "safeToWriteData", "(", "response", ",", "command", ")" ]
https://github.com/9miao/G-Firefly/blob/8fbeeb3ef9782600560be48228c91cfb8f5ff87d/gfirefly/gfirefly/netconnect/protoc.py#L43-L66
9miao/G-Firefly
8fbeeb3ef9782600560be48228c91cfb8f5ff87d
gfirefly/gfirefly/netconnect/protoc.py
python
LiberateFactory.__init__
(self,dataprotocl=DataPackProtoc())
初始化
初始化
[ "初始化" ]
def __init__(self,dataprotocl=DataPackProtoc()): '''初始化 ''' protocols.ServerFactory.__init__(self) self.service = None self.connmanager = ConnectionManager() self.dataprotocl = dataprotocl
[ "def", "__init__", "(", "self", ",", "dataprotocl", "=", "DataPackProtoc", "(", ")", ")", ":", "protocols", ".", "ServerFactory", ".", "__init__", "(", "self", ")", "self", ".", "service", "=", "None", "self", ".", "connmanager", "=", "ConnectionManager", "(", ")", "self", ".", "dataprotocl", "=", "dataprotocl" ]
https://github.com/9miao/G-Firefly/blob/8fbeeb3ef9782600560be48228c91cfb8f5ff87d/gfirefly/gfirefly/netconnect/protoc.py#L73-L79
9miao/G-Firefly
8fbeeb3ef9782600560be48228c91cfb8f5ff87d
gfirefly/gfirefly/netconnect/protoc.py
python
LiberateFactory.doConnectionMade
(self,conn)
当连接建立时的处理
当连接建立时的处理
[ "当连接建立时的处理" ]
def doConnectionMade(self,conn): '''当连接建立时的处理''' pass
[ "def", "doConnectionMade", "(", "self", ",", "conn", ")", ":", "pass" ]
https://github.com/9miao/G-Firefly/blob/8fbeeb3ef9782600560be48228c91cfb8f5ff87d/gfirefly/gfirefly/netconnect/protoc.py#L86-L88
9miao/G-Firefly
8fbeeb3ef9782600560be48228c91cfb8f5ff87d
gfirefly/gfirefly/netconnect/protoc.py
python
LiberateFactory.doConnectionLost
(self,conn)
连接断开时的处理
连接断开时的处理
[ "连接断开时的处理" ]
def doConnectionLost(self,conn): '''连接断开时的处理''' pass
[ "def", "doConnectionLost", "(", "self", ",", "conn", ")", ":", "pass" ]
https://github.com/9miao/G-Firefly/blob/8fbeeb3ef9782600560be48228c91cfb8f5ff87d/gfirefly/gfirefly/netconnect/protoc.py#L90-L92
9miao/G-Firefly
8fbeeb3ef9782600560be48228c91cfb8f5ff87d
gfirefly/gfirefly/netconnect/protoc.py
python
LiberateFactory.addServiceChannel
(self,service)
添加服务通道
添加服务通道
[ "添加服务通道" ]
def addServiceChannel(self,service): '''添加服务通道''' self.service = service
[ "def", "addServiceChannel", "(", "self", ",", "service", ")", ":", "self", ".", "service", "=", "service" ]
https://github.com/9miao/G-Firefly/blob/8fbeeb3ef9782600560be48228c91cfb8f5ff87d/gfirefly/gfirefly/netconnect/protoc.py#L94-L96
9miao/G-Firefly
8fbeeb3ef9782600560be48228c91cfb8f5ff87d
gfirefly/gfirefly/netconnect/protoc.py
python
LiberateFactory.doDataReceived
(self,conn,commandID,data)
return response
数据到达时的处理
数据到达时的处理
[ "数据到达时的处理" ]
def doDataReceived(self,conn,commandID,data): '''数据到达时的处理''' response = self.service.callTarget(commandID,conn,data) return response
[ "def", "doDataReceived", "(", "self", ",", "conn", ",", "commandID", ",", "data", ")", ":", "response", "=", "self", ".", "service", ".", "callTarget", "(", "commandID", ",", "conn", ",", "data", ")", "return", "response" ]
https://github.com/9miao/G-Firefly/blob/8fbeeb3ef9782600560be48228c91cfb8f5ff87d/gfirefly/gfirefly/netconnect/protoc.py#L98-L101
9miao/G-Firefly
8fbeeb3ef9782600560be48228c91cfb8f5ff87d
gfirefly/gfirefly/netconnect/protoc.py
python
LiberateFactory.produceResult
(self,command,response)
return self.dataprotocl.pack(command,response)
产生客户端需要的最终结果 @param response: str 分布式客户端获取的结果
产生客户端需要的最终结果
[ "产生客户端需要的最终结果" ]
def produceResult(self,command,response): '''产生客户端需要的最终结果 @param response: str 分布式客户端获取的结果 ''' return self.dataprotocl.pack(command,response)
[ "def", "produceResult", "(", "self", ",", "command", ",", "response", ")", ":", "return", "self", ".", "dataprotocl", ".", "pack", "(", "command", ",", "response", ")" ]
https://github.com/9miao/G-Firefly/blob/8fbeeb3ef9782600560be48228c91cfb8f5ff87d/gfirefly/gfirefly/netconnect/protoc.py#L103-L107
9miao/G-Firefly
8fbeeb3ef9782600560be48228c91cfb8f5ff87d
gfirefly/gfirefly/netconnect/protoc.py
python
LiberateFactory.loseConnection
(self,connID)
主动端口与客户端的连接
主动端口与客户端的连接
[ "主动端口与客户端的连接" ]
def loseConnection(self,connID): """主动端口与客户端的连接 """ self.connmanager.loseConnection(connID)
[ "def", "loseConnection", "(", "self", ",", "connID", ")", ":", "self", ".", "connmanager", ".", "loseConnection", "(", "connID", ")" ]
https://github.com/9miao/G-Firefly/blob/8fbeeb3ef9782600560be48228c91cfb8f5ff87d/gfirefly/gfirefly/netconnect/protoc.py#L109-L112
9miao/G-Firefly
8fbeeb3ef9782600560be48228c91cfb8f5ff87d
gfirefly/gfirefly/netconnect/protoc.py
python
LiberateFactory.pushObject
(self,topicID , msg, sendList)
服务端向客户端推消息 @param topicID: int 消息的主题id号 @param msg: 消息的类容,protobuf结构类型 @param sendList: 推向的目标列表(客户端id 列表)
服务端向客户端推消息
[ "服务端向客户端推消息" ]
def pushObject(self,topicID , msg, sendList): '''服务端向客户端推消息 @param topicID: int 消息的主题id号 @param msg: 消息的类容,protobuf结构类型 @param sendList: 推向的目标列表(客户端id 列表) ''' self.connmanager.pushObject(topicID, msg, sendList)
[ "def", "pushObject", "(", "self", ",", "topicID", ",", "msg", ",", "sendList", ")", ":", "self", ".", "connmanager", ".", "pushObject", "(", "topicID", ",", "msg", ",", "sendList", ")" ]
https://github.com/9miao/G-Firefly/blob/8fbeeb3ef9782600560be48228c91cfb8f5ff87d/gfirefly/gfirefly/netconnect/protoc.py#L114-L120
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/utils.py
python
logits_to_log_prob
(logits)
return log_probs
Computes log probabilities using numerically stable trick. This uses two numerical stability tricks: 1) softmax(x) = softmax(x - c) where c is a constant applied to all arguments. If we set c = max(x) then the softmax is more numerically stable. 2) log softmax(x) is not numerically stable, but we can stabilize it by using the identity log softmax(x) = x - log sum exp(x) Args: logits: Tensor of arbitrary shape whose last dimension contains logits. Returns: A tensor of the same shape as the input, but with corresponding log probabilities.
Computes log probabilities using numerically stable trick.
[ "Computes", "log", "probabilities", "using", "numerically", "stable", "trick", "." ]
def logits_to_log_prob(logits): """Computes log probabilities using numerically stable trick. This uses two numerical stability tricks: 1) softmax(x) = softmax(x - c) where c is a constant applied to all arguments. If we set c = max(x) then the softmax is more numerically stable. 2) log softmax(x) is not numerically stable, but we can stabilize it by using the identity log softmax(x) = x - log sum exp(x) Args: logits: Tensor of arbitrary shape whose last dimension contains logits. Returns: A tensor of the same shape as the input, but with corresponding log probabilities. """ with tf.variable_scope('log_probabilities'): reduction_indices = len(logits.shape.as_list()) - 1 max_logits = tf.reduce_max( logits, reduction_indices=reduction_indices, keep_dims=True) safe_logits = tf.subtract(logits, max_logits) sum_exp = tf.reduce_sum( tf.exp(safe_logits), reduction_indices=reduction_indices, keep_dims=True) log_probs = tf.subtract(safe_logits, tf.log(sum_exp)) return log_probs
[ "def", "logits_to_log_prob", "(", "logits", ")", ":", "with", "tf", ".", "variable_scope", "(", "'log_probabilities'", ")", ":", "reduction_indices", "=", "len", "(", "logits", ".", "shape", ".", "as_list", "(", ")", ")", "-", "1", "max_logits", "=", "tf", ".", "reduce_max", "(", "logits", ",", "reduction_indices", "=", "reduction_indices", ",", "keep_dims", "=", "True", ")", "safe_logits", "=", "tf", ".", "subtract", "(", "logits", ",", "max_logits", ")", "sum_exp", "=", "tf", ".", "reduce_sum", "(", "tf", ".", "exp", "(", "safe_logits", ")", ",", "reduction_indices", "=", "reduction_indices", ",", "keep_dims", "=", "True", ")", "log_probs", "=", "tf", ".", "subtract", "(", "safe_logits", ",", "tf", ".", "log", "(", "sum_exp", ")", ")", "return", "log_probs" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/utils.py#L22-L50
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/utils.py
python
variables_to_restore
(scope=None, strip_scope=False)
Returns a list of variables to restore for the specified list of methods. It is supposed that variable name starts with the method's scope (a prefix returned by _method_scope function). Args: methods_names: a list of names of configurable methods. strip_scope: if True will return variable names without method's scope. If methods_names is None will return names unchanged. model_scope: a scope for a whole model. Returns: a dictionary mapping variable names to variables for restore.
Returns a list of variables to restore for the specified list of methods.
[ "Returns", "a", "list", "of", "variables", "to", "restore", "for", "the", "specified", "list", "of", "methods", "." ]
def variables_to_restore(scope=None, strip_scope=False): """Returns a list of variables to restore for the specified list of methods. It is supposed that variable name starts with the method's scope (a prefix returned by _method_scope function). Args: methods_names: a list of names of configurable methods. strip_scope: if True will return variable names without method's scope. If methods_names is None will return names unchanged. model_scope: a scope for a whole model. Returns: a dictionary mapping variable names to variables for restore. """ if scope: variable_map = {} method_variables = slim.get_variables_to_restore(include=[scope]) for var in method_variables: if strip_scope: var_name = var.op.name[len(scope) + 1:] else: var_name = var.op.name variable_map[var_name] = var return variable_map else: return {v.op.name: v for v in slim.get_variables_to_restore()}
[ "def", "variables_to_restore", "(", "scope", "=", "None", ",", "strip_scope", "=", "False", ")", ":", "if", "scope", ":", "variable_map", "=", "{", "}", "method_variables", "=", "slim", ".", "get_variables_to_restore", "(", "include", "=", "[", "scope", "]", ")", "for", "var", "in", "method_variables", ":", "if", "strip_scope", ":", "var_name", "=", "var", ".", "op", ".", "name", "[", "len", "(", "scope", ")", "+", "1", ":", "]", "else", ":", "var_name", "=", "var", ".", "op", ".", "name", "variable_map", "[", "var_name", "]", "=", "var", "return", "variable_map", "else", ":", "return", "{", "v", ".", "op", ".", "name", ":", "v", "for", "v", "in", "slim", ".", "get_variables_to_restore", "(", ")", "}" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/utils.py#L53-L80
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/common_flags.py
python
define
()
Define common flags.
Define common flags.
[ "Define", "common", "flags", "." ]
def define(): """Define common flags.""" # yapf: disable flags.DEFINE_integer('batch_size', 32, 'Batch size.') flags.DEFINE_integer('crop_width', None, 'Width of the central crop for images.') flags.DEFINE_integer('crop_height', None, 'Height of the central crop for images.') flags.DEFINE_string('train_log_dir', '/home/ucmed/opt/python/models-master/research/attention_ocr/python/logs', 'Directory where to write event logs.') flags.DEFINE_string('dataset_name', 'fsns', 'Name of the dataset. Supported: fsns') flags.DEFINE_string('split_name', 'train', 'Dataset split name to run evaluation for: test,train.') flags.DEFINE_string('dataset_dir', None, 'Dataset root folder.') flags.DEFINE_string('checkpoint', '', 'Path for checkpoint to restore weights from.') flags.DEFINE_string('master', '', 'BNS name of the TensorFlow master to use.') # Model hyper parameters flags.DEFINE_float('learning_rate', 0.004, 'learning rate') flags.DEFINE_string('optimizer', 'momentum', 'the optimizer to use') flags.DEFINE_string('momentum', 0.9, 'momentum value for the momentum optimizer if used') flags.DEFINE_bool('use_augment_input', True, 'If True will use image augmentation') # Method hyper parameters # conv_tower_fn flags.DEFINE_string('final_endpoint', 'Mixed_5d', 'Endpoint to cut inception tower') # sequence_logit_fn flags.DEFINE_bool('use_attention', True, 'If True will use the attention mechanism') flags.DEFINE_bool('use_autoregression', True, 'If True will use autoregression (a feedback link)') flags.DEFINE_integer('num_lstm_units', 256, 'number of LSTM units for sequence LSTM') flags.DEFINE_float('weight_decay', 0.00004, 'weight decay for char prediction FC layers') flags.DEFINE_float('lstm_state_clip_value', 10.0, 'cell state is clipped by this value prior to the cell' ' output activation') # 'sequence_loss_fn' flags.DEFINE_float('label_smoothing', 0.1, 'weight for label smoothing') flags.DEFINE_bool('ignore_nulls', True, 'ignore null characters for computing the loss') flags.DEFINE_bool('average_across_timesteps', False, 'divide the returned cost by the total label weight')
[ "def", "define", "(", ")", ":", "# yapf: disable", "flags", ".", "DEFINE_integer", "(", "'batch_size'", ",", "32", ",", "'Batch size.'", ")", "flags", ".", "DEFINE_integer", "(", "'crop_width'", ",", "None", ",", "'Width of the central crop for images.'", ")", "flags", ".", "DEFINE_integer", "(", "'crop_height'", ",", "None", ",", "'Height of the central crop for images.'", ")", "flags", ".", "DEFINE_string", "(", "'train_log_dir'", ",", "'/home/ucmed/opt/python/models-master/research/attention_ocr/python/logs'", ",", "'Directory where to write event logs.'", ")", "flags", ".", "DEFINE_string", "(", "'dataset_name'", ",", "'fsns'", ",", "'Name of the dataset. Supported: fsns'", ")", "flags", ".", "DEFINE_string", "(", "'split_name'", ",", "'train'", ",", "'Dataset split name to run evaluation for: test,train.'", ")", "flags", ".", "DEFINE_string", "(", "'dataset_dir'", ",", "None", ",", "'Dataset root folder.'", ")", "flags", ".", "DEFINE_string", "(", "'checkpoint'", ",", "''", ",", "'Path for checkpoint to restore weights from.'", ")", "flags", ".", "DEFINE_string", "(", "'master'", ",", "''", ",", "'BNS name of the TensorFlow master to use.'", ")", "# Model hyper parameters", "flags", ".", "DEFINE_float", "(", "'learning_rate'", ",", "0.004", ",", "'learning rate'", ")", "flags", ".", "DEFINE_string", "(", "'optimizer'", ",", "'momentum'", ",", "'the optimizer to use'", ")", "flags", ".", "DEFINE_string", "(", "'momentum'", ",", "0.9", ",", "'momentum value for the momentum optimizer if used'", ")", "flags", ".", "DEFINE_bool", "(", "'use_augment_input'", ",", "True", ",", "'If True will use image augmentation'", ")", "# Method hyper parameters", "# conv_tower_fn", "flags", ".", "DEFINE_string", "(", "'final_endpoint'", ",", "'Mixed_5d'", ",", "'Endpoint to cut inception tower'", ")", "# sequence_logit_fn", "flags", ".", "DEFINE_bool", "(", "'use_attention'", ",", "True", ",", "'If True will use the attention mechanism'", ")", "flags", ".", "DEFINE_bool", "(", "'use_autoregression'", ",", "True", ",", "'If True will use autoregression (a feedback link)'", ")", "flags", ".", "DEFINE_integer", "(", "'num_lstm_units'", ",", "256", ",", "'number of LSTM units for sequence LSTM'", ")", "flags", ".", "DEFINE_float", "(", "'weight_decay'", ",", "0.00004", ",", "'weight decay for char prediction FC layers'", ")", "flags", ".", "DEFINE_float", "(", "'lstm_state_clip_value'", ",", "10.0", ",", "'cell state is clipped by this value prior to the cell'", "' output activation'", ")", "# 'sequence_loss_fn'", "flags", ".", "DEFINE_float", "(", "'label_smoothing'", ",", "0.1", ",", "'weight for label smoothing'", ")", "flags", ".", "DEFINE_bool", "(", "'ignore_nulls'", ",", "True", ",", "'ignore null characters for computing the loss'", ")", "flags", ".", "DEFINE_bool", "(", "'average_across_timesteps'", ",", "False", ",", "'divide the returned cost by the total label weight'", ")" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/common_flags.py#L38-L112
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/model.py
python
get_softmax_loss_fn
(label_smoothing)
return loss_fn
Returns sparse or dense loss function depending on the label_smoothing. Args: label_smoothing: weight for label smoothing Returns: a function which takes labels and predictions as arguments and returns a softmax loss for the selected type of labels (sparse or dense).
Returns sparse or dense loss function depending on the label_smoothing.
[ "Returns", "sparse", "or", "dense", "loss", "function", "depending", "on", "the", "label_smoothing", "." ]
def get_softmax_loss_fn(label_smoothing): """Returns sparse or dense loss function depending on the label_smoothing. Args: label_smoothing: weight for label smoothing Returns: a function which takes labels and predictions as arguments and returns a softmax loss for the selected type of labels (sparse or dense). """ if label_smoothing > 0: def loss_fn(labels, logits): return (tf.nn.softmax_cross_entropy_with_logits( logits=logits, labels=labels)) else: def loss_fn(labels, logits): return tf.nn.sparse_softmax_cross_entropy_with_logits( logits=logits, labels=labels) return loss_fn
[ "def", "get_softmax_loss_fn", "(", "label_smoothing", ")", ":", "if", "label_smoothing", ">", "0", ":", "def", "loss_fn", "(", "labels", ",", "logits", ")", ":", "return", "(", "tf", ".", "nn", ".", "softmax_cross_entropy_with_logits", "(", "logits", "=", "logits", ",", "labels", "=", "labels", ")", ")", "else", ":", "def", "loss_fn", "(", "labels", ",", "logits", ")", ":", "return", "tf", ".", "nn", ".", "sparse_softmax_cross_entropy_with_logits", "(", "logits", "=", "logits", ",", "labels", "=", "labels", ")", "return", "loss_fn" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/model.py#L100-L121
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/model.py
python
CharsetMapper.__init__
(self, charset, default_character='?')
Creates a lookup table. Args: charset: a dictionary with id-to-character mapping.
Creates a lookup table.
[ "Creates", "a", "lookup", "table", "." ]
def __init__(self, charset, default_character='?'): """Creates a lookup table. Args: charset: a dictionary with id-to-character mapping. """ mapping_strings = tf.constant(_dict_to_array(charset, default_character)) self.table = tf.contrib.lookup.index_to_string_table_from_tensor( mapping=mapping_strings, default_value=default_character)
[ "def", "__init__", "(", "self", ",", "charset", ",", "default_character", "=", "'?'", ")", ":", "mapping_strings", "=", "tf", ".", "constant", "(", "_dict_to_array", "(", "charset", ",", "default_character", ")", ")", "self", ".", "table", "=", "tf", ".", "contrib", ".", "lookup", ".", "index_to_string_table_from_tensor", "(", "mapping", "=", "mapping_strings", ",", "default_value", "=", "default_character", ")" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/model.py#L80-L88
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/model.py
python
CharsetMapper.get_text
(self, ids)
return tf.reduce_join( self.table.lookup(tf.to_int64(ids)), reduction_indices=1)
Returns a string corresponding to a sequence of character ids. Args: ids: a tensor with shape [batch_size, max_sequence_length]
Returns a string corresponding to a sequence of character ids.
[ "Returns", "a", "string", "corresponding", "to", "a", "sequence", "of", "character", "ids", "." ]
def get_text(self, ids): """Returns a string corresponding to a sequence of character ids. Args: ids: a tensor with shape [batch_size, max_sequence_length] """ return tf.reduce_join( self.table.lookup(tf.to_int64(ids)), reduction_indices=1)
[ "def", "get_text", "(", "self", ",", "ids", ")", ":", "return", "tf", ".", "reduce_join", "(", "self", ".", "table", ".", "lookup", "(", "tf", ".", "to_int64", "(", "ids", ")", ")", ",", "reduction_indices", "=", "1", ")" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/model.py#L90-L97
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/model.py
python
Model.__init__
(self, num_char_classes, seq_length, num_views, null_code, mparams=None, charset=None)
Initialized model parameters. Args: num_char_classes: size of character set. seq_length: number of characters in a sequence. num_views: Number of views (conv towers) to use. null_code: A character code corresponding to a character which indicates end of a sequence. mparams: a dictionary with hyper parameters for methods, keys - function names, values - corresponding namedtuples. charset: an optional dictionary with a mapping between character ids and utf8 strings. If specified the OutputEndpoints.predicted_text will utf8 encoded strings corresponding to the character ids returned by OutputEndpoints.predicted_chars (by default the predicted_text contains an empty vector). NOTE: Make sure you call tf.tables_initializer().run() if the charset specified.
Initialized model parameters.
[ "Initialized", "model", "parameters", "." ]
def __init__(self, num_char_classes, seq_length, num_views, null_code, mparams=None, charset=None): """Initialized model parameters. Args: num_char_classes: size of character set. seq_length: number of characters in a sequence. num_views: Number of views (conv towers) to use. null_code: A character code corresponding to a character which indicates end of a sequence. mparams: a dictionary with hyper parameters for methods, keys - function names, values - corresponding namedtuples. charset: an optional dictionary with a mapping between character ids and utf8 strings. If specified the OutputEndpoints.predicted_text will utf8 encoded strings corresponding to the character ids returned by OutputEndpoints.predicted_chars (by default the predicted_text contains an empty vector). NOTE: Make sure you call tf.tables_initializer().run() if the charset specified. """ super(Model, self).__init__() self._params = ModelParams( num_char_classes=num_char_classes, seq_length=seq_length, num_views=num_views, null_code=null_code) self._mparams = self.default_mparams() if mparams: self._mparams.update(mparams) self._charset = charset
[ "def", "__init__", "(", "self", ",", "num_char_classes", ",", "seq_length", ",", "num_views", ",", "null_code", ",", "mparams", "=", "None", ",", "charset", "=", "None", ")", ":", "super", "(", "Model", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "_params", "=", "ModelParams", "(", "num_char_classes", "=", "num_char_classes", ",", "seq_length", "=", "seq_length", ",", "num_views", "=", "num_views", ",", "null_code", "=", "null_code", ")", "self", ".", "_mparams", "=", "self", ".", "default_mparams", "(", ")", "if", "mparams", ":", "self", ".", "_mparams", ".", "update", "(", "mparams", ")", "self", ".", "_charset", "=", "charset" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/model.py#L127-L161
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/model.py
python
Model.conv_tower_fn
(self, images, is_training=True, reuse=None)
Computes convolutional features using the InceptionV3 model. Args: images: A tensor of shape [batch_size, height, width, channels]. is_training: whether is training or not. reuse: whether or not the network and its variables should be reused. To be able to reuse 'scope' must be given. Returns: A tensor of shape [batch_size, OH, OW, N], where OWxOH is resolution of output feature map and N is number of output features (depends on the network architecture).
Computes convolutional features using the InceptionV3 model.
[ "Computes", "convolutional", "features", "using", "the", "InceptionV3", "model", "." ]
def conv_tower_fn(self, images, is_training=True, reuse=None): """Computes convolutional features using the InceptionV3 model. Args: images: A tensor of shape [batch_size, height, width, channels]. is_training: whether is training or not. reuse: whether or not the network and its variables should be reused. To be able to reuse 'scope' must be given. Returns: A tensor of shape [batch_size, OH, OW, N], where OWxOH is resolution of output feature map and N is number of output features (depends on the network architecture). """ mparams = self._mparams['conv_tower_fn'] logging.debug('Using final_endpoint=%s', mparams.final_endpoint) with tf.variable_scope('conv_tower_fn/INCE'): if reuse: tf.get_variable_scope().reuse_variables() with slim.arg_scope(inception.inception_v3_arg_scope()): with slim.arg_scope([slim.batch_norm, slim.dropout], is_training=is_training): net, _ = inception.inception_v3_base( images, final_endpoint=mparams.final_endpoint) return net
[ "def", "conv_tower_fn", "(", "self", ",", "images", ",", "is_training", "=", "True", ",", "reuse", "=", "None", ")", ":", "mparams", "=", "self", ".", "_mparams", "[", "'conv_tower_fn'", "]", "logging", ".", "debug", "(", "'Using final_endpoint=%s'", ",", "mparams", ".", "final_endpoint", ")", "with", "tf", ".", "variable_scope", "(", "'conv_tower_fn/INCE'", ")", ":", "if", "reuse", ":", "tf", ".", "get_variable_scope", "(", ")", ".", "reuse_variables", "(", ")", "with", "slim", ".", "arg_scope", "(", "inception", ".", "inception_v3_arg_scope", "(", ")", ")", ":", "with", "slim", ".", "arg_scope", "(", "[", "slim", ".", "batch_norm", ",", "slim", ".", "dropout", "]", ",", "is_training", "=", "is_training", ")", ":", "net", ",", "_", "=", "inception", ".", "inception_v3_base", "(", "images", ",", "final_endpoint", "=", "mparams", ".", "final_endpoint", ")", "return", "net" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/model.py#L185-L209
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/model.py
python
Model._create_lstm_inputs
(self, net)
return tf.unstack(net, axis=1)
Splits an input tensor into a list of tensors (features). Args: net: A feature map of shape [batch_size, num_features, feature_size]. Raises: AssertionError: if num_features is less than seq_length. Returns: A list with seq_length tensors of shape [batch_size, feature_size]
Splits an input tensor into a list of tensors (features).
[ "Splits", "an", "input", "tensor", "into", "a", "list", "of", "tensors", "(", "features", ")", "." ]
def _create_lstm_inputs(self, net): """Splits an input tensor into a list of tensors (features). Args: net: A feature map of shape [batch_size, num_features, feature_size]. Raises: AssertionError: if num_features is less than seq_length. Returns: A list with seq_length tensors of shape [batch_size, feature_size] """ num_features = net.get_shape().dims[1].value if num_features < self._params.seq_length: raise AssertionError('Incorrect dimension #1 of input tensor' ' %d should be bigger than %d (shape=%s)' % (num_features, self._params.seq_length, net.get_shape())) elif num_features > self._params.seq_length: logging.warning('Ignoring some features: use %d of %d (shape=%s)', self._params.seq_length, num_features, net.get_shape()) net = tf.slice(net, [0, 0, 0], [-1, self._params.seq_length, -1]) return tf.unstack(net, axis=1)
[ "def", "_create_lstm_inputs", "(", "self", ",", "net", ")", ":", "num_features", "=", "net", ".", "get_shape", "(", ")", ".", "dims", "[", "1", "]", ".", "value", "if", "num_features", "<", "self", ".", "_params", ".", "seq_length", ":", "raise", "AssertionError", "(", "'Incorrect dimension #1 of input tensor'", "' %d should be bigger than %d (shape=%s)'", "%", "(", "num_features", ",", "self", ".", "_params", ".", "seq_length", ",", "net", ".", "get_shape", "(", ")", ")", ")", "elif", "num_features", ">", "self", ".", "_params", ".", "seq_length", ":", "logging", ".", "warning", "(", "'Ignoring some features: use %d of %d (shape=%s)'", ",", "self", ".", "_params", ".", "seq_length", ",", "num_features", ",", "net", ".", "get_shape", "(", ")", ")", "net", "=", "tf", ".", "slice", "(", "net", ",", "[", "0", ",", "0", ",", "0", "]", ",", "[", "-", "1", ",", "self", ".", "_params", ".", "seq_length", ",", "-", "1", "]", ")", "return", "tf", ".", "unstack", "(", "net", ",", "axis", "=", "1", ")" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/model.py#L211-L234
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/model.py
python
Model.max_pool_views
(self, nets_list)
return net
Max pool across all nets in spatial dimensions. Args: nets_list: A list of 4D tensors with identical size. Returns: A tensor with the same size as any input tensors.
Max pool across all nets in spatial dimensions.
[ "Max", "pool", "across", "all", "nets", "in", "spatial", "dimensions", "." ]
def max_pool_views(self, nets_list): """Max pool across all nets in spatial dimensions. Args: nets_list: A list of 4D tensors with identical size. Returns: A tensor with the same size as any input tensors. """ batch_size, height, width, num_features = [ d.value for d in nets_list[0].get_shape().dims ] xy_flat_shape = (batch_size, 1, height * width, num_features) nets_for_merge = [] with tf.variable_scope('max_pool_views', values=nets_list): for net in nets_list: nets_for_merge.append(tf.reshape(net, xy_flat_shape)) merged_net = tf.concat(nets_for_merge, 1) net = slim.max_pool2d( merged_net, kernel_size=[len(nets_list), 1], stride=1) net = tf.reshape(net, (batch_size, height, width, num_features)) return net
[ "def", "max_pool_views", "(", "self", ",", "nets_list", ")", ":", "batch_size", ",", "height", ",", "width", ",", "num_features", "=", "[", "d", ".", "value", "for", "d", "in", "nets_list", "[", "0", "]", ".", "get_shape", "(", ")", ".", "dims", "]", "xy_flat_shape", "=", "(", "batch_size", ",", "1", ",", "height", "*", "width", ",", "num_features", ")", "nets_for_merge", "=", "[", "]", "with", "tf", ".", "variable_scope", "(", "'max_pool_views'", ",", "values", "=", "nets_list", ")", ":", "for", "net", "in", "nets_list", ":", "nets_for_merge", ".", "append", "(", "tf", ".", "reshape", "(", "net", ",", "xy_flat_shape", ")", ")", "merged_net", "=", "tf", ".", "concat", "(", "nets_for_merge", ",", "1", ")", "net", "=", "slim", ".", "max_pool2d", "(", "merged_net", ",", "kernel_size", "=", "[", "len", "(", "nets_list", ")", ",", "1", "]", ",", "stride", "=", "1", ")", "net", "=", "tf", ".", "reshape", "(", "net", ",", "(", "batch_size", ",", "height", ",", "width", ",", "num_features", ")", ")", "return", "net" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/model.py#L245-L266
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/model.py
python
Model.pool_views_fn
(self, nets)
Combines output of multiple convolutional towers into a single tensor. It stacks towers one on top another (in height dim) in a 4x1 grid. The order is arbitrary design choice and shouldn't matter much. Args: nets: list of tensors of shape=[batch_size, height, width, num_features]. Returns: A tensor of shape [batch_size, seq_length, features_size].
Combines output of multiple convolutional towers into a single tensor.
[ "Combines", "output", "of", "multiple", "convolutional", "towers", "into", "a", "single", "tensor", "." ]
def pool_views_fn(self, nets): """Combines output of multiple convolutional towers into a single tensor. It stacks towers one on top another (in height dim) in a 4x1 grid. The order is arbitrary design choice and shouldn't matter much. Args: nets: list of tensors of shape=[batch_size, height, width, num_features]. Returns: A tensor of shape [batch_size, seq_length, features_size]. """ with tf.variable_scope('pool_views_fn/STCK'): net = tf.concat(nets, 1) batch_size = net.get_shape().dims[0].value feature_size = net.get_shape().dims[3].value return tf.reshape(net, [batch_size, -1, feature_size])
[ "def", "pool_views_fn", "(", "self", ",", "nets", ")", ":", "with", "tf", ".", "variable_scope", "(", "'pool_views_fn/STCK'", ")", ":", "net", "=", "tf", ".", "concat", "(", "nets", ",", "1", ")", "batch_size", "=", "net", ".", "get_shape", "(", ")", ".", "dims", "[", "0", "]", ".", "value", "feature_size", "=", "net", ".", "get_shape", "(", ")", ".", "dims", "[", "3", "]", ".", "value", "return", "tf", ".", "reshape", "(", "net", ",", "[", "batch_size", ",", "-", "1", ",", "feature_size", "]", ")" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/model.py#L268-L284
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/model.py
python
Model.char_predictions
(self, chars_logit)
return ids, log_prob, scores
Returns confidence scores (softmax values) for predicted characters. Args: chars_logit: chars logits, a tensor with shape [batch_size x seq_length x num_char_classes] Returns: A tuple (ids, log_prob, scores), where: ids - predicted characters, a int32 tensor with shape [batch_size x seq_length]; log_prob - a log probability of all characters, a float tensor with shape [batch_size, seq_length, num_char_classes]; scores - corresponding confidence scores for characters, a float tensor with shape [batch_size x seq_length].
Returns confidence scores (softmax values) for predicted characters.
[ "Returns", "confidence", "scores", "(", "softmax", "values", ")", "for", "predicted", "characters", "." ]
def char_predictions(self, chars_logit): """Returns confidence scores (softmax values) for predicted characters. Args: chars_logit: chars logits, a tensor with shape [batch_size x seq_length x num_char_classes] Returns: A tuple (ids, log_prob, scores), where: ids - predicted characters, a int32 tensor with shape [batch_size x seq_length]; log_prob - a log probability of all characters, a float tensor with shape [batch_size, seq_length, num_char_classes]; scores - corresponding confidence scores for characters, a float tensor with shape [batch_size x seq_length]. """ log_prob = utils.logits_to_log_prob(chars_logit) ids = tf.to_int32(tf.argmax(log_prob, axis=2), name='predicted_chars') mask = tf.cast( slim.one_hot_encoding(ids, self._params.num_char_classes), tf.bool) all_scores = tf.nn.softmax(chars_logit) selected_scores = tf.boolean_mask(all_scores, mask, name='char_scores') scores = tf.reshape(selected_scores, shape=(-1, self._params.seq_length)) return ids, log_prob, scores
[ "def", "char_predictions", "(", "self", ",", "chars_logit", ")", ":", "log_prob", "=", "utils", ".", "logits_to_log_prob", "(", "chars_logit", ")", "ids", "=", "tf", ".", "to_int32", "(", "tf", ".", "argmax", "(", "log_prob", ",", "axis", "=", "2", ")", ",", "name", "=", "'predicted_chars'", ")", "mask", "=", "tf", ".", "cast", "(", "slim", ".", "one_hot_encoding", "(", "ids", ",", "self", ".", "_params", ".", "num_char_classes", ")", ",", "tf", ".", "bool", ")", "all_scores", "=", "tf", ".", "nn", ".", "softmax", "(", "chars_logit", ")", "selected_scores", "=", "tf", ".", "boolean_mask", "(", "all_scores", ",", "mask", ",", "name", "=", "'char_scores'", ")", "scores", "=", "tf", ".", "reshape", "(", "selected_scores", ",", "shape", "=", "(", "-", "1", ",", "self", ".", "_params", ".", "seq_length", ")", ")", "return", "ids", ",", "log_prob", ",", "scores" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/model.py#L286-L310
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/model.py
python
Model.encode_coordinates_fn
(self, net)
Adds one-hot encoding of coordinates to different views in the networks. For each "pixel" of a feature map it adds a onehot encoded x and y coordinates. Args: net: a tensor of shape=[batch_size, height, width, num_features] Returns: a tensor with the same height and width, but altered feature_size.
Adds one-hot encoding of coordinates to different views in the networks.
[ "Adds", "one", "-", "hot", "encoding", "of", "coordinates", "to", "different", "views", "in", "the", "networks", "." ]
def encode_coordinates_fn(self, net): """Adds one-hot encoding of coordinates to different views in the networks. For each "pixel" of a feature map it adds a onehot encoded x and y coordinates. Args: net: a tensor of shape=[batch_size, height, width, num_features] Returns: a tensor with the same height and width, but altered feature_size. """ mparams = self._mparams['encode_coordinates_fn'] if mparams.enabled: batch_size, h, w, _ = net.shape.as_list() x, y = tf.meshgrid(tf.range(w), tf.range(h)) w_loc = slim.one_hot_encoding(x, num_classes=w) h_loc = slim.one_hot_encoding(y, num_classes=h) loc = tf.concat([h_loc, w_loc], 2) loc = tf.tile(tf.expand_dims(loc, 0), [batch_size, 1, 1, 1]) return tf.concat([net, loc], 3) else: return net
[ "def", "encode_coordinates_fn", "(", "self", ",", "net", ")", ":", "mparams", "=", "self", ".", "_mparams", "[", "'encode_coordinates_fn'", "]", "if", "mparams", ".", "enabled", ":", "batch_size", ",", "h", ",", "w", ",", "_", "=", "net", ".", "shape", ".", "as_list", "(", ")", "x", ",", "y", "=", "tf", ".", "meshgrid", "(", "tf", ".", "range", "(", "w", ")", ",", "tf", ".", "range", "(", "h", ")", ")", "w_loc", "=", "slim", ".", "one_hot_encoding", "(", "x", ",", "num_classes", "=", "w", ")", "h_loc", "=", "slim", ".", "one_hot_encoding", "(", "y", ",", "num_classes", "=", "h", ")", "loc", "=", "tf", ".", "concat", "(", "[", "h_loc", ",", "w_loc", "]", ",", "2", ")", "loc", "=", "tf", ".", "tile", "(", "tf", ".", "expand_dims", "(", "loc", ",", "0", ")", ",", "[", "batch_size", ",", "1", ",", "1", ",", "1", "]", ")", "return", "tf", ".", "concat", "(", "[", "net", ",", "loc", "]", ",", "3", ")", "else", ":", "return", "net" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/model.py#L312-L334
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/model.py
python
Model.create_base
(self, images, labels_one_hot, scope='AttentionOcr_v1', reuse=None)
return OutputEndpoints( chars_logit=chars_logit, chars_log_prob=chars_log_prob, predicted_chars=predicted_chars, predicted_scores=predicted_scores, predicted_text=predicted_text)
Creates a base part of the Model (no gradients, losses or summaries). Args: images: A tensor of shape [batch_size, height, width, channels]. labels_one_hot: Optional (can be None) one-hot encoding for ground truth labels. If provided the function will create a model for training. scope: Optional variable_scope. reuse: whether or not the network and its variables should be reused. To be able to reuse 'scope' must be given. Returns: A named tuple OutputEndpoints.
Creates a base part of the Model (no gradients, losses or summaries).
[ "Creates", "a", "base", "part", "of", "the", "Model", "(", "no", "gradients", "losses", "or", "summaries", ")", "." ]
def create_base(self, images, labels_one_hot, scope='AttentionOcr_v1', reuse=None): """Creates a base part of the Model (no gradients, losses or summaries). Args: images: A tensor of shape [batch_size, height, width, channels]. labels_one_hot: Optional (can be None) one-hot encoding for ground truth labels. If provided the function will create a model for training. scope: Optional variable_scope. reuse: whether or not the network and its variables should be reused. To be able to reuse 'scope' must be given. Returns: A named tuple OutputEndpoints. """ logging.debug('images: %s', images) is_training = labels_one_hot is not None with tf.variable_scope(scope, reuse=reuse): views = tf.split( value=images, num_or_size_splits=self._params.num_views, axis=2) logging.debug('Views=%d single view: %s', len(views), views[0]) nets = [ self.conv_tower_fn(v, is_training, reuse=(i != 0)) for i, v in enumerate(views) ] logging.debug('Conv tower: %s', nets[0]) nets = [self.encode_coordinates_fn(net) for net in nets] logging.debug('Conv tower w/ encoded coordinates: %s', nets[0]) net = self.pool_views_fn(nets) logging.debug('Pooled views: %s', net) chars_logit = self.sequence_logit_fn(net, labels_one_hot) logging.debug('chars_logit: %s', chars_logit) predicted_chars, chars_log_prob, predicted_scores = ( self.char_predictions(chars_logit)) if self._charset: character_mapper = CharsetMapper(self._charset) predicted_text = character_mapper.get_text(predicted_chars) else: predicted_text = tf.constant([]) return OutputEndpoints( chars_logit=chars_logit, chars_log_prob=chars_log_prob, predicted_chars=predicted_chars, predicted_scores=predicted_scores, predicted_text=predicted_text)
[ "def", "create_base", "(", "self", ",", "images", ",", "labels_one_hot", ",", "scope", "=", "'AttentionOcr_v1'", ",", "reuse", "=", "None", ")", ":", "logging", ".", "debug", "(", "'images: %s'", ",", "images", ")", "is_training", "=", "labels_one_hot", "is", "not", "None", "with", "tf", ".", "variable_scope", "(", "scope", ",", "reuse", "=", "reuse", ")", ":", "views", "=", "tf", ".", "split", "(", "value", "=", "images", ",", "num_or_size_splits", "=", "self", ".", "_params", ".", "num_views", ",", "axis", "=", "2", ")", "logging", ".", "debug", "(", "'Views=%d single view: %s'", ",", "len", "(", "views", ")", ",", "views", "[", "0", "]", ")", "nets", "=", "[", "self", ".", "conv_tower_fn", "(", "v", ",", "is_training", ",", "reuse", "=", "(", "i", "!=", "0", ")", ")", "for", "i", ",", "v", "in", "enumerate", "(", "views", ")", "]", "logging", ".", "debug", "(", "'Conv tower: %s'", ",", "nets", "[", "0", "]", ")", "nets", "=", "[", "self", ".", "encode_coordinates_fn", "(", "net", ")", "for", "net", "in", "nets", "]", "logging", ".", "debug", "(", "'Conv tower w/ encoded coordinates: %s'", ",", "nets", "[", "0", "]", ")", "net", "=", "self", ".", "pool_views_fn", "(", "nets", ")", "logging", ".", "debug", "(", "'Pooled views: %s'", ",", "net", ")", "chars_logit", "=", "self", ".", "sequence_logit_fn", "(", "net", ",", "labels_one_hot", ")", "logging", ".", "debug", "(", "'chars_logit: %s'", ",", "chars_logit", ")", "predicted_chars", ",", "chars_log_prob", ",", "predicted_scores", "=", "(", "self", ".", "char_predictions", "(", "chars_logit", ")", ")", "if", "self", ".", "_charset", ":", "character_mapper", "=", "CharsetMapper", "(", "self", ".", "_charset", ")", "predicted_text", "=", "character_mapper", ".", "get_text", "(", "predicted_chars", ")", "else", ":", "predicted_text", "=", "tf", ".", "constant", "(", "[", "]", ")", "return", "OutputEndpoints", "(", "chars_logit", "=", "chars_logit", ",", "chars_log_prob", "=", "chars_log_prob", ",", "predicted_chars", "=", "predicted_chars", ",", "predicted_scores", "=", "predicted_scores", ",", "predicted_text", "=", "predicted_text", ")" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/model.py#L336-L389
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/model.py
python
Model.create_loss
(self, data, endpoints)
return total_loss
Creates all losses required to train the model. Args: data: InputEndpoints namedtuple. endpoints: Model namedtuple. Returns: Total loss.
Creates all losses required to train the model.
[ "Creates", "all", "losses", "required", "to", "train", "the", "model", "." ]
def create_loss(self, data, endpoints): """Creates all losses required to train the model. Args: data: InputEndpoints namedtuple. endpoints: Model namedtuple. Returns: Total loss. """ # NOTE: the return value of ModelLoss is not used directly for the # gradient computation because under the hood it calls slim.losses.AddLoss, # which registers the loss in an internal collection and later returns it # as part of GetTotalLoss. We need to use total loss because model may have # multiple losses including regularization losses. self.sequence_loss_fn(endpoints.chars_logit, data.labels) total_loss = slim.losses.get_total_loss() tf.summary.scalar('TotalLoss', total_loss) return total_loss
[ "def", "create_loss", "(", "self", ",", "data", ",", "endpoints", ")", ":", "# NOTE: the return value of ModelLoss is not used directly for the", "# gradient computation because under the hood it calls slim.losses.AddLoss,", "# which registers the loss in an internal collection and later returns it", "# as part of GetTotalLoss. We need to use total loss because model may have", "# multiple losses including regularization losses.", "self", ".", "sequence_loss_fn", "(", "endpoints", ".", "chars_logit", ",", "data", ".", "labels", ")", "total_loss", "=", "slim", ".", "losses", ".", "get_total_loss", "(", ")", "tf", ".", "summary", ".", "scalar", "(", "'TotalLoss'", ",", "total_loss", ")", "return", "total_loss" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/model.py#L391-L409
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/model.py
python
Model.label_smoothing_regularization
(self, chars_labels, weight=0.1)
return one_hot_labels * pos_weight + neg_weight
Applies a label smoothing regularization. Uses the same method as in https://arxiv.org/abs/1512.00567. Args: chars_labels: ground truth ids of charactes, shape=[batch_size, seq_length]; weight: label-smoothing regularization weight. Returns: A sensor with the same shape as the input.
Applies a label smoothing regularization.
[ "Applies", "a", "label", "smoothing", "regularization", "." ]
def label_smoothing_regularization(self, chars_labels, weight=0.1): """Applies a label smoothing regularization. Uses the same method as in https://arxiv.org/abs/1512.00567. Args: chars_labels: ground truth ids of charactes, shape=[batch_size, seq_length]; weight: label-smoothing regularization weight. Returns: A sensor with the same shape as the input. """ one_hot_labels = tf.one_hot( chars_labels, depth=self._params.num_char_classes, axis=-1) pos_weight = 1.0 - weight neg_weight = weight / self._params.num_char_classes return one_hot_labels * pos_weight + neg_weight
[ "def", "label_smoothing_regularization", "(", "self", ",", "chars_labels", ",", "weight", "=", "0.1", ")", ":", "one_hot_labels", "=", "tf", ".", "one_hot", "(", "chars_labels", ",", "depth", "=", "self", ".", "_params", ".", "num_char_classes", ",", "axis", "=", "-", "1", ")", "pos_weight", "=", "1.0", "-", "weight", "neg_weight", "=", "weight", "/", "self", ".", "_params", ".", "num_char_classes", "return", "one_hot_labels", "*", "pos_weight", "+", "neg_weight" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/model.py#L411-L428
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/model.py
python
Model.sequence_loss_fn
(self, chars_logits, chars_labels)
Loss function for char sequence. Depending on values of hyper parameters it applies label smoothing and can also ignore all null chars after the first one. Args: chars_logits: logits for predicted characters, shape=[batch_size, seq_length, num_char_classes]; chars_labels: ground truth ids of characters, shape=[batch_size, seq_length]; mparams: method hyper parameters. Returns: A Tensor with shape [batch_size] - the log-perplexity for each sequence.
Loss function for char sequence.
[ "Loss", "function", "for", "char", "sequence", "." ]
def sequence_loss_fn(self, chars_logits, chars_labels): """Loss function for char sequence. Depending on values of hyper parameters it applies label smoothing and can also ignore all null chars after the first one. Args: chars_logits: logits for predicted characters, shape=[batch_size, seq_length, num_char_classes]; chars_labels: ground truth ids of characters, shape=[batch_size, seq_length]; mparams: method hyper parameters. Returns: A Tensor with shape [batch_size] - the log-perplexity for each sequence. """ mparams = self._mparams['sequence_loss_fn'] with tf.variable_scope('sequence_loss_fn/SLF'): if mparams.label_smoothing > 0: smoothed_one_hot_labels = self.label_smoothing_regularization( chars_labels, mparams.label_smoothing) labels_list = tf.unstack(smoothed_one_hot_labels, axis=1) else: # NOTE: in case of sparse softmax we are not using one-hot # encoding. labels_list = tf.unstack(chars_labels, axis=1) batch_size, seq_length, _ = chars_logits.shape.as_list() if mparams.ignore_nulls: weights = tf.ones((batch_size, seq_length), dtype=tf.float32) else: # Suppose that reject character is the last in the charset. reject_char = tf.constant( self._params.num_char_classes - 1, shape=(batch_size, seq_length), dtype=tf.int64) known_char = tf.not_equal(chars_labels, reject_char) weights = tf.to_float(known_char) logits_list = tf.unstack(chars_logits, axis=1) weights_list = tf.unstack(weights, axis=1) loss = tf.contrib.legacy_seq2seq.sequence_loss( logits_list, labels_list, weights_list, softmax_loss_function=get_softmax_loss_fn(mparams.label_smoothing), average_across_timesteps=mparams.average_across_timesteps) tf.losses.add_loss(loss) return loss
[ "def", "sequence_loss_fn", "(", "self", ",", "chars_logits", ",", "chars_labels", ")", ":", "mparams", "=", "self", ".", "_mparams", "[", "'sequence_loss_fn'", "]", "with", "tf", ".", "variable_scope", "(", "'sequence_loss_fn/SLF'", ")", ":", "if", "mparams", ".", "label_smoothing", ">", "0", ":", "smoothed_one_hot_labels", "=", "self", ".", "label_smoothing_regularization", "(", "chars_labels", ",", "mparams", ".", "label_smoothing", ")", "labels_list", "=", "tf", ".", "unstack", "(", "smoothed_one_hot_labels", ",", "axis", "=", "1", ")", "else", ":", "# NOTE: in case of sparse softmax we are not using one-hot", "# encoding.", "labels_list", "=", "tf", ".", "unstack", "(", "chars_labels", ",", "axis", "=", "1", ")", "batch_size", ",", "seq_length", ",", "_", "=", "chars_logits", ".", "shape", ".", "as_list", "(", ")", "if", "mparams", ".", "ignore_nulls", ":", "weights", "=", "tf", ".", "ones", "(", "(", "batch_size", ",", "seq_length", ")", ",", "dtype", "=", "tf", ".", "float32", ")", "else", ":", "# Suppose that reject character is the last in the charset.", "reject_char", "=", "tf", ".", "constant", "(", "self", ".", "_params", ".", "num_char_classes", "-", "1", ",", "shape", "=", "(", "batch_size", ",", "seq_length", ")", ",", "dtype", "=", "tf", ".", "int64", ")", "known_char", "=", "tf", ".", "not_equal", "(", "chars_labels", ",", "reject_char", ")", "weights", "=", "tf", ".", "to_float", "(", "known_char", ")", "logits_list", "=", "tf", ".", "unstack", "(", "chars_logits", ",", "axis", "=", "1", ")", "weights_list", "=", "tf", ".", "unstack", "(", "weights", ",", "axis", "=", "1", ")", "loss", "=", "tf", ".", "contrib", ".", "legacy_seq2seq", ".", "sequence_loss", "(", "logits_list", ",", "labels_list", ",", "weights_list", ",", "softmax_loss_function", "=", "get_softmax_loss_fn", "(", "mparams", ".", "label_smoothing", ")", ",", "average_across_timesteps", "=", "mparams", ".", "average_across_timesteps", ")", "tf", ".", "losses", ".", "add_loss", "(", "loss", ")", "return", "loss" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/model.py#L430-L478
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/model.py
python
Model.create_summaries
(self, data, endpoints, charset, is_training)
Creates all summaries for the model. Args: data: InputEndpoints namedtuple. endpoints: OutputEndpoints namedtuple. charset: A dictionary with mapping between character codes and unicode characters. Use the one provided by a dataset.charset. is_training: If True will create summary prefixes for training job, otherwise - for evaluation. Returns: A list of evaluation ops
Creates all summaries for the model.
[ "Creates", "all", "summaries", "for", "the", "model", "." ]
def create_summaries(self, data, endpoints, charset, is_training): """Creates all summaries for the model. Args: data: InputEndpoints namedtuple. endpoints: OutputEndpoints namedtuple. charset: A dictionary with mapping between character codes and unicode characters. Use the one provided by a dataset.charset. is_training: If True will create summary prefixes for training job, otherwise - for evaluation. Returns: A list of evaluation ops """ def sname(label): prefix = 'train' if is_training else 'eval' return '%s/%s' % (prefix, label) max_outputs = 4 # TODO(gorban): uncomment, when tf.summary.text released. charset_mapper = CharsetMapper(charset) pr_text = charset_mapper.get_text( endpoints.predicted_chars[:max_outputs,:]) tf.summary.text(sname('text/pr'), pr_text) gt_text = charset_mapper.get_text(data.labels[:max_outputs,:]) tf.summary.text(sname('text/gt'), gt_text) tf.summary.image(sname('image'), data.images, max_outputs=max_outputs) if is_training: tf.summary.image( sname('image/orig'), data.images_orig, max_outputs=max_outputs) for var in tf.trainable_variables(): tf.summary.histogram(var.op.name, var) return None else: names_to_values = {} names_to_updates = {} def use_metric(name, value_update_tuple): names_to_values[name] = value_update_tuple[0] names_to_updates[name] = value_update_tuple[1] use_metric('CharacterAccuracy', metrics.char_accuracy( endpoints.predicted_chars, data.labels, streaming=True, rej_char=self._params.null_code)) # Sequence accuracy computed by cutting sequence at the first null char use_metric('SequenceAccuracy', metrics.sequence_accuracy( endpoints.predicted_chars, data.labels, streaming=True, rej_char=self._params.null_code)) for name, value in names_to_values.items(): summary_name = 'eval/' + name tf.summary.scalar(summary_name, tf.Print(value, [value], summary_name)) return list(names_to_updates.values())
[ "def", "create_summaries", "(", "self", ",", "data", ",", "endpoints", ",", "charset", ",", "is_training", ")", ":", "def", "sname", "(", "label", ")", ":", "prefix", "=", "'train'", "if", "is_training", "else", "'eval'", "return", "'%s/%s'", "%", "(", "prefix", ",", "label", ")", "max_outputs", "=", "4", "# TODO(gorban): uncomment, when tf.summary.text released.", "charset_mapper", "=", "CharsetMapper", "(", "charset", ")", "pr_text", "=", "charset_mapper", ".", "get_text", "(", "endpoints", ".", "predicted_chars", "[", ":", "max_outputs", ",", ":", "]", ")", "tf", ".", "summary", ".", "text", "(", "sname", "(", "'text/pr'", ")", ",", "pr_text", ")", "gt_text", "=", "charset_mapper", ".", "get_text", "(", "data", ".", "labels", "[", ":", "max_outputs", ",", ":", "]", ")", "tf", ".", "summary", ".", "text", "(", "sname", "(", "'text/gt'", ")", ",", "gt_text", ")", "tf", ".", "summary", ".", "image", "(", "sname", "(", "'image'", ")", ",", "data", ".", "images", ",", "max_outputs", "=", "max_outputs", ")", "if", "is_training", ":", "tf", ".", "summary", ".", "image", "(", "sname", "(", "'image/orig'", ")", ",", "data", ".", "images_orig", ",", "max_outputs", "=", "max_outputs", ")", "for", "var", "in", "tf", ".", "trainable_variables", "(", ")", ":", "tf", ".", "summary", ".", "histogram", "(", "var", ".", "op", ".", "name", ",", "var", ")", "return", "None", "else", ":", "names_to_values", "=", "{", "}", "names_to_updates", "=", "{", "}", "def", "use_metric", "(", "name", ",", "value_update_tuple", ")", ":", "names_to_values", "[", "name", "]", "=", "value_update_tuple", "[", "0", "]", "names_to_updates", "[", "name", "]", "=", "value_update_tuple", "[", "1", "]", "use_metric", "(", "'CharacterAccuracy'", ",", "metrics", ".", "char_accuracy", "(", "endpoints", ".", "predicted_chars", ",", "data", ".", "labels", ",", "streaming", "=", "True", ",", "rej_char", "=", "self", ".", "_params", ".", "null_code", ")", ")", "# Sequence accuracy computed by cutting sequence at the first null char", "use_metric", "(", "'SequenceAccuracy'", ",", "metrics", ".", "sequence_accuracy", "(", "endpoints", ".", "predicted_chars", ",", "data", ".", "labels", ",", "streaming", "=", "True", ",", "rej_char", "=", "self", ".", "_params", ".", "null_code", ")", ")", "for", "name", ",", "value", "in", "names_to_values", ".", "items", "(", ")", ":", "summary_name", "=", "'eval/'", "+", "name", "tf", ".", "summary", ".", "scalar", "(", "summary_name", ",", "tf", ".", "Print", "(", "value", ",", "[", "value", "]", ",", "summary_name", ")", ")", "return", "list", "(", "names_to_updates", ".", "values", "(", ")", ")" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/model.py#L480-L541
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/model.py
python
Model.create_init_fn_to_restore
(self, master_checkpoint, inception_checkpoint=None)
return init_assign_fn
Creates an init operations to restore weights from various checkpoints. Args: master_checkpoint: path to a checkpoint which contains all weights for the whole model. inception_checkpoint: path to a checkpoint which contains weights for the inception part only. Returns: a function to run initialization ops.
Creates an init operations to restore weights from various checkpoints.
[ "Creates", "an", "init", "operations", "to", "restore", "weights", "from", "various", "checkpoints", "." ]
def create_init_fn_to_restore(self, master_checkpoint, inception_checkpoint=None): """Creates an init operations to restore weights from various checkpoints. Args: master_checkpoint: path to a checkpoint which contains all weights for the whole model. inception_checkpoint: path to a checkpoint which contains weights for the inception part only. Returns: a function to run initialization ops. """ all_assign_ops = [] all_feed_dict = {} def assign_from_checkpoint(variables, checkpoint): logging.info('Request to re-store %d weights from %s', len(variables), checkpoint) if not variables: logging.error('Can\'t find any variables to restore.') sys.exit(1) assign_op, feed_dict = slim.assign_from_checkpoint(checkpoint, variables) all_assign_ops.append(assign_op) all_feed_dict.update(feed_dict) logging.info('variables_to_restore:\n%s' % utils.variables_to_restore().keys()) logging.info('moving_average_variables:\n%s' % [v.op.name for v in tf.moving_average_variables()]) logging.info('trainable_variables:\n%s' % [v.op.name for v in tf.trainable_variables()]) if master_checkpoint: assign_from_checkpoint(utils.variables_to_restore(), master_checkpoint) if inception_checkpoint: variables = utils.variables_to_restore( 'AttentionOcr_v1/conv_tower_fn/INCE', strip_scope=True) assign_from_checkpoint(variables, inception_checkpoint) def init_assign_fn(sess): logging.info('Restoring checkpoint(s)') sess.run(all_assign_ops, all_feed_dict) return init_assign_fn
[ "def", "create_init_fn_to_restore", "(", "self", ",", "master_checkpoint", ",", "inception_checkpoint", "=", "None", ")", ":", "all_assign_ops", "=", "[", "]", "all_feed_dict", "=", "{", "}", "def", "assign_from_checkpoint", "(", "variables", ",", "checkpoint", ")", ":", "logging", ".", "info", "(", "'Request to re-store %d weights from %s'", ",", "len", "(", "variables", ")", ",", "checkpoint", ")", "if", "not", "variables", ":", "logging", ".", "error", "(", "'Can\\'t find any variables to restore.'", ")", "sys", ".", "exit", "(", "1", ")", "assign_op", ",", "feed_dict", "=", "slim", ".", "assign_from_checkpoint", "(", "checkpoint", ",", "variables", ")", "all_assign_ops", ".", "append", "(", "assign_op", ")", "all_feed_dict", ".", "update", "(", "feed_dict", ")", "logging", ".", "info", "(", "'variables_to_restore:\\n%s'", "%", "utils", ".", "variables_to_restore", "(", ")", ".", "keys", "(", ")", ")", "logging", ".", "info", "(", "'moving_average_variables:\\n%s'", "%", "[", "v", ".", "op", ".", "name", "for", "v", "in", "tf", ".", "moving_average_variables", "(", ")", "]", ")", "logging", ".", "info", "(", "'trainable_variables:\\n%s'", "%", "[", "v", ".", "op", ".", "name", "for", "v", "in", "tf", ".", "trainable_variables", "(", ")", "]", ")", "if", "master_checkpoint", ":", "assign_from_checkpoint", "(", "utils", ".", "variables_to_restore", "(", ")", ",", "master_checkpoint", ")", "if", "inception_checkpoint", ":", "variables", "=", "utils", ".", "variables_to_restore", "(", "'AttentionOcr_v1/conv_tower_fn/INCE'", ",", "strip_scope", "=", "True", ")", "assign_from_checkpoint", "(", "variables", ",", "inception_checkpoint", ")", "def", "init_assign_fn", "(", "sess", ")", ":", "logging", ".", "info", "(", "'Restoring checkpoint(s)'", ")", "sess", ".", "run", "(", "all_assign_ops", ",", "all_feed_dict", ")", "return", "init_assign_fn" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/model.py#L543-L584
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/sequence_layers.py
python
orthogonal_initializer
(shape, dtype=tf.float32, *args, **kwargs)
return tf.constant(w.reshape(shape), dtype=dtype)
Generates orthonormal matrices with random values. Orthonormal initialization is important for RNNs: http://arxiv.org/abs/1312.6120 http://smerity.com/articles/2016/orthogonal_init.html For non-square shapes the returned matrix will be semi-orthonormal: if the number of columns exceeds the number of rows, then the rows are orthonormal vectors; but if the number of rows exceeds the number of columns, then the columns are orthonormal vectors. We use SVD decomposition to generate an orthonormal matrix with random values. The same way as it is done in the Lasagne library for Theano. Note that both u and v returned by the svd are orthogonal and random. We just need to pick one with the right shape. Args: shape: a shape of the tensor matrix to initialize. dtype: a dtype of the initialized tensor. *args: not used. **kwargs: not used. Returns: An initialized tensor.
Generates orthonormal matrices with random values.
[ "Generates", "orthonormal", "matrices", "with", "random", "values", "." ]
def orthogonal_initializer(shape, dtype=tf.float32, *args, **kwargs): """Generates orthonormal matrices with random values. Orthonormal initialization is important for RNNs: http://arxiv.org/abs/1312.6120 http://smerity.com/articles/2016/orthogonal_init.html For non-square shapes the returned matrix will be semi-orthonormal: if the number of columns exceeds the number of rows, then the rows are orthonormal vectors; but if the number of rows exceeds the number of columns, then the columns are orthonormal vectors. We use SVD decomposition to generate an orthonormal matrix with random values. The same way as it is done in the Lasagne library for Theano. Note that both u and v returned by the svd are orthogonal and random. We just need to pick one with the right shape. Args: shape: a shape of the tensor matrix to initialize. dtype: a dtype of the initialized tensor. *args: not used. **kwargs: not used. Returns: An initialized tensor. """ del args del kwargs flat_shape = (shape[0], np.prod(shape[1:])) w = np.random.randn(*flat_shape) u, _, v = np.linalg.svd(w, full_matrices=False) w = u if u.shape == flat_shape else v return tf.constant(w.reshape(shape), dtype=dtype)
[ "def", "orthogonal_initializer", "(", "shape", ",", "dtype", "=", "tf", ".", "float32", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "del", "args", "del", "kwargs", "flat_shape", "=", "(", "shape", "[", "0", "]", ",", "np", ".", "prod", "(", "shape", "[", "1", ":", "]", ")", ")", "w", "=", "np", ".", "random", ".", "randn", "(", "*", "flat_shape", ")", "u", ",", "_", ",", "v", "=", "np", ".", "linalg", ".", "svd", "(", "w", ",", "full_matrices", "=", "False", ")", "w", "=", "u", "if", "u", ".", "shape", "==", "flat_shape", "else", "v", "return", "tf", ".", "constant", "(", "w", ".", "reshape", "(", "shape", ")", ",", "dtype", "=", "dtype", ")" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/sequence_layers.py#L48-L80
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/sequence_layers.py
python
get_layer_class
(use_attention, use_autoregression)
return layer_class
A convenience function to get a layer class based on requirements. Args: use_attention: if True a returned class will use attention. use_autoregression: if True a returned class will use auto regression. Returns: One of available sequence layers (child classes for SequenceLayerBase).
A convenience function to get a layer class based on requirements.
[ "A", "convenience", "function", "to", "get", "a", "layer", "class", "based", "on", "requirements", "." ]
def get_layer_class(use_attention, use_autoregression): """A convenience function to get a layer class based on requirements. Args: use_attention: if True a returned class will use attention. use_autoregression: if True a returned class will use auto regression. Returns: One of available sequence layers (child classes for SequenceLayerBase). """ if use_attention and use_autoregression: layer_class = AttentionWithAutoregression elif use_attention and not use_autoregression: layer_class = Attention elif not use_attention and not use_autoregression: layer_class = NetSlice elif not use_attention and use_autoregression: layer_class = NetSliceWithAutoregression else: raise AssertionError('Unsupported sequence layer class') logging.debug('Use %s as a layer class', layer_class.__name__) return layer_class
[ "def", "get_layer_class", "(", "use_attention", ",", "use_autoregression", ")", ":", "if", "use_attention", "and", "use_autoregression", ":", "layer_class", "=", "AttentionWithAutoregression", "elif", "use_attention", "and", "not", "use_autoregression", ":", "layer_class", "=", "Attention", "elif", "not", "use_attention", "and", "not", "use_autoregression", ":", "layer_class", "=", "NetSlice", "elif", "not", "use_attention", "and", "use_autoregression", ":", "layer_class", "=", "NetSliceWithAutoregression", "else", ":", "raise", "AssertionError", "(", "'Unsupported sequence layer class'", ")", "logging", ".", "debug", "(", "'Use %s as a layer class'", ",", "layer_class", ".", "__name__", ")", "return", "layer_class" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/sequence_layers.py#L400-L422
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/sequence_layers.py
python
SequenceLayerBase.__init__
(self, net, labels_one_hot, model_params, method_params)
Stores argument in member variable for further use. Args: net: A tensor with shape [batch_size, num_features, feature_size] which contains some extracted image features. labels_one_hot: An optional (can be None) ground truth labels for the input features. Is a tensor with shape [batch_size, seq_length, num_char_classes] model_params: A namedtuple with model parameters (model.ModelParams). method_params: A SequenceLayerParams instance.
Stores argument in member variable for further use.
[ "Stores", "argument", "in", "member", "variable", "for", "further", "use", "." ]
def __init__(self, net, labels_one_hot, model_params, method_params): """Stores argument in member variable for further use. Args: net: A tensor with shape [batch_size, num_features, feature_size] which contains some extracted image features. labels_one_hot: An optional (can be None) ground truth labels for the input features. Is a tensor with shape [batch_size, seq_length, num_char_classes] model_params: A namedtuple with model parameters (model.ModelParams). method_params: A SequenceLayerParams instance. """ self._params = model_params self._mparams = method_params self._net = net self._labels_one_hot = labels_one_hot self._batch_size = net.get_shape().dims[0].value # Initialize parameters for char logits which will be computed on the fly # inside an LSTM decoder. self._char_logits = {} regularizer = slim.l2_regularizer(self._mparams.weight_decay) self._softmax_w = slim.model_variable( 'softmax_w', [self._mparams.num_lstm_units, self._params.num_char_classes], initializer=orthogonal_initializer, regularizer=regularizer) self._softmax_b = slim.model_variable( 'softmax_b', [self._params.num_char_classes], initializer=tf.zeros_initializer(), regularizer=regularizer)
[ "def", "__init__", "(", "self", ",", "net", ",", "labels_one_hot", ",", "model_params", ",", "method_params", ")", ":", "self", ".", "_params", "=", "model_params", "self", ".", "_mparams", "=", "method_params", "self", ".", "_net", "=", "net", "self", ".", "_labels_one_hot", "=", "labels_one_hot", "self", ".", "_batch_size", "=", "net", ".", "get_shape", "(", ")", ".", "dims", "[", "0", "]", ".", "value", "# Initialize parameters for char logits which will be computed on the fly", "# inside an LSTM decoder.", "self", ".", "_char_logits", "=", "{", "}", "regularizer", "=", "slim", ".", "l2_regularizer", "(", "self", ".", "_mparams", ".", "weight_decay", ")", "self", ".", "_softmax_w", "=", "slim", ".", "model_variable", "(", "'softmax_w'", ",", "[", "self", ".", "_mparams", ".", "num_lstm_units", ",", "self", ".", "_params", ".", "num_char_classes", "]", ",", "initializer", "=", "orthogonal_initializer", ",", "regularizer", "=", "regularizer", ")", "self", ".", "_softmax_b", "=", "slim", ".", "model_variable", "(", "'softmax_b'", ",", "[", "self", ".", "_params", ".", "num_char_classes", "]", ",", "initializer", "=", "tf", ".", "zeros_initializer", "(", ")", ",", "regularizer", "=", "regularizer", ")" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/sequence_layers.py#L98-L128
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/sequence_layers.py
python
SequenceLayerBase.get_train_input
(self, prev, i)
Returns a sample to be used to predict a character during training. This function is used as a loop_function for an RNN decoder. Args: prev: output tensor from previous step of the RNN. A tensor with shape: [batch_size, num_char_classes]. i: index of a character in the output sequence. Returns: A tensor with shape [batch_size, ?] - depth depends on implementation details.
Returns a sample to be used to predict a character during training.
[ "Returns", "a", "sample", "to", "be", "used", "to", "predict", "a", "character", "during", "training", "." ]
def get_train_input(self, prev, i): """Returns a sample to be used to predict a character during training. This function is used as a loop_function for an RNN decoder. Args: prev: output tensor from previous step of the RNN. A tensor with shape: [batch_size, num_char_classes]. i: index of a character in the output sequence. Returns: A tensor with shape [batch_size, ?] - depth depends on implementation details. """ pass
[ "def", "get_train_input", "(", "self", ",", "prev", ",", "i", ")", ":", "pass" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/sequence_layers.py#L131-L145
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/sequence_layers.py
python
SequenceLayerBase.get_eval_input
(self, prev, i)
Returns a sample to be used to predict a character during inference. This function is used as a loop_function for an RNN decoder. Args: prev: output tensor from previous step of the RNN. A tensor with shape: [batch_size, num_char_classes]. i: index of a character in the output sequence. Returns: A tensor with shape [batch_size, ?] - depth depends on implementation details.
Returns a sample to be used to predict a character during inference.
[ "Returns", "a", "sample", "to", "be", "used", "to", "predict", "a", "character", "during", "inference", "." ]
def get_eval_input(self, prev, i): """Returns a sample to be used to predict a character during inference. This function is used as a loop_function for an RNN decoder. Args: prev: output tensor from previous step of the RNN. A tensor with shape: [batch_size, num_char_classes]. i: index of a character in the output sequence. Returns: A tensor with shape [batch_size, ?] - depth depends on implementation details. """ raise AssertionError('Not implemented')
[ "def", "get_eval_input", "(", "self", ",", "prev", ",", "i", ")", ":", "raise", "AssertionError", "(", "'Not implemented'", ")" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/sequence_layers.py#L148-L162
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/sequence_layers.py
python
SequenceLayerBase.unroll_cell
(self, decoder_inputs, initial_state, loop_function, cell)
Unrolls an RNN cell for all inputs. This is a placeholder to call some RNN decoder. It has a similar to tf.seq2seq.rnn_decode interface. Args: decoder_inputs: A list of 2D Tensors* [batch_size x input_size]. In fact, most of existing decoders in presence of a loop_function use only the first element to determine batch_size and length of the list to determine number of steps. initial_state: 2D Tensor with shape [batch_size x cell.state_size]. loop_function: function will be applied to the i-th output in order to generate the i+1-st input (see self.get_input). cell: rnn_cell.RNNCell defining the cell function and size. Returns: A tuple of the form (outputs, state), where: outputs: A list of character logits of the same length as decoder_inputs of 2D Tensors with shape [batch_size x num_characters]. state: The state of each cell at the final time-step. It is a 2D Tensor of shape [batch_size x cell.state_size].
Unrolls an RNN cell for all inputs.
[ "Unrolls", "an", "RNN", "cell", "for", "all", "inputs", "." ]
def unroll_cell(self, decoder_inputs, initial_state, loop_function, cell): """Unrolls an RNN cell for all inputs. This is a placeholder to call some RNN decoder. It has a similar to tf.seq2seq.rnn_decode interface. Args: decoder_inputs: A list of 2D Tensors* [batch_size x input_size]. In fact, most of existing decoders in presence of a loop_function use only the first element to determine batch_size and length of the list to determine number of steps. initial_state: 2D Tensor with shape [batch_size x cell.state_size]. loop_function: function will be applied to the i-th output in order to generate the i+1-st input (see self.get_input). cell: rnn_cell.RNNCell defining the cell function and size. Returns: A tuple of the form (outputs, state), where: outputs: A list of character logits of the same length as decoder_inputs of 2D Tensors with shape [batch_size x num_characters]. state: The state of each cell at the final time-step. It is a 2D Tensor of shape [batch_size x cell.state_size]. """ pass
[ "def", "unroll_cell", "(", "self", ",", "decoder_inputs", ",", "initial_state", ",", "loop_function", ",", "cell", ")", ":", "pass" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/sequence_layers.py#L165-L188
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/sequence_layers.py
python
SequenceLayerBase.is_training
(self)
return self._labels_one_hot is not None
Returns True if the layer is created for training stage.
Returns True if the layer is created for training stage.
[ "Returns", "True", "if", "the", "layer", "is", "created", "for", "training", "stage", "." ]
def is_training(self): """Returns True if the layer is created for training stage.""" return self._labels_one_hot is not None
[ "def", "is_training", "(", "self", ")", ":", "return", "self", ".", "_labels_one_hot", "is", "not", "None" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/sequence_layers.py#L190-L192
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/sequence_layers.py
python
SequenceLayerBase.char_logit
(self, inputs, char_index)
return self._char_logits[char_index]
Creates logits for a character if required. Args: inputs: A tensor with shape [batch_size, ?] (depth is implementation dependent). char_index: A integer index of a character in the output sequence. Returns: A tensor with shape [batch_size, num_char_classes]
Creates logits for a character if required.
[ "Creates", "logits", "for", "a", "character", "if", "required", "." ]
def char_logit(self, inputs, char_index): """Creates logits for a character if required. Args: inputs: A tensor with shape [batch_size, ?] (depth is implementation dependent). char_index: A integer index of a character in the output sequence. Returns: A tensor with shape [batch_size, num_char_classes] """ if char_index not in self._char_logits: self._char_logits[char_index] = tf.nn.xw_plus_b(inputs, self._softmax_w, self._softmax_b) return self._char_logits[char_index]
[ "def", "char_logit", "(", "self", ",", "inputs", ",", "char_index", ")", ":", "if", "char_index", "not", "in", "self", ".", "_char_logits", ":", "self", ".", "_char_logits", "[", "char_index", "]", "=", "tf", ".", "nn", ".", "xw_plus_b", "(", "inputs", ",", "self", ".", "_softmax_w", ",", "self", ".", "_softmax_b", ")", "return", "self", ".", "_char_logits", "[", "char_index", "]" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/sequence_layers.py#L194-L208
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/sequence_layers.py
python
SequenceLayerBase.char_one_hot
(self, logit)
return slim.one_hot_encoding(prediction, self._params.num_char_classes)
Creates one hot encoding for a logit of a character. Args: logit: A tensor with shape [batch_size, num_char_classes]. Returns: A tensor with shape [batch_size, num_char_classes]
Creates one hot encoding for a logit of a character.
[ "Creates", "one", "hot", "encoding", "for", "a", "logit", "of", "a", "character", "." ]
def char_one_hot(self, logit): """Creates one hot encoding for a logit of a character. Args: logit: A tensor with shape [batch_size, num_char_classes]. Returns: A tensor with shape [batch_size, num_char_classes] """ prediction = tf.argmax(logit, axis=1) return slim.one_hot_encoding(prediction, self._params.num_char_classes)
[ "def", "char_one_hot", "(", "self", ",", "logit", ")", ":", "prediction", "=", "tf", ".", "argmax", "(", "logit", ",", "axis", "=", "1", ")", "return", "slim", ".", "one_hot_encoding", "(", "prediction", ",", "self", ".", "_params", ".", "num_char_classes", ")" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/sequence_layers.py#L210-L220
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/sequence_layers.py
python
SequenceLayerBase.get_input
(self, prev, i)
A wrapper for get_train_input and get_eval_input. Args: prev: output tensor from previous step of the RNN. A tensor with shape: [batch_size, num_char_classes]. i: index of a character in the output sequence. Returns: A tensor with shape [batch_size, ?] - depth depends on implementation details.
A wrapper for get_train_input and get_eval_input.
[ "A", "wrapper", "for", "get_train_input", "and", "get_eval_input", "." ]
def get_input(self, prev, i): """A wrapper for get_train_input and get_eval_input. Args: prev: output tensor from previous step of the RNN. A tensor with shape: [batch_size, num_char_classes]. i: index of a character in the output sequence. Returns: A tensor with shape [batch_size, ?] - depth depends on implementation details. """ if self.is_training(): return self.get_train_input(prev, i) else: return self.get_eval_input(prev, i)
[ "def", "get_input", "(", "self", ",", "prev", ",", "i", ")", ":", "if", "self", ".", "is_training", "(", ")", ":", "return", "self", ".", "get_train_input", "(", "prev", ",", "i", ")", "else", ":", "return", "self", ".", "get_eval_input", "(", "prev", ",", "i", ")" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/sequence_layers.py#L222-L237
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/sequence_layers.py
python
SequenceLayerBase.create_logits
(self)
return tf.concat(logits_list, 1)
Creates character sequence logits for a net specified in the constructor. A "main" method for the sequence layer which glues together all pieces. Returns: A tensor with shape [batch_size, seq_length, num_char_classes].
Creates character sequence logits for a net specified in the constructor.
[ "Creates", "character", "sequence", "logits", "for", "a", "net", "specified", "in", "the", "constructor", "." ]
def create_logits(self): """Creates character sequence logits for a net specified in the constructor. A "main" method for the sequence layer which glues together all pieces. Returns: A tensor with shape [batch_size, seq_length, num_char_classes]. """ with tf.variable_scope('LSTM'): first_label = self.get_input(prev=None, i=0) decoder_inputs = [first_label] + [None] * (self._params.seq_length - 1) lstm_cell = tf.contrib.rnn.LSTMCell( self._mparams.num_lstm_units, use_peepholes=False, cell_clip=self._mparams.lstm_state_clip_value, state_is_tuple=True, initializer=orthogonal_initializer) lstm_outputs, _ = self.unroll_cell( decoder_inputs=decoder_inputs, initial_state=lstm_cell.zero_state(self._batch_size, tf.float32), loop_function=self.get_input, cell=lstm_cell) with tf.variable_scope('logits'): logits_list = [ tf.expand_dims(self.char_logit(logit, i), dim=1) for i, logit in enumerate(lstm_outputs) ] return tf.concat(logits_list, 1)
[ "def", "create_logits", "(", "self", ")", ":", "with", "tf", ".", "variable_scope", "(", "'LSTM'", ")", ":", "first_label", "=", "self", ".", "get_input", "(", "prev", "=", "None", ",", "i", "=", "0", ")", "decoder_inputs", "=", "[", "first_label", "]", "+", "[", "None", "]", "*", "(", "self", ".", "_params", ".", "seq_length", "-", "1", ")", "lstm_cell", "=", "tf", ".", "contrib", ".", "rnn", ".", "LSTMCell", "(", "self", ".", "_mparams", ".", "num_lstm_units", ",", "use_peepholes", "=", "False", ",", "cell_clip", "=", "self", ".", "_mparams", ".", "lstm_state_clip_value", ",", "state_is_tuple", "=", "True", ",", "initializer", "=", "orthogonal_initializer", ")", "lstm_outputs", ",", "_", "=", "self", ".", "unroll_cell", "(", "decoder_inputs", "=", "decoder_inputs", ",", "initial_state", "=", "lstm_cell", ".", "zero_state", "(", "self", ".", "_batch_size", ",", "tf", ".", "float32", ")", ",", "loop_function", "=", "self", ".", "get_input", ",", "cell", "=", "lstm_cell", ")", "with", "tf", ".", "variable_scope", "(", "'logits'", ")", ":", "logits_list", "=", "[", "tf", ".", "expand_dims", "(", "self", ".", "char_logit", "(", "logit", ",", "i", ")", ",", "dim", "=", "1", ")", "for", "i", ",", "logit", "in", "enumerate", "(", "lstm_outputs", ")", "]", "return", "tf", ".", "concat", "(", "logits_list", ",", "1", ")" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/sequence_layers.py#L239-L268
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/sequence_layers.py
python
NetSlice.get_image_feature
(self, char_index)
return feature
Returns a subset of image features for a character. Args: char_index: an index of a character. Returns: A tensor with shape [batch_size, ?]. The output depth depends on the depth of input net.
Returns a subset of image features for a character.
[ "Returns", "a", "subset", "of", "image", "features", "for", "a", "character", "." ]
def get_image_feature(self, char_index): """Returns a subset of image features for a character. Args: char_index: an index of a character. Returns: A tensor with shape [batch_size, ?]. The output depth depends on the depth of input net. """ batch_size, features_num, _ = [d.value for d in self._net.get_shape()] slice_len = int(features_num / self._params.seq_length) # In case when features_num != seq_length, we just pick a subset of image # features, this choice is arbitrary and there is no intuitive geometrical # interpretation. If features_num is not dividable by seq_length there will # be unused image features. net_slice = self._net[:, char_index:char_index + slice_len, :] feature = tf.reshape(net_slice, [batch_size, -1]) logging.debug('Image feature: %s', feature) return feature
[ "def", "get_image_feature", "(", "self", ",", "char_index", ")", ":", "batch_size", ",", "features_num", ",", "_", "=", "[", "d", ".", "value", "for", "d", "in", "self", ".", "_net", ".", "get_shape", "(", ")", "]", "slice_len", "=", "int", "(", "features_num", "/", "self", ".", "_params", ".", "seq_length", ")", "# In case when features_num != seq_length, we just pick a subset of image", "# features, this choice is arbitrary and there is no intuitive geometrical", "# interpretation. If features_num is not dividable by seq_length there will", "# be unused image features.", "net_slice", "=", "self", ".", "_net", "[", ":", ",", "char_index", ":", "char_index", "+", "slice_len", ",", ":", "]", "feature", "=", "tf", ".", "reshape", "(", "net_slice", ",", "[", "batch_size", ",", "-", "1", "]", ")", "logging", ".", "debug", "(", "'Image feature: %s'", ",", "feature", ")", "return", "feature" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/sequence_layers.py#L280-L299
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/sequence_layers.py
python
NetSlice.get_eval_input
(self, prev, i)
return self.get_image_feature(i)
See SequenceLayerBase.get_eval_input for details.
See SequenceLayerBase.get_eval_input for details.
[ "See", "SequenceLayerBase", ".", "get_eval_input", "for", "details", "." ]
def get_eval_input(self, prev, i): """See SequenceLayerBase.get_eval_input for details.""" del prev return self.get_image_feature(i)
[ "def", "get_eval_input", "(", "self", ",", "prev", ",", "i", ")", ":", "del", "prev", "return", "self", ".", "get_image_feature", "(", "i", ")" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/sequence_layers.py#L301-L304
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/sequence_layers.py
python
NetSlice.get_train_input
(self, prev, i)
return self.get_eval_input(prev, i)
See SequenceLayerBase.get_train_input for details.
See SequenceLayerBase.get_train_input for details.
[ "See", "SequenceLayerBase", ".", "get_train_input", "for", "details", "." ]
def get_train_input(self, prev, i): """See SequenceLayerBase.get_train_input for details.""" return self.get_eval_input(prev, i)
[ "def", "get_train_input", "(", "self", ",", "prev", ",", "i", ")", ":", "return", "self", ".", "get_eval_input", "(", "prev", ",", "i", ")" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/sequence_layers.py#L306-L308
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/sequence_layers.py
python
NetSlice.unroll_cell
(self, decoder_inputs, initial_state, loop_function, cell)
return tf.contrib.legacy_seq2seq.rnn_decoder( decoder_inputs=decoder_inputs, initial_state=initial_state, cell=cell, loop_function=self.get_input)
See SequenceLayerBase.unroll_cell for details.
See SequenceLayerBase.unroll_cell for details.
[ "See", "SequenceLayerBase", ".", "unroll_cell", "for", "details", "." ]
def unroll_cell(self, decoder_inputs, initial_state, loop_function, cell): """See SequenceLayerBase.unroll_cell for details.""" return tf.contrib.legacy_seq2seq.rnn_decoder( decoder_inputs=decoder_inputs, initial_state=initial_state, cell=cell, loop_function=self.get_input)
[ "def", "unroll_cell", "(", "self", ",", "decoder_inputs", ",", "initial_state", ",", "loop_function", ",", "cell", ")", ":", "return", "tf", ".", "contrib", ".", "legacy_seq2seq", ".", "rnn_decoder", "(", "decoder_inputs", "=", "decoder_inputs", ",", "initial_state", "=", "initial_state", ",", "cell", "=", "cell", ",", "loop_function", "=", "self", ".", "get_input", ")" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/sequence_layers.py#L310-L316
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/sequence_layers.py
python
NetSliceWithAutoregression.get_eval_input
(self, prev, i)
return tf.concat([image_feature, prev], 1)
See SequenceLayerBase.get_eval_input for details.
See SequenceLayerBase.get_eval_input for details.
[ "See", "SequenceLayerBase", ".", "get_eval_input", "for", "details", "." ]
def get_eval_input(self, prev, i): """See SequenceLayerBase.get_eval_input for details.""" if i == 0: prev = self._zero_label else: logit = self.char_logit(prev, char_index=i - 1) prev = self.char_one_hot(logit) image_feature = self.get_image_feature(char_index=i) return tf.concat([image_feature, prev], 1)
[ "def", "get_eval_input", "(", "self", ",", "prev", ",", "i", ")", ":", "if", "i", "==", "0", ":", "prev", "=", "self", ".", "_zero_label", "else", ":", "logit", "=", "self", ".", "char_logit", "(", "prev", ",", "char_index", "=", "i", "-", "1", ")", "prev", "=", "self", ".", "char_one_hot", "(", "logit", ")", "image_feature", "=", "self", ".", "get_image_feature", "(", "char_index", "=", "i", ")", "return", "tf", ".", "concat", "(", "[", "image_feature", ",", "prev", "]", ",", "1", ")" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/sequence_layers.py#L329-L337
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/sequence_layers.py
python
NetSliceWithAutoregression.get_train_input
(self, prev, i)
return tf.concat([image_feature, prev], 1)
See SequenceLayerBase.get_train_input for details.
See SequenceLayerBase.get_train_input for details.
[ "See", "SequenceLayerBase", ".", "get_train_input", "for", "details", "." ]
def get_train_input(self, prev, i): """See SequenceLayerBase.get_train_input for details.""" if i == 0: prev = self._zero_label else: prev = self._labels_one_hot[:, i - 1, :] image_feature = self.get_image_feature(i) return tf.concat([image_feature, prev], 1)
[ "def", "get_train_input", "(", "self", ",", "prev", ",", "i", ")", ":", "if", "i", "==", "0", ":", "prev", "=", "self", ".", "_zero_label", "else", ":", "prev", "=", "self", ".", "_labels_one_hot", "[", ":", ",", "i", "-", "1", ",", ":", "]", "image_feature", "=", "self", ".", "get_image_feature", "(", "i", ")", "return", "tf", ".", "concat", "(", "[", "image_feature", ",", "prev", "]", ",", "1", ")" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/sequence_layers.py#L339-L346
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/sequence_layers.py
python
Attention.get_eval_input
(self, prev, i)
return self._zero_label
See SequenceLayerBase.get_eval_input for details.
See SequenceLayerBase.get_eval_input for details.
[ "See", "SequenceLayerBase", ".", "get_eval_input", "for", "details", "." ]
def get_eval_input(self, prev, i): """See SequenceLayerBase.get_eval_input for details.""" del prev, i # The attention_decoder will fetch image features from the net, no need for # extra inputs. return self._zero_label
[ "def", "get_eval_input", "(", "self", ",", "prev", ",", "i", ")", ":", "del", "prev", ",", "i", "# The attention_decoder will fetch image features from the net, no need for", "# extra inputs.", "return", "self", ".", "_zero_label" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/sequence_layers.py#L357-L362
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/sequence_layers.py
python
Attention.get_train_input
(self, prev, i)
return self.get_eval_input(prev, i)
See SequenceLayerBase.get_train_input for details.
See SequenceLayerBase.get_train_input for details.
[ "See", "SequenceLayerBase", ".", "get_train_input", "for", "details", "." ]
def get_train_input(self, prev, i): """See SequenceLayerBase.get_train_input for details.""" return self.get_eval_input(prev, i)
[ "def", "get_train_input", "(", "self", ",", "prev", ",", "i", ")", ":", "return", "self", ".", "get_eval_input", "(", "prev", ",", "i", ")" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/sequence_layers.py#L364-L366
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/sequence_layers.py
python
AttentionWithAutoregression.get_train_input
(self, prev, i)
See SequenceLayerBase.get_train_input for details.
See SequenceLayerBase.get_train_input for details.
[ "See", "SequenceLayerBase", ".", "get_train_input", "for", "details", "." ]
def get_train_input(self, prev, i): """See SequenceLayerBase.get_train_input for details.""" if i == 0: return self._zero_label else: # TODO(gorban): update to gradually introduce gt labels. return self._labels_one_hot[:, i - 1, :]
[ "def", "get_train_input", "(", "self", ",", "prev", ",", "i", ")", ":", "if", "i", "==", "0", ":", "return", "self", ".", "_zero_label", "else", ":", "# TODO(gorban): update to gradually introduce gt labels.", "return", "self", ".", "_labels_one_hot", "[", ":", ",", "i", "-", "1", ",", ":", "]" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/sequence_layers.py#L383-L389
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/sequence_layers.py
python
AttentionWithAutoregression.get_eval_input
(self, prev, i)
See SequenceLayerBase.get_eval_input for details.
See SequenceLayerBase.get_eval_input for details.
[ "See", "SequenceLayerBase", ".", "get_eval_input", "for", "details", "." ]
def get_eval_input(self, prev, i): """See SequenceLayerBase.get_eval_input for details.""" if i == 0: return self._zero_label else: logit = self.char_logit(prev, char_index=i - 1) return self.char_one_hot(logit)
[ "def", "get_eval_input", "(", "self", ",", "prev", ",", "i", ")", ":", "if", "i", "==", "0", ":", "return", "self", ".", "_zero_label", "else", ":", "logit", "=", "self", ".", "char_logit", "(", "prev", ",", "char_index", "=", "i", "-", "1", ")", "return", "self", ".", "char_one_hot", "(", "logit", ")" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/sequence_layers.py#L391-L397
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/train.py
python
create_optimizer
(hparams)
return optimizer
Creates optimized based on the specified flags.
Creates optimized based on the specified flags.
[ "Creates", "optimized", "based", "on", "the", "specified", "flags", "." ]
def create_optimizer(hparams): """Creates optimized based on the specified flags.""" if hparams.optimizer == 'momentum': optimizer = tf.train.MomentumOptimizer( hparams.learning_rate, momentum=hparams.momentum) elif hparams.optimizer == 'adam': optimizer = tf.train.AdamOptimizer(hparams.learning_rate) elif hparams.optimizer == 'adadelta': optimizer = tf.train.AdadeltaOptimizer(hparams.learning_rate) elif hparams.optimizer == 'adagrad': optimizer = tf.train.AdagradOptimizer(hparams.learning_rate) elif hparams.optimizer == 'rmsprop': optimizer = tf.train.RMSPropOptimizer( hparams.learning_rate, momentum=hparams.momentum) return optimizer
[ "def", "create_optimizer", "(", "hparams", ")", ":", "if", "hparams", ".", "optimizer", "==", "'momentum'", ":", "optimizer", "=", "tf", ".", "train", ".", "MomentumOptimizer", "(", "hparams", ".", "learning_rate", ",", "momentum", "=", "hparams", ".", "momentum", ")", "elif", "hparams", ".", "optimizer", "==", "'adam'", ":", "optimizer", "=", "tf", ".", "train", ".", "AdamOptimizer", "(", "hparams", ".", "learning_rate", ")", "elif", "hparams", ".", "optimizer", "==", "'adadelta'", ":", "optimizer", "=", "tf", ".", "train", ".", "AdadeltaOptimizer", "(", "hparams", ".", "learning_rate", ")", "elif", "hparams", ".", "optimizer", "==", "'adagrad'", ":", "optimizer", "=", "tf", ".", "train", ".", "AdagradOptimizer", "(", "hparams", ".", "learning_rate", ")", "elif", "hparams", ".", "optimizer", "==", "'rmsprop'", ":", "optimizer", "=", "tf", ".", "train", ".", "RMSPropOptimizer", "(", "hparams", ".", "learning_rate", ",", "momentum", "=", "hparams", ".", "momentum", ")", "return", "optimizer" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/train.py#L98-L112
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/train.py
python
train
(loss, init_fn, hparams)
Wraps slim.learning.train to run a training loop. Args: loss: a loss tensor init_fn: A callable to be executed after all other initialization is done. hparams: a model hyper parameters
Wraps slim.learning.train to run a training loop.
[ "Wraps", "slim", ".", "learning", ".", "train", "to", "run", "a", "training", "loop", "." ]
def train(loss, init_fn, hparams): """Wraps slim.learning.train to run a training loop. Args: loss: a loss tensor init_fn: A callable to be executed after all other initialization is done. hparams: a model hyper parameters """ optimizer = create_optimizer(hparams) if FLAGS.sync_replicas: replica_id = tf.constant(FLAGS.task, tf.int32, shape=()) optimizer = tf.LegacySyncReplicasOptimizer( opt=optimizer, replicas_to_aggregate=FLAGS.replicas_to_aggregate, replica_id=replica_id, total_num_replicas=FLAGS.total_num_replicas) sync_optimizer = optimizer startup_delay_steps = 0 else: startup_delay_steps = 0 sync_optimizer = None train_op = slim.learning.create_train_op( loss, optimizer, summarize_gradients=True, clip_gradient_norm=FLAGS.clip_gradient_norm) slim.learning.train( train_op=train_op, logdir=FLAGS.train_log_dir, graph=loss.graph, master=FLAGS.master, is_chief=(FLAGS.task == 0), number_of_steps=FLAGS.max_number_of_steps, save_summaries_secs=FLAGS.save_summaries_secs, save_interval_secs=FLAGS.save_interval_secs, startup_delay_steps=startup_delay_steps, sync_optimizer=sync_optimizer, init_fn=init_fn)
[ "def", "train", "(", "loss", ",", "init_fn", ",", "hparams", ")", ":", "optimizer", "=", "create_optimizer", "(", "hparams", ")", "if", "FLAGS", ".", "sync_replicas", ":", "replica_id", "=", "tf", ".", "constant", "(", "FLAGS", ".", "task", ",", "tf", ".", "int32", ",", "shape", "=", "(", ")", ")", "optimizer", "=", "tf", ".", "LegacySyncReplicasOptimizer", "(", "opt", "=", "optimizer", ",", "replicas_to_aggregate", "=", "FLAGS", ".", "replicas_to_aggregate", ",", "replica_id", "=", "replica_id", ",", "total_num_replicas", "=", "FLAGS", ".", "total_num_replicas", ")", "sync_optimizer", "=", "optimizer", "startup_delay_steps", "=", "0", "else", ":", "startup_delay_steps", "=", "0", "sync_optimizer", "=", "None", "train_op", "=", "slim", ".", "learning", ".", "create_train_op", "(", "loss", ",", "optimizer", ",", "summarize_gradients", "=", "True", ",", "clip_gradient_norm", "=", "FLAGS", ".", "clip_gradient_norm", ")", "slim", ".", "learning", ".", "train", "(", "train_op", "=", "train_op", ",", "logdir", "=", "FLAGS", ".", "train_log_dir", ",", "graph", "=", "loss", ".", "graph", ",", "master", "=", "FLAGS", ".", "master", ",", "is_chief", "=", "(", "FLAGS", ".", "task", "==", "0", ")", ",", "number_of_steps", "=", "FLAGS", ".", "max_number_of_steps", ",", "save_summaries_secs", "=", "FLAGS", ".", "save_summaries_secs", ",", "save_interval_secs", "=", "FLAGS", ".", "save_interval_secs", ",", "startup_delay_steps", "=", "startup_delay_steps", ",", "sync_optimizer", "=", "sync_optimizer", ",", "init_fn", "=", "init_fn", ")" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/train.py#L115-L155
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/data_provider.py
python
augment_image
(image)
return distorted_image
Augmentation the image with a random modification. Args: image: input Tensor image of rank 3, with the last dimension of size 3. Returns: Distorted Tensor image of the same shape.
Augmentation the image with a random modification.
[ "Augmentation", "the", "image", "with", "a", "random", "modification", "." ]
def augment_image(image): """Augmentation the image with a random modification. Args: image: input Tensor image of rank 3, with the last dimension of size 3. Returns: Distorted Tensor image of the same shape. """ with tf.variable_scope('AugmentImage'): height = image.get_shape().dims[0].value width = image.get_shape().dims[1].value # Random crop cut from the street sign image, resized to the same size. # Assures that the crop is covers at least 0.8 area of the input image. bbox_begin, bbox_size, _ = tf.image.sample_distorted_bounding_box( tf.shape(image), bounding_boxes=tf.zeros([0, 0, 4]), min_object_covered=0.8, aspect_ratio_range=[0.8, 1.2], area_range=[0.8, 1.0], use_image_if_no_bounding_boxes=True) distorted_image = tf.slice(image, bbox_begin, bbox_size) # Randomly chooses one of the 4 interpolation methods distorted_image = inception_preprocessing.apply_with_random_selector( distorted_image, lambda x, method: tf.image.resize_images(x, [height, width], method), num_cases=4) distorted_image.set_shape([height, width, 3]) # Color distortion distorted_image = inception_preprocessing.apply_with_random_selector( distorted_image, functools.partial( inception_preprocessing.distort_color, fast_mode=False), num_cases=4) distorted_image = tf.clip_by_value(distorted_image, -1.5, 1.5) return distorted_image
[ "def", "augment_image", "(", "image", ")", ":", "with", "tf", ".", "variable_scope", "(", "'AugmentImage'", ")", ":", "height", "=", "image", ".", "get_shape", "(", ")", ".", "dims", "[", "0", "]", ".", "value", "width", "=", "image", ".", "get_shape", "(", ")", ".", "dims", "[", "1", "]", ".", "value", "# Random crop cut from the street sign image, resized to the same size.", "# Assures that the crop is covers at least 0.8 area of the input image.", "bbox_begin", ",", "bbox_size", ",", "_", "=", "tf", ".", "image", ".", "sample_distorted_bounding_box", "(", "tf", ".", "shape", "(", "image", ")", ",", "bounding_boxes", "=", "tf", ".", "zeros", "(", "[", "0", ",", "0", ",", "4", "]", ")", ",", "min_object_covered", "=", "0.8", ",", "aspect_ratio_range", "=", "[", "0.8", ",", "1.2", "]", ",", "area_range", "=", "[", "0.8", ",", "1.0", "]", ",", "use_image_if_no_bounding_boxes", "=", "True", ")", "distorted_image", "=", "tf", ".", "slice", "(", "image", ",", "bbox_begin", ",", "bbox_size", ")", "# Randomly chooses one of the 4 interpolation methods", "distorted_image", "=", "inception_preprocessing", ".", "apply_with_random_selector", "(", "distorted_image", ",", "lambda", "x", ",", "method", ":", "tf", ".", "image", ".", "resize_images", "(", "x", ",", "[", "height", ",", "width", "]", ",", "method", ")", ",", "num_cases", "=", "4", ")", "distorted_image", ".", "set_shape", "(", "[", "height", ",", "width", ",", "3", "]", ")", "# Color distortion", "distorted_image", "=", "inception_preprocessing", ".", "apply_with_random_selector", "(", "distorted_image", ",", "functools", ".", "partial", "(", "inception_preprocessing", ".", "distort_color", ",", "fast_mode", "=", "False", ")", ",", "num_cases", "=", "4", ")", "distorted_image", "=", "tf", ".", "clip_by_value", "(", "distorted_image", ",", "-", "1.5", ",", "1.5", ")", "return", "distorted_image" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/data_provider.py#L49-L89
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/data_provider.py
python
central_crop
(image, crop_size)
Returns a central crop for the specified size of an image. Args: image: A tensor with shape [height, width, channels] crop_size: A tuple (crop_width, crop_height) Returns: A tensor of shape [crop_height, crop_width, channels].
Returns a central crop for the specified size of an image.
[ "Returns", "a", "central", "crop", "for", "the", "specified", "size", "of", "an", "image", "." ]
def central_crop(image, crop_size): """Returns a central crop for the specified size of an image. Args: image: A tensor with shape [height, width, channels] crop_size: A tuple (crop_width, crop_height) Returns: A tensor of shape [crop_height, crop_width, channels]. """ with tf.variable_scope('CentralCrop'): target_width, target_height = crop_size image_height, image_width = tf.shape(image)[0], tf.shape(image)[1] assert_op1 = tf.Assert( tf.greater_equal(image_height, target_height), ['image_height < target_height', image_height, target_height]) assert_op2 = tf.Assert( tf.greater_equal(image_width, target_width), ['image_width < target_width', image_width, target_width]) with tf.control_dependencies([assert_op1, assert_op2]): offset_width = (image_width - target_width) / 2 offset_height = (image_height - target_height) / 2 return tf.image.crop_to_bounding_box(image, offset_height, offset_width, target_height, target_width)
[ "def", "central_crop", "(", "image", ",", "crop_size", ")", ":", "with", "tf", ".", "variable_scope", "(", "'CentralCrop'", ")", ":", "target_width", ",", "target_height", "=", "crop_size", "image_height", ",", "image_width", "=", "tf", ".", "shape", "(", "image", ")", "[", "0", "]", ",", "tf", ".", "shape", "(", "image", ")", "[", "1", "]", "assert_op1", "=", "tf", ".", "Assert", "(", "tf", ".", "greater_equal", "(", "image_height", ",", "target_height", ")", ",", "[", "'image_height < target_height'", ",", "image_height", ",", "target_height", "]", ")", "assert_op2", "=", "tf", ".", "Assert", "(", "tf", ".", "greater_equal", "(", "image_width", ",", "target_width", ")", ",", "[", "'image_width < target_width'", ",", "image_width", ",", "target_width", "]", ")", "with", "tf", ".", "control_dependencies", "(", "[", "assert_op1", ",", "assert_op2", "]", ")", ":", "offset_width", "=", "(", "image_width", "-", "target_width", ")", "/", "2", "offset_height", "=", "(", "image_height", "-", "target_height", ")", "/", "2", "return", "tf", ".", "image", ".", "crop_to_bounding_box", "(", "image", ",", "offset_height", ",", "offset_width", ",", "target_height", ",", "target_width", ")" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/data_provider.py#L92-L115
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/data_provider.py
python
preprocess_image
(image, augment=False, central_crop_size=None, num_towers=4)
return image
Normalizes image to have values in a narrow range around zero. Args: image: a [H x W x 3] uint8 tensor. augment: optional, if True do random image distortion. central_crop_size: A tuple (crop_width, crop_height). num_towers: optional, number of shots of the same image in the input image. Returns: A float32 tensor of shape [H x W x 3] with RGB values in the required range.
Normalizes image to have values in a narrow range around zero.
[ "Normalizes", "image", "to", "have", "values", "in", "a", "narrow", "range", "around", "zero", "." ]
def preprocess_image(image, augment=False, central_crop_size=None, num_towers=4): """Normalizes image to have values in a narrow range around zero. Args: image: a [H x W x 3] uint8 tensor. augment: optional, if True do random image distortion. central_crop_size: A tuple (crop_width, crop_height). num_towers: optional, number of shots of the same image in the input image. Returns: A float32 tensor of shape [H x W x 3] with RGB values in the required range. """ with tf.variable_scope('PreprocessImage'): image = tf.image.convert_image_dtype(image, dtype=tf.float32) if augment or central_crop_size: if num_towers == 1: images = [image] else: images = tf.split(value=image, num_or_size_splits=num_towers, axis=1) if central_crop_size: view_crop_size = (central_crop_size[0] / num_towers, central_crop_size[1]) images = [central_crop(img, view_crop_size) for img in images] if augment: images = [augment_image(img) for img in images] image = tf.concat(images, 1) image = tf.subtract(image, 0.5) image = tf.multiply(image, 2.5) return image
[ "def", "preprocess_image", "(", "image", ",", "augment", "=", "False", ",", "central_crop_size", "=", "None", ",", "num_towers", "=", "4", ")", ":", "with", "tf", ".", "variable_scope", "(", "'PreprocessImage'", ")", ":", "image", "=", "tf", ".", "image", ".", "convert_image_dtype", "(", "image", ",", "dtype", "=", "tf", ".", "float32", ")", "if", "augment", "or", "central_crop_size", ":", "if", "num_towers", "==", "1", ":", "images", "=", "[", "image", "]", "else", ":", "images", "=", "tf", ".", "split", "(", "value", "=", "image", ",", "num_or_size_splits", "=", "num_towers", ",", "axis", "=", "1", ")", "if", "central_crop_size", ":", "view_crop_size", "=", "(", "central_crop_size", "[", "0", "]", "/", "num_towers", ",", "central_crop_size", "[", "1", "]", ")", "images", "=", "[", "central_crop", "(", "img", ",", "view_crop_size", ")", "for", "img", "in", "images", "]", "if", "augment", ":", "images", "=", "[", "augment_image", "(", "img", ")", "for", "img", "in", "images", "]", "image", "=", "tf", ".", "concat", "(", "images", ",", "1", ")", "image", "=", "tf", ".", "subtract", "(", "image", ",", "0.5", ")", "image", "=", "tf", ".", "multiply", "(", "image", ",", "2.5", ")", "return", "image" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/data_provider.py#L118-L150
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/data_provider.py
python
get_data
(dataset, batch_size, augment=False, central_crop_size=None, shuffle_config=None, shuffle=True)
return InputEndpoints( images=images, images_orig=images_orig, labels=labels, labels_one_hot=labels_one_hot)
Wraps calls to DatasetDataProviders and shuffle_batch. For more details about supported Dataset objects refer to datasets/fsns.py. Args: dataset: a slim.data.dataset.Dataset object. batch_size: number of samples per batch. augment: optional, if True does random image distortion. central_crop_size: A CharLogittuple (crop_width, crop_height). shuffle_config: A namedtuple ShuffleBatchConfig. shuffle: if True use data shuffling. Returns:
Wraps calls to DatasetDataProviders and shuffle_batch.
[ "Wraps", "calls", "to", "DatasetDataProviders", "and", "shuffle_batch", "." ]
def get_data(dataset, batch_size, augment=False, central_crop_size=None, shuffle_config=None, shuffle=True): """Wraps calls to DatasetDataProviders and shuffle_batch. For more details about supported Dataset objects refer to datasets/fsns.py. Args: dataset: a slim.data.dataset.Dataset object. batch_size: number of samples per batch. augment: optional, if True does random image distortion. central_crop_size: A CharLogittuple (crop_width, crop_height). shuffle_config: A namedtuple ShuffleBatchConfig. shuffle: if True use data shuffling. Returns: """ if not shuffle_config: shuffle_config = DEFAULT_SHUFFLE_CONFIG provider = slim.dataset_data_provider.DatasetDataProvider( dataset, shuffle=shuffle, common_queue_capacity=2 * batch_size, common_queue_min=batch_size) image_orig, label = provider.get(['image', 'label']) image = preprocess_image( image_orig, augment, central_crop_size, num_towers=dataset.num_of_views) label_one_hot = slim.one_hot_encoding(label, dataset.num_char_classes) images, images_orig, labels, labels_one_hot = (tf.train.shuffle_batch( [image, image_orig, label, label_one_hot], batch_size=batch_size, num_threads=shuffle_config.num_batching_threads, capacity=shuffle_config.queue_capacity, min_after_dequeue=shuffle_config.min_after_dequeue)) return InputEndpoints( images=images, images_orig=images_orig, labels=labels, labels_one_hot=labels_one_hot)
[ "def", "get_data", "(", "dataset", ",", "batch_size", ",", "augment", "=", "False", ",", "central_crop_size", "=", "None", ",", "shuffle_config", "=", "None", ",", "shuffle", "=", "True", ")", ":", "if", "not", "shuffle_config", ":", "shuffle_config", "=", "DEFAULT_SHUFFLE_CONFIG", "provider", "=", "slim", ".", "dataset_data_provider", ".", "DatasetDataProvider", "(", "dataset", ",", "shuffle", "=", "shuffle", ",", "common_queue_capacity", "=", "2", "*", "batch_size", ",", "common_queue_min", "=", "batch_size", ")", "image_orig", ",", "label", "=", "provider", ".", "get", "(", "[", "'image'", ",", "'label'", "]", ")", "image", "=", "preprocess_image", "(", "image_orig", ",", "augment", ",", "central_crop_size", ",", "num_towers", "=", "dataset", ".", "num_of_views", ")", "label_one_hot", "=", "slim", ".", "one_hot_encoding", "(", "label", ",", "dataset", ".", "num_char_classes", ")", "images", ",", "images_orig", ",", "labels", ",", "labels_one_hot", "=", "(", "tf", ".", "train", ".", "shuffle_batch", "(", "[", "image", ",", "image_orig", ",", "label", ",", "label_one_hot", "]", ",", "batch_size", "=", "batch_size", ",", "num_threads", "=", "shuffle_config", ".", "num_batching_threads", ",", "capacity", "=", "shuffle_config", ".", "queue_capacity", ",", "min_after_dequeue", "=", "shuffle_config", ".", "min_after_dequeue", ")", ")", "return", "InputEndpoints", "(", "images", "=", "images", ",", "images_orig", "=", "images_orig", ",", "labels", "=", "labels", ",", "labels_one_hot", "=", "labels_one_hot", ")" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/data_provider.py#L153-L199
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/metrics.py
python
char_accuracy
(predictions, targets, rej_char, streaming=False)
Computes character level accuracy. Both predictions and targets should have the same shape [batch_size x seq_length]. Args: predictions: predicted characters ids. targets: ground truth character ids. rej_char: the character id used to mark an empty element (end of sequence). streaming: if True, uses the streaming mean from the slim.metric module. Returns: a update_ops for execution and value tensor whose value on evaluation returns the total character accuracy.
Computes character level accuracy.
[ "Computes", "character", "level", "accuracy", "." ]
def char_accuracy(predictions, targets, rej_char, streaming=False): """Computes character level accuracy. Both predictions and targets should have the same shape [batch_size x seq_length]. Args: predictions: predicted characters ids. targets: ground truth character ids. rej_char: the character id used to mark an empty element (end of sequence). streaming: if True, uses the streaming mean from the slim.metric module. Returns: a update_ops for execution and value tensor whose value on evaluation returns the total character accuracy. """ with tf.variable_scope('CharAccuracy'): predictions.get_shape().assert_is_compatible_with(targets.get_shape()) targets = tf.to_int32(targets) const_rej_char = tf.constant(rej_char, shape=targets.get_shape()) weights = tf.to_float(tf.not_equal(targets, const_rej_char)) correct_chars = tf.to_float(tf.equal(predictions, targets)) accuracy_per_example = tf.div( tf.reduce_sum(tf.multiply(correct_chars, weights), 1), tf.reduce_sum(weights, 1)) if streaming: return tf.contrib.metrics.streaming_mean(accuracy_per_example) else: return tf.reduce_mean(accuracy_per_example)
[ "def", "char_accuracy", "(", "predictions", ",", "targets", ",", "rej_char", ",", "streaming", "=", "False", ")", ":", "with", "tf", ".", "variable_scope", "(", "'CharAccuracy'", ")", ":", "predictions", ".", "get_shape", "(", ")", ".", "assert_is_compatible_with", "(", "targets", ".", "get_shape", "(", ")", ")", "targets", "=", "tf", ".", "to_int32", "(", "targets", ")", "const_rej_char", "=", "tf", ".", "constant", "(", "rej_char", ",", "shape", "=", "targets", ".", "get_shape", "(", ")", ")", "weights", "=", "tf", ".", "to_float", "(", "tf", ".", "not_equal", "(", "targets", ",", "const_rej_char", ")", ")", "correct_chars", "=", "tf", ".", "to_float", "(", "tf", ".", "equal", "(", "predictions", ",", "targets", ")", ")", "accuracy_per_example", "=", "tf", ".", "div", "(", "tf", ".", "reduce_sum", "(", "tf", ".", "multiply", "(", "correct_chars", ",", "weights", ")", ",", "1", ")", ",", "tf", ".", "reduce_sum", "(", "weights", ",", "1", ")", ")", "if", "streaming", ":", "return", "tf", ".", "contrib", ".", "metrics", ".", "streaming_mean", "(", "accuracy_per_example", ")", "else", ":", "return", "tf", ".", "reduce_mean", "(", "accuracy_per_example", ")" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/metrics.py#L21-L50
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/metrics.py
python
sequence_accuracy
(predictions, targets, rej_char, streaming=False)
Computes sequence level accuracy. Both input tensors should have the same shape: [batch_size x seq_length]. Args: predictions: predicted character classes. targets: ground truth character classes. rej_char: the character id used to mark empty element (end of sequence). streaming: if True, uses the streaming mean from the slim.metric module. Returns: a update_ops for execution and value tensor whose value on evaluation returns the total sequence accuracy.
Computes sequence level accuracy.
[ "Computes", "sequence", "level", "accuracy", "." ]
def sequence_accuracy(predictions, targets, rej_char, streaming=False): """Computes sequence level accuracy. Both input tensors should have the same shape: [batch_size x seq_length]. Args: predictions: predicted character classes. targets: ground truth character classes. rej_char: the character id used to mark empty element (end of sequence). streaming: if True, uses the streaming mean from the slim.metric module. Returns: a update_ops for execution and value tensor whose value on evaluation returns the total sequence accuracy. """ with tf.variable_scope('SequenceAccuracy'): predictions.get_shape().assert_is_compatible_with(targets.get_shape()) targets = tf.to_int32(targets) const_rej_char = tf.constant( rej_char, shape=targets.get_shape(), dtype=tf.int32) include_mask = tf.not_equal(targets, const_rej_char) include_predictions = tf.to_int32( tf.where(include_mask, predictions, tf.zeros_like(predictions) + rej_char)) correct_chars = tf.to_float(tf.equal(include_predictions, targets)) correct_chars_counts = tf.cast( tf.reduce_sum(correct_chars, reduction_indices=[1]), dtype=tf.int32) target_length = targets.get_shape().dims[1].value target_chars_counts = tf.constant( target_length, shape=correct_chars_counts.get_shape()) accuracy_per_example = tf.to_float( tf.equal(correct_chars_counts, target_chars_counts)) if streaming: return tf.contrib.metrics.streaming_mean(accuracy_per_example) else: return tf.reduce_mean(accuracy_per_example)
[ "def", "sequence_accuracy", "(", "predictions", ",", "targets", ",", "rej_char", ",", "streaming", "=", "False", ")", ":", "with", "tf", ".", "variable_scope", "(", "'SequenceAccuracy'", ")", ":", "predictions", ".", "get_shape", "(", ")", ".", "assert_is_compatible_with", "(", "targets", ".", "get_shape", "(", ")", ")", "targets", "=", "tf", ".", "to_int32", "(", "targets", ")", "const_rej_char", "=", "tf", ".", "constant", "(", "rej_char", ",", "shape", "=", "targets", ".", "get_shape", "(", ")", ",", "dtype", "=", "tf", ".", "int32", ")", "include_mask", "=", "tf", ".", "not_equal", "(", "targets", ",", "const_rej_char", ")", "include_predictions", "=", "tf", ".", "to_int32", "(", "tf", ".", "where", "(", "include_mask", ",", "predictions", ",", "tf", ".", "zeros_like", "(", "predictions", ")", "+", "rej_char", ")", ")", "correct_chars", "=", "tf", ".", "to_float", "(", "tf", ".", "equal", "(", "include_predictions", ",", "targets", ")", ")", "correct_chars_counts", "=", "tf", ".", "cast", "(", "tf", ".", "reduce_sum", "(", "correct_chars", ",", "reduction_indices", "=", "[", "1", "]", ")", ",", "dtype", "=", "tf", ".", "int32", ")", "target_length", "=", "targets", ".", "get_shape", "(", ")", ".", "dims", "[", "1", "]", ".", "value", "target_chars_counts", "=", "tf", ".", "constant", "(", "target_length", ",", "shape", "=", "correct_chars_counts", ".", "get_shape", "(", ")", ")", "accuracy_per_example", "=", "tf", ".", "to_float", "(", "tf", ".", "equal", "(", "correct_chars_counts", ",", "target_chars_counts", ")", ")", "if", "streaming", ":", "return", "tf", ".", "contrib", ".", "metrics", ".", "streaming_mean", "(", "accuracy_per_example", ")", "else", ":", "return", "tf", ".", "reduce_mean", "(", "accuracy_per_example", ")" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/metrics.py#L53-L90
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/inception_preprocessing.py
python
apply_with_random_selector
(x, func, num_cases)
return control_flow_ops.merge([ func(control_flow_ops.switch(x, tf.equal(sel, case))[1], case) for case in range(num_cases) ])[0]
Computes func(x, sel), with sel sampled from [0...num_cases-1]. Args: x: input Tensor. func: Python function to apply. num_cases: Python int32, number of cases to sample sel from. Returns: The result of func(x, sel), where func receives the value of the selector as a python integer, but sel is sampled dynamically.
Computes func(x, sel), with sel sampled from [0...num_cases-1].
[ "Computes", "func", "(", "x", "sel", ")", "with", "sel", "sampled", "from", "[", "0", "...", "num_cases", "-", "1", "]", "." ]
def apply_with_random_selector(x, func, num_cases): """Computes func(x, sel), with sel sampled from [0...num_cases-1]. Args: x: input Tensor. func: Python function to apply. num_cases: Python int32, number of cases to sample sel from. Returns: The result of func(x, sel), where func receives the value of the selector as a python integer, but sel is sampled dynamically. """ sel = tf.random_uniform([], maxval=num_cases, dtype=tf.int32) # Pass the real x only to one of the func calls. return control_flow_ops.merge([ func(control_flow_ops.switch(x, tf.equal(sel, case))[1], case) for case in range(num_cases) ])[0]
[ "def", "apply_with_random_selector", "(", "x", ",", "func", ",", "num_cases", ")", ":", "sel", "=", "tf", ".", "random_uniform", "(", "[", "]", ",", "maxval", "=", "num_cases", ",", "dtype", "=", "tf", ".", "int32", ")", "# Pass the real x only to one of the func calls.", "return", "control_flow_ops", ".", "merge", "(", "[", "func", "(", "control_flow_ops", ".", "switch", "(", "x", ",", "tf", ".", "equal", "(", "sel", ",", "case", ")", ")", "[", "1", "]", ",", "case", ")", "for", "case", "in", "range", "(", "num_cases", ")", "]", ")", "[", "0", "]" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/inception_preprocessing.py#L29-L46
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/inception_preprocessing.py
python
distort_color
(image, color_ordering=0, fast_mode=True, scope=None)
Distort the color of a Tensor image. Each color distortion is non-commutative and thus ordering of the color ops matters. Ideally we would randomly permute the ordering of the color ops. Rather then adding that level of complication, we select a distinct ordering of color ops for each preprocessing thread. Args: image: 3-D Tensor containing single image in [0, 1]. color_ordering: Python int, a type of distortion (valid values: 0-3). fast_mode: Avoids slower ops (random_hue and random_contrast) scope: Optional scope for name_scope. Returns: 3-D Tensor color-distorted image on range [0, 1] Raises: ValueError: if color_ordering not in [0, 3]
Distort the color of a Tensor image.
[ "Distort", "the", "color", "of", "a", "Tensor", "image", "." ]
def distort_color(image, color_ordering=0, fast_mode=True, scope=None): """Distort the color of a Tensor image. Each color distortion is non-commutative and thus ordering of the color ops matters. Ideally we would randomly permute the ordering of the color ops. Rather then adding that level of complication, we select a distinct ordering of color ops for each preprocessing thread. Args: image: 3-D Tensor containing single image in [0, 1]. color_ordering: Python int, a type of distortion (valid values: 0-3). fast_mode: Avoids slower ops (random_hue and random_contrast) scope: Optional scope for name_scope. Returns: 3-D Tensor color-distorted image on range [0, 1] Raises: ValueError: if color_ordering not in [0, 3] """ with tf.name_scope(scope, 'distort_color', [image]): if fast_mode: if color_ordering == 0: image = tf.image.random_brightness(image, max_delta=32. / 255.) image = tf.image.random_saturation(image, lower=0.5, upper=1.5) else: image = tf.image.random_saturation(image, lower=0.5, upper=1.5) image = tf.image.random_brightness(image, max_delta=32. / 255.) else: if color_ordering == 0: image = tf.image.random_brightness(image, max_delta=32. / 255.) image = tf.image.random_saturation(image, lower=0.5, upper=1.5) image = tf.image.random_hue(image, max_delta=0.2) image = tf.image.random_contrast(image, lower=0.5, upper=1.5) elif color_ordering == 1: image = tf.image.random_saturation(image, lower=0.5, upper=1.5) image = tf.image.random_brightness(image, max_delta=32. / 255.) image = tf.image.random_contrast(image, lower=0.5, upper=1.5) image = tf.image.random_hue(image, max_delta=0.2) elif color_ordering == 2: image = tf.image.random_contrast(image, lower=0.5, upper=1.5) image = tf.image.random_hue(image, max_delta=0.2) image = tf.image.random_brightness(image, max_delta=32. / 255.) image = tf.image.random_saturation(image, lower=0.5, upper=1.5) elif color_ordering == 3: image = tf.image.random_hue(image, max_delta=0.2) image = tf.image.random_saturation(image, lower=0.5, upper=1.5) image = tf.image.random_contrast(image, lower=0.5, upper=1.5) image = tf.image.random_brightness(image, max_delta=32. / 255.) else: raise ValueError('color_ordering must be in [0, 3]') # The random_* ops do not necessarily clamp. return tf.clip_by_value(image, 0.0, 1.0)
[ "def", "distort_color", "(", "image", ",", "color_ordering", "=", "0", ",", "fast_mode", "=", "True", ",", "scope", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "scope", ",", "'distort_color'", ",", "[", "image", "]", ")", ":", "if", "fast_mode", ":", "if", "color_ordering", "==", "0", ":", "image", "=", "tf", ".", "image", ".", "random_brightness", "(", "image", ",", "max_delta", "=", "32.", "/", "255.", ")", "image", "=", "tf", ".", "image", ".", "random_saturation", "(", "image", ",", "lower", "=", "0.5", ",", "upper", "=", "1.5", ")", "else", ":", "image", "=", "tf", ".", "image", ".", "random_saturation", "(", "image", ",", "lower", "=", "0.5", ",", "upper", "=", "1.5", ")", "image", "=", "tf", ".", "image", ".", "random_brightness", "(", "image", ",", "max_delta", "=", "32.", "/", "255.", ")", "else", ":", "if", "color_ordering", "==", "0", ":", "image", "=", "tf", ".", "image", ".", "random_brightness", "(", "image", ",", "max_delta", "=", "32.", "/", "255.", ")", "image", "=", "tf", ".", "image", ".", "random_saturation", "(", "image", ",", "lower", "=", "0.5", ",", "upper", "=", "1.5", ")", "image", "=", "tf", ".", "image", ".", "random_hue", "(", "image", ",", "max_delta", "=", "0.2", ")", "image", "=", "tf", ".", "image", ".", "random_contrast", "(", "image", ",", "lower", "=", "0.5", ",", "upper", "=", "1.5", ")", "elif", "color_ordering", "==", "1", ":", "image", "=", "tf", ".", "image", ".", "random_saturation", "(", "image", ",", "lower", "=", "0.5", ",", "upper", "=", "1.5", ")", "image", "=", "tf", ".", "image", ".", "random_brightness", "(", "image", ",", "max_delta", "=", "32.", "/", "255.", ")", "image", "=", "tf", ".", "image", ".", "random_contrast", "(", "image", ",", "lower", "=", "0.5", ",", "upper", "=", "1.5", ")", "image", "=", "tf", ".", "image", ".", "random_hue", "(", "image", ",", "max_delta", "=", "0.2", ")", "elif", "color_ordering", "==", "2", ":", "image", "=", "tf", ".", "image", ".", "random_contrast", "(", "image", ",", "lower", "=", "0.5", ",", "upper", "=", "1.5", ")", "image", "=", "tf", ".", "image", ".", "random_hue", "(", "image", ",", "max_delta", "=", "0.2", ")", "image", "=", "tf", ".", "image", ".", "random_brightness", "(", "image", ",", "max_delta", "=", "32.", "/", "255.", ")", "image", "=", "tf", ".", "image", ".", "random_saturation", "(", "image", ",", "lower", "=", "0.5", ",", "upper", "=", "1.5", ")", "elif", "color_ordering", "==", "3", ":", "image", "=", "tf", ".", "image", ".", "random_hue", "(", "image", ",", "max_delta", "=", "0.2", ")", "image", "=", "tf", ".", "image", ".", "random_saturation", "(", "image", ",", "lower", "=", "0.5", ",", "upper", "=", "1.5", ")", "image", "=", "tf", ".", "image", ".", "random_contrast", "(", "image", ",", "lower", "=", "0.5", ",", "upper", "=", "1.5", ")", "image", "=", "tf", ".", "image", ".", "random_brightness", "(", "image", ",", "max_delta", "=", "32.", "/", "255.", ")", "else", ":", "raise", "ValueError", "(", "'color_ordering must be in [0, 3]'", ")", "# The random_* ops do not necessarily clamp.", "return", "tf", ".", "clip_by_value", "(", "image", ",", "0.0", ",", "1.0", ")" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/inception_preprocessing.py#L49-L100
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/inception_preprocessing.py
python
distorted_bounding_box_crop
(image, bbox, min_object_covered=0.1, aspect_ratio_range=(0.75, 1.33), area_range=(0.05, 1.0), max_attempts=100, scope=None)
Generates cropped_image using a one of the bboxes randomly distorted. See `tf.image.sample_distorted_bounding_box` for more documentation. Args: image: 3-D Tensor of image (it will be converted to floats in [0, 1]). bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords] where each coordinate is [0, 1) and the coordinates are arranged as [ymin, xmin, ymax, xmax]. If num_boxes is 0 then it would use the whole image. min_object_covered: An optional `float`. Defaults to `0.1`. The cropped area of the image must contain at least this fraction of any bounding box supplied. aspect_ratio_range: An optional list of `floats`. The cropped area of the image must have an aspect ratio = width / height within this range. area_range: An optional list of `floats`. The cropped area of the image must contain a fraction of the supplied image within in this range. max_attempts: An optional `int`. Number of attempts at generating a cropped region of the image of the specified constraints. After `max_attempts` failures, return the entire image. scope: Optional scope for name_scope. Returns: A tuple, a 3-D Tensor cropped_image and the distorted bbox
Generates cropped_image using a one of the bboxes randomly distorted.
[ "Generates", "cropped_image", "using", "a", "one", "of", "the", "bboxes", "randomly", "distorted", "." ]
def distorted_bounding_box_crop(image, bbox, min_object_covered=0.1, aspect_ratio_range=(0.75, 1.33), area_range=(0.05, 1.0), max_attempts=100, scope=None): """Generates cropped_image using a one of the bboxes randomly distorted. See `tf.image.sample_distorted_bounding_box` for more documentation. Args: image: 3-D Tensor of image (it will be converted to floats in [0, 1]). bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords] where each coordinate is [0, 1) and the coordinates are arranged as [ymin, xmin, ymax, xmax]. If num_boxes is 0 then it would use the whole image. min_object_covered: An optional `float`. Defaults to `0.1`. The cropped area of the image must contain at least this fraction of any bounding box supplied. aspect_ratio_range: An optional list of `floats`. The cropped area of the image must have an aspect ratio = width / height within this range. area_range: An optional list of `floats`. The cropped area of the image must contain a fraction of the supplied image within in this range. max_attempts: An optional `int`. Number of attempts at generating a cropped region of the image of the specified constraints. After `max_attempts` failures, return the entire image. scope: Optional scope for name_scope. Returns: A tuple, a 3-D Tensor cropped_image and the distorted bbox """ with tf.name_scope(scope, 'distorted_bounding_box_crop', [image, bbox]): # Each bounding box has shape [1, num_boxes, box coords] and # the coordinates are ordered [ymin, xmin, ymax, xmax]. # A large fraction of image datasets contain a human-annotated bounding # box delineating the region of the image containing the object of interest. # We choose to create a new bounding box for the object which is a randomly # distorted version of the human-annotated bounding box that obeys an # allowed range of aspect ratios, sizes and overlap with the human-annotated # bounding box. If no box is supplied, then we assume the bounding box is # the entire image. sample_distorted_bounding_box = tf.image.sample_distorted_bounding_box( tf.shape(image), bounding_boxes=bbox, min_object_covered=min_object_covered, aspect_ratio_range=aspect_ratio_range, area_range=area_range, max_attempts=max_attempts, use_image_if_no_bounding_boxes=True) bbox_begin, bbox_size, distort_bbox = sample_distorted_bounding_box # Crop the image to the specified bounding box. cropped_image = tf.slice(image, bbox_begin, bbox_size) return cropped_image, distort_bbox
[ "def", "distorted_bounding_box_crop", "(", "image", ",", "bbox", ",", "min_object_covered", "=", "0.1", ",", "aspect_ratio_range", "=", "(", "0.75", ",", "1.33", ")", ",", "area_range", "=", "(", "0.05", ",", "1.0", ")", ",", "max_attempts", "=", "100", ",", "scope", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "scope", ",", "'distorted_bounding_box_crop'", ",", "[", "image", ",", "bbox", "]", ")", ":", "# Each bounding box has shape [1, num_boxes, box coords] and", "# the coordinates are ordered [ymin, xmin, ymax, xmax].", "# A large fraction of image datasets contain a human-annotated bounding", "# box delineating the region of the image containing the object of interest.", "# We choose to create a new bounding box for the object which is a randomly", "# distorted version of the human-annotated bounding box that obeys an", "# allowed range of aspect ratios, sizes and overlap with the human-annotated", "# bounding box. If no box is supplied, then we assume the bounding box is", "# the entire image.", "sample_distorted_bounding_box", "=", "tf", ".", "image", ".", "sample_distorted_bounding_box", "(", "tf", ".", "shape", "(", "image", ")", ",", "bounding_boxes", "=", "bbox", ",", "min_object_covered", "=", "min_object_covered", ",", "aspect_ratio_range", "=", "aspect_ratio_range", ",", "area_range", "=", "area_range", ",", "max_attempts", "=", "max_attempts", ",", "use_image_if_no_bounding_boxes", "=", "True", ")", "bbox_begin", ",", "bbox_size", ",", "distort_bbox", "=", "sample_distorted_bounding_box", "# Crop the image to the specified bounding box.", "cropped_image", "=", "tf", ".", "slice", "(", "image", ",", "bbox_begin", ",", "bbox_size", ")", "return", "cropped_image", ",", "distort_bbox" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/inception_preprocessing.py#L103-L157
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/inception_preprocessing.py
python
preprocess_for_train
(image, height, width, bbox, fast_mode=True, scope=None)
Distort one image for training a network. Distorting images provides a useful technique for augmenting the data set during training in order to make the network invariant to aspects of the image that do not effect the label. Additionally it would create image_summaries to display the different transformations applied to the image. Args: image: 3-D Tensor of image. If dtype is tf.float32 then the range should be [0, 1], otherwise it would converted to tf.float32 assuming that the range is [0, MAX], where MAX is largest positive representable number for int(8/16/32) data type (see `tf.image.convert_image_dtype` for details). height: integer width: integer bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords] where each coordinate is [0, 1) and the coordinates are arranged as [ymin, xmin, ymax, xmax]. fast_mode: Optional boolean, if True avoids slower transformations (i.e. bi-cubic resizing, random_hue or random_contrast). scope: Optional scope for name_scope. Returns: 3-D float Tensor of distorted image used for training with range [-1, 1].
Distort one image for training a network.
[ "Distort", "one", "image", "for", "training", "a", "network", "." ]
def preprocess_for_train(image, height, width, bbox, fast_mode=True, scope=None): """Distort one image for training a network. Distorting images provides a useful technique for augmenting the data set during training in order to make the network invariant to aspects of the image that do not effect the label. Additionally it would create image_summaries to display the different transformations applied to the image. Args: image: 3-D Tensor of image. If dtype is tf.float32 then the range should be [0, 1], otherwise it would converted to tf.float32 assuming that the range is [0, MAX], where MAX is largest positive representable number for int(8/16/32) data type (see `tf.image.convert_image_dtype` for details). height: integer width: integer bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords] where each coordinate is [0, 1) and the coordinates are arranged as [ymin, xmin, ymax, xmax]. fast_mode: Optional boolean, if True avoids slower transformations (i.e. bi-cubic resizing, random_hue or random_contrast). scope: Optional scope for name_scope. Returns: 3-D float Tensor of distorted image used for training with range [-1, 1]. """ with tf.name_scope(scope, 'distort_image', [image, height, width, bbox]): if bbox is None: bbox = tf.constant( [0.0, 0.0, 1.0, 1.0], dtype=tf.float32, shape=[1, 1, 4]) if image.dtype != tf.float32: image = tf.image.convert_image_dtype(image, dtype=tf.float32) # Each bounding box has shape [1, num_boxes, box coords] and # the coordinates are ordered [ymin, xmin, ymax, xmax]. image_with_box = tf.image.draw_bounding_boxes( tf.expand_dims(image, 0), bbox) tf.summary.image('image_with_bounding_boxes', image_with_box) distorted_image, distorted_bbox = distorted_bounding_box_crop(image, bbox) # Restore the shape since the dynamic slice based upon the bbox_size loses # the third dimension. distorted_image.set_shape([None, None, 3]) image_with_distorted_box = tf.image.draw_bounding_boxes( tf.expand_dims(image, 0), distorted_bbox) tf.summary.image('images_with_distorted_bounding_box', image_with_distorted_box) # This resizing operation may distort the images because the aspect # ratio is not respected. We select a resize method in a round robin # fashion based on the thread number. # Note that ResizeMethod contains 4 enumerated resizing methods. # We select only 1 case for fast_mode bilinear. num_resize_cases = 1 if fast_mode else 4 distorted_image = apply_with_random_selector( distorted_image, lambda x, method: tf.image.resize_images(x, [height, width], method=method), num_cases=num_resize_cases) tf.summary.image('cropped_resized_image', tf.expand_dims(distorted_image, 0)) # Randomly flip the image horizontally. distorted_image = tf.image.random_flip_left_right(distorted_image) # Randomly distort the colors. There are 4 ways to do it. distorted_image = apply_with_random_selector( distorted_image, lambda x, ordering: distort_color(x, ordering, fast_mode), num_cases=4) tf.summary.image('final_distorted_image', tf.expand_dims(distorted_image, 0)) distorted_image = tf.subtract(distorted_image, 0.5) distorted_image = tf.multiply(distorted_image, 2.0) return distorted_image
[ "def", "preprocess_for_train", "(", "image", ",", "height", ",", "width", ",", "bbox", ",", "fast_mode", "=", "True", ",", "scope", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "scope", ",", "'distort_image'", ",", "[", "image", ",", "height", ",", "width", ",", "bbox", "]", ")", ":", "if", "bbox", "is", "None", ":", "bbox", "=", "tf", ".", "constant", "(", "[", "0.0", ",", "0.0", ",", "1.0", ",", "1.0", "]", ",", "dtype", "=", "tf", ".", "float32", ",", "shape", "=", "[", "1", ",", "1", ",", "4", "]", ")", "if", "image", ".", "dtype", "!=", "tf", ".", "float32", ":", "image", "=", "tf", ".", "image", ".", "convert_image_dtype", "(", "image", ",", "dtype", "=", "tf", ".", "float32", ")", "# Each bounding box has shape [1, num_boxes, box coords] and", "# the coordinates are ordered [ymin, xmin, ymax, xmax].", "image_with_box", "=", "tf", ".", "image", ".", "draw_bounding_boxes", "(", "tf", ".", "expand_dims", "(", "image", ",", "0", ")", ",", "bbox", ")", "tf", ".", "summary", ".", "image", "(", "'image_with_bounding_boxes'", ",", "image_with_box", ")", "distorted_image", ",", "distorted_bbox", "=", "distorted_bounding_box_crop", "(", "image", ",", "bbox", ")", "# Restore the shape since the dynamic slice based upon the bbox_size loses", "# the third dimension.", "distorted_image", ".", "set_shape", "(", "[", "None", ",", "None", ",", "3", "]", ")", "image_with_distorted_box", "=", "tf", ".", "image", ".", "draw_bounding_boxes", "(", "tf", ".", "expand_dims", "(", "image", ",", "0", ")", ",", "distorted_bbox", ")", "tf", ".", "summary", ".", "image", "(", "'images_with_distorted_bounding_box'", ",", "image_with_distorted_box", ")", "# This resizing operation may distort the images because the aspect", "# ratio is not respected. We select a resize method in a round robin", "# fashion based on the thread number.", "# Note that ResizeMethod contains 4 enumerated resizing methods.", "# We select only 1 case for fast_mode bilinear.", "num_resize_cases", "=", "1", "if", "fast_mode", "else", "4", "distorted_image", "=", "apply_with_random_selector", "(", "distorted_image", ",", "lambda", "x", ",", "method", ":", "tf", ".", "image", ".", "resize_images", "(", "x", ",", "[", "height", ",", "width", "]", ",", "method", "=", "method", ")", ",", "num_cases", "=", "num_resize_cases", ")", "tf", ".", "summary", ".", "image", "(", "'cropped_resized_image'", ",", "tf", ".", "expand_dims", "(", "distorted_image", ",", "0", ")", ")", "# Randomly flip the image horizontally.", "distorted_image", "=", "tf", ".", "image", ".", "random_flip_left_right", "(", "distorted_image", ")", "# Randomly distort the colors. There are 4 ways to do it.", "distorted_image", "=", "apply_with_random_selector", "(", "distorted_image", ",", "lambda", "x", ",", "ordering", ":", "distort_color", "(", "x", ",", "ordering", ",", "fast_mode", ")", ",", "num_cases", "=", "4", ")", "tf", ".", "summary", ".", "image", "(", "'final_distorted_image'", ",", "tf", ".", "expand_dims", "(", "distorted_image", ",", "0", ")", ")", "distorted_image", "=", "tf", ".", "subtract", "(", "distorted_image", ",", "0.5", ")", "distorted_image", "=", "tf", ".", "multiply", "(", "distorted_image", ",", "2.0", ")", "return", "distorted_image" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/inception_preprocessing.py#L160-L240
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/inception_preprocessing.py
python
preprocess_for_eval
(image, height, width, central_fraction=0.875, scope=None)
Prepare one image for evaluation. If height and width are specified it would output an image with that size by applying resize_bilinear. If central_fraction is specified it would cropt the central fraction of the input image. Args: image: 3-D Tensor of image. If dtype is tf.float32 then the range should be [0, 1], otherwise it would converted to tf.float32 assuming that the range is [0, MAX], where MAX is largest positive representable number for int(8/16/32) data type (see `tf.image.convert_image_dtype` for details) height: integer width: integer central_fraction: Optional Float, fraction of the image to crop. scope: Optional scope for name_scope. Returns: 3-D float Tensor of prepared image.
Prepare one image for evaluation.
[ "Prepare", "one", "image", "for", "evaluation", "." ]
def preprocess_for_eval(image, height, width, central_fraction=0.875, scope=None): """Prepare one image for evaluation. If height and width are specified it would output an image with that size by applying resize_bilinear. If central_fraction is specified it would cropt the central fraction of the input image. Args: image: 3-D Tensor of image. If dtype is tf.float32 then the range should be [0, 1], otherwise it would converted to tf.float32 assuming that the range is [0, MAX], where MAX is largest positive representable number for int(8/16/32) data type (see `tf.image.convert_image_dtype` for details) height: integer width: integer central_fraction: Optional Float, fraction of the image to crop. scope: Optional scope for name_scope. Returns: 3-D float Tensor of prepared image. """ with tf.name_scope(scope, 'eval_image', [image, height, width]): if image.dtype != tf.float32: image = tf.image.convert_image_dtype(image, dtype=tf.float32) # Crop the central region of the image with an area containing 87.5% of # the original image. if central_fraction: image = tf.image.central_crop(image, central_fraction=central_fraction) if height and width: # Resize the image to the specified height and width. image = tf.expand_dims(image, 0) image = tf.image.resize_bilinear( image, [height, width], align_corners=False) image = tf.squeeze(image, [0]) image = tf.subtract(image, 0.5) image = tf.multiply(image, 2.0) return image
[ "def", "preprocess_for_eval", "(", "image", ",", "height", ",", "width", ",", "central_fraction", "=", "0.875", ",", "scope", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "scope", ",", "'eval_image'", ",", "[", "image", ",", "height", ",", "width", "]", ")", ":", "if", "image", ".", "dtype", "!=", "tf", ".", "float32", ":", "image", "=", "tf", ".", "image", ".", "convert_image_dtype", "(", "image", ",", "dtype", "=", "tf", ".", "float32", ")", "# Crop the central region of the image with an area containing 87.5% of", "# the original image.", "if", "central_fraction", ":", "image", "=", "tf", ".", "image", ".", "central_crop", "(", "image", ",", "central_fraction", "=", "central_fraction", ")", "if", "height", "and", "width", ":", "# Resize the image to the specified height and width.", "image", "=", "tf", ".", "expand_dims", "(", "image", ",", "0", ")", "image", "=", "tf", ".", "image", ".", "resize_bilinear", "(", "image", ",", "[", "height", ",", "width", "]", ",", "align_corners", "=", "False", ")", "image", "=", "tf", ".", "squeeze", "(", "image", ",", "[", "0", "]", ")", "image", "=", "tf", ".", "subtract", "(", "image", ",", "0.5", ")", "image", "=", "tf", ".", "multiply", "(", "image", ",", "2.0", ")", "return", "image" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/inception_preprocessing.py#L243-L284
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/inception_preprocessing.py
python
preprocess_image
(image, height, width, is_training=False, bbox=None, fast_mode=True)
Pre-process one image for training or evaluation. Args: image: 3-D Tensor [height, width, channels] with the image. height: integer, image expected height. width: integer, image expected width. is_training: Boolean. If true it would transform an image for train, otherwise it would transform it for evaluation. bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords] where each coordinate is [0, 1) and the coordinates are arranged as [ymin, xmin, ymax, xmax]. fast_mode: Optional boolean, if True avoids slower transformations. Returns: 3-D float Tensor containing an appropriately scaled image Raises: ValueError: if user does not provide bounding box
Pre-process one image for training or evaluation.
[ "Pre", "-", "process", "one", "image", "for", "training", "or", "evaluation", "." ]
def preprocess_image(image, height, width, is_training=False, bbox=None, fast_mode=True): """Pre-process one image for training or evaluation. Args: image: 3-D Tensor [height, width, channels] with the image. height: integer, image expected height. width: integer, image expected width. is_training: Boolean. If true it would transform an image for train, otherwise it would transform it for evaluation. bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords] where each coordinate is [0, 1) and the coordinates are arranged as [ymin, xmin, ymax, xmax]. fast_mode: Optional boolean, if True avoids slower transformations. Returns: 3-D float Tensor containing an appropriately scaled image Raises: ValueError: if user does not provide bounding box """ if is_training: return preprocess_for_train(image, height, width, bbox, fast_mode) else: return preprocess_for_eval(image, height, width)
[ "def", "preprocess_image", "(", "image", ",", "height", ",", "width", ",", "is_training", "=", "False", ",", "bbox", "=", "None", ",", "fast_mode", "=", "True", ")", ":", "if", "is_training", ":", "return", "preprocess_for_train", "(", "image", ",", "height", ",", "width", ",", "bbox", ",", "fast_mode", ")", "else", ":", "return", "preprocess_for_eval", "(", "image", ",", "height", ",", "width", ")" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/inception_preprocessing.py#L287-L315
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/datasets/fsns.py
python
read_charset
(filename, null_character=u'\u2591')
return charset
Reads a charset definition from a tab separated text file. charset file has to have format compatible with the FSNS dataset. Args: filename: a path to the charset file. null_character: a unicode character used to replace '<null>' character. the default value is a light shade block '░'. Returns: a dictionary with keys equal to character codes and values - unicode characters.
Reads a charset definition from a tab separated text file.
[ "Reads", "a", "charset", "definition", "from", "a", "tab", "separated", "text", "file", "." ]
def read_charset(filename, null_character=u'\u2591'): """Reads a charset definition from a tab separated text file. charset file has to have format compatible with the FSNS dataset. Args: filename: a path to the charset file. null_character: a unicode character used to replace '<null>' character. the default value is a light shade block '░'. Returns: a dictionary with keys equal to character codes and values - unicode characters. """ pattern = re.compile(r'(\d+)\t(.+)') charset = {} with tf.gfile.GFile(filename) as f: for i, line in enumerate(f): m = pattern.match(line) if m is None: logging.warning('incorrect charset file. line #%d: %s', i, line) continue code = int(m.group(1)) #char = m.group(2).decode('utf-8') char = m.group(2) #print(char) if char == '<nul>': char = null_character charset[code] = char return charset
[ "def", "read_charset", "(", "filename", ",", "null_character", "=", "u'\\u2591'", ")", ":", "pattern", "=", "re", ".", "compile", "(", "r'(\\d+)\\t(.+)'", ")", "charset", "=", "{", "}", "with", "tf", ".", "gfile", ".", "GFile", "(", "filename", ")", "as", "f", ":", "for", "i", ",", "line", "in", "enumerate", "(", "f", ")", ":", "m", "=", "pattern", ".", "match", "(", "line", ")", "if", "m", "is", "None", ":", "logging", ".", "warning", "(", "'incorrect charset file. line #%d: %s'", ",", "i", ",", "line", ")", "continue", "code", "=", "int", "(", "m", ".", "group", "(", "1", ")", ")", "#char = m.group(2).decode('utf-8')", "char", "=", "m", ".", "group", "(", "2", ")", "#print(char)", "if", "char", "==", "'<nul>'", ":", "char", "=", "null_character", "charset", "[", "code", "]", "=", "char", "return", "charset" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/datasets/fsns.py#L59-L89
A-bone1/Attention-ocr-Chinese-Version
a08d4e587e73bb013cd22eadae250dbbf9cff7d4
python/datasets/fsns.py
python
get_split
(split_name, dataset_dir=None, config=None)
return slim.dataset.Dataset( data_sources=file_pattern, reader=tf.TFRecordReader, decoder=decoder, num_samples=config['splits'][split_name]['size'], items_to_descriptions=config['items_to_descriptions'], # additional parameters for convenience. charset=charset, num_char_classes=len(charset), num_of_views=config['num_of_views'], max_sequence_length=config['max_sequence_length'], null_code=config['null_code'])
Returns a dataset tuple for FSNS dataset. Args: split_name: A train/test split name. dataset_dir: The base directory of the dataset sources, by default it uses a predefined CNS path (see DEFAULT_DATASET_DIR). config: A dictionary with dataset configuration. If None - will use the DEFAULT_CONFIG. Returns: A `Dataset` namedtuple. Raises: ValueError: if `split_name` is not a valid train/test split.
Returns a dataset tuple for FSNS dataset.
[ "Returns", "a", "dataset", "tuple", "for", "FSNS", "dataset", "." ]
def get_split(split_name, dataset_dir=None, config=None): """Returns a dataset tuple for FSNS dataset. Args: split_name: A train/test split name. dataset_dir: The base directory of the dataset sources, by default it uses a predefined CNS path (see DEFAULT_DATASET_DIR). config: A dictionary with dataset configuration. If None - will use the DEFAULT_CONFIG. Returns: A `Dataset` namedtuple. Raises: ValueError: if `split_name` is not a valid train/test split. """ if not dataset_dir: dataset_dir = DEFAULT_DATASET_DIR if not config: config = DEFAULT_CONFIG if split_name not in config['splits']: raise ValueError('split name %s was not recognized.' % split_name) logging.info('Using %s dataset split_name=%s dataset_dir=%s', config['name'], split_name, dataset_dir) # Ignores the 'image/height' feature. zero = tf.zeros([1], dtype=tf.int64) keys_to_features = { 'image/encoded': tf.FixedLenFeature((), tf.string, default_value=''), 'image/format': tf.FixedLenFeature((), tf.string, default_value='png'), 'image/width': tf.FixedLenFeature([1], tf.int64, default_value=zero), 'image/orig_width': tf.FixedLenFeature([1], tf.int64, default_value=zero), 'image/class': tf.FixedLenFeature([config['max_sequence_length']], tf.int64), 'image/unpadded_class': tf.VarLenFeature(tf.int64), 'image/text': tf.FixedLenFeature([1], tf.string, default_value=''), } items_to_handlers = { 'image': slim.tfexample_decoder.Image( shape=config['image_shape'], image_key='image/encoded', format_key='image/format'), 'label': slim.tfexample_decoder.Tensor(tensor_key='image/class'), 'text': slim.tfexample_decoder.Tensor(tensor_key='image/text'), 'num_of_views': _NumOfViewsHandler( width_key='image/width', original_width_key='image/orig_width', num_of_views=config['num_of_views']) } decoder = slim.tfexample_decoder.TFExampleDecoder(keys_to_features, items_to_handlers) charset_file = os.path.join(dataset_dir, config['charset_filename']) charset = read_charset(charset_file) print(charset) file_pattern = os.path.join(dataset_dir, config['splits'][split_name]['pattern']) return slim.dataset.Dataset( data_sources=file_pattern, reader=tf.TFRecordReader, decoder=decoder, num_samples=config['splits'][split_name]['size'], items_to_descriptions=config['items_to_descriptions'], # additional parameters for convenience. charset=charset, num_char_classes=len(charset), num_of_views=config['num_of_views'], max_sequence_length=config['max_sequence_length'], null_code=config['null_code'])
[ "def", "get_split", "(", "split_name", ",", "dataset_dir", "=", "None", ",", "config", "=", "None", ")", ":", "if", "not", "dataset_dir", ":", "dataset_dir", "=", "DEFAULT_DATASET_DIR", "if", "not", "config", ":", "config", "=", "DEFAULT_CONFIG", "if", "split_name", "not", "in", "config", "[", "'splits'", "]", ":", "raise", "ValueError", "(", "'split name %s was not recognized.'", "%", "split_name", ")", "logging", ".", "info", "(", "'Using %s dataset split_name=%s dataset_dir=%s'", ",", "config", "[", "'name'", "]", ",", "split_name", ",", "dataset_dir", ")", "# Ignores the 'image/height' feature.", "zero", "=", "tf", ".", "zeros", "(", "[", "1", "]", ",", "dtype", "=", "tf", ".", "int64", ")", "keys_to_features", "=", "{", "'image/encoded'", ":", "tf", ".", "FixedLenFeature", "(", "(", ")", ",", "tf", ".", "string", ",", "default_value", "=", "''", ")", ",", "'image/format'", ":", "tf", ".", "FixedLenFeature", "(", "(", ")", ",", "tf", ".", "string", ",", "default_value", "=", "'png'", ")", ",", "'image/width'", ":", "tf", ".", "FixedLenFeature", "(", "[", "1", "]", ",", "tf", ".", "int64", ",", "default_value", "=", "zero", ")", ",", "'image/orig_width'", ":", "tf", ".", "FixedLenFeature", "(", "[", "1", "]", ",", "tf", ".", "int64", ",", "default_value", "=", "zero", ")", ",", "'image/class'", ":", "tf", ".", "FixedLenFeature", "(", "[", "config", "[", "'max_sequence_length'", "]", "]", ",", "tf", ".", "int64", ")", ",", "'image/unpadded_class'", ":", "tf", ".", "VarLenFeature", "(", "tf", ".", "int64", ")", ",", "'image/text'", ":", "tf", ".", "FixedLenFeature", "(", "[", "1", "]", ",", "tf", ".", "string", ",", "default_value", "=", "''", ")", ",", "}", "items_to_handlers", "=", "{", "'image'", ":", "slim", ".", "tfexample_decoder", ".", "Image", "(", "shape", "=", "config", "[", "'image_shape'", "]", ",", "image_key", "=", "'image/encoded'", ",", "format_key", "=", "'image/format'", ")", ",", "'label'", ":", "slim", ".", "tfexample_decoder", ".", "Tensor", "(", "tensor_key", "=", "'image/class'", ")", ",", "'text'", ":", "slim", ".", "tfexample_decoder", ".", "Tensor", "(", "tensor_key", "=", "'image/text'", ")", ",", "'num_of_views'", ":", "_NumOfViewsHandler", "(", "width_key", "=", "'image/width'", ",", "original_width_key", "=", "'image/orig_width'", ",", "num_of_views", "=", "config", "[", "'num_of_views'", "]", ")", "}", "decoder", "=", "slim", ".", "tfexample_decoder", ".", "TFExampleDecoder", "(", "keys_to_features", ",", "items_to_handlers", ")", "charset_file", "=", "os", ".", "path", ".", "join", "(", "dataset_dir", ",", "config", "[", "'charset_filename'", "]", ")", "charset", "=", "read_charset", "(", "charset_file", ")", "print", "(", "charset", ")", "file_pattern", "=", "os", ".", "path", ".", "join", "(", "dataset_dir", ",", "config", "[", "'splits'", "]", "[", "split_name", "]", "[", "'pattern'", "]", ")", "return", "slim", ".", "dataset", ".", "Dataset", "(", "data_sources", "=", "file_pattern", ",", "reader", "=", "tf", ".", "TFRecordReader", ",", "decoder", "=", "decoder", ",", "num_samples", "=", "config", "[", "'splits'", "]", "[", "split_name", "]", "[", "'size'", "]", ",", "items_to_descriptions", "=", "config", "[", "'items_to_descriptions'", "]", ",", "# additional parameters for convenience.", "charset", "=", "charset", ",", "num_char_classes", "=", "len", "(", "charset", ")", ",", "num_of_views", "=", "config", "[", "'num_of_views'", "]", ",", "max_sequence_length", "=", "config", "[", "'max_sequence_length'", "]", ",", "null_code", "=", "config", "[", "'null_code'", "]", ")" ]
https://github.com/A-bone1/Attention-ocr-Chinese-Version/blob/a08d4e587e73bb013cd22eadae250dbbf9cff7d4/python/datasets/fsns.py#L107-L188
A3M4/YouTube-Report
dcdbc29e8c05fca643da03ca0ae3fa7bd1b8d0a9
parse.py
python
HTML._find_times
(self)
return times
Find and format times within the HTML file. Returns ------- times : List[str] e.g. "19 Feb 2013, 11:56:19 UTC Tue"
Find and format times within the HTML file.
[ "Find", "and", "format", "times", "within", "the", "HTML", "file", "." ]
def _find_times(self): """ Find and format times within the HTML file. Returns ------- times : List[str] e.g. "19 Feb 2013, 11:56:19 UTC Tue" """ # Format all matched dates times = [ datetime_obj.strftime("%d %b %Y, %H:%M:%S UTC %a") for datetime_obj in self._find_times_datetime() ] return times
[ "def", "_find_times", "(", "self", ")", ":", "# Format all matched dates", "times", "=", "[", "datetime_obj", ".", "strftime", "(", "\"%d %b %Y, %H:%M:%S UTC %a\"", ")", "for", "datetime_obj", "in", "self", ".", "_find_times_datetime", "(", ")", "]", "return", "times" ]
https://github.com/A3M4/YouTube-Report/blob/dcdbc29e8c05fca643da03ca0ae3fa7bd1b8d0a9/parse.py#L93-L107
AIChallenger/AI_Challenger_2017
52014e0defbbdd85bf94ab05d308300d5764022f
Baselines/caption_baseline/build_tfrecord.py
python
_int64_feature
(value)
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
Wrapper for inserting an int64 Feature into a SequenceExample proto.
Wrapper for inserting an int64 Feature into a SequenceExample proto.
[ "Wrapper", "for", "inserting", "an", "int64", "Feature", "into", "a", "SequenceExample", "proto", "." ]
def _int64_feature(value): """Wrapper for inserting an int64 Feature into a SequenceExample proto.""" return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
[ "def", "_int64_feature", "(", "value", ")", ":", "return", "tf", ".", "train", ".", "Feature", "(", "int64_list", "=", "tf", ".", "train", ".", "Int64List", "(", "value", "=", "[", "value", "]", ")", ")" ]
https://github.com/AIChallenger/AI_Challenger_2017/blob/52014e0defbbdd85bf94ab05d308300d5764022f/Baselines/caption_baseline/build_tfrecord.py#L115-L117
AIChallenger/AI_Challenger_2017
52014e0defbbdd85bf94ab05d308300d5764022f
Baselines/caption_baseline/build_tfrecord.py
python
_bytes_feature
(value)
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[str(value)]))
Wrapper for inserting a bytes Feature into a SequenceExample proto.
Wrapper for inserting a bytes Feature into a SequenceExample proto.
[ "Wrapper", "for", "inserting", "a", "bytes", "Feature", "into", "a", "SequenceExample", "proto", "." ]
def _bytes_feature(value): """Wrapper for inserting a bytes Feature into a SequenceExample proto.""" return tf.train.Feature(bytes_list=tf.train.BytesList(value=[str(value)]))
[ "def", "_bytes_feature", "(", "value", ")", ":", "return", "tf", ".", "train", ".", "Feature", "(", "bytes_list", "=", "tf", ".", "train", ".", "BytesList", "(", "value", "=", "[", "str", "(", "value", ")", "]", ")", ")" ]
https://github.com/AIChallenger/AI_Challenger_2017/blob/52014e0defbbdd85bf94ab05d308300d5764022f/Baselines/caption_baseline/build_tfrecord.py#L120-L122
AIChallenger/AI_Challenger_2017
52014e0defbbdd85bf94ab05d308300d5764022f
Baselines/caption_baseline/build_tfrecord.py
python
_int64_feature_list
(values)
return tf.train.FeatureList(feature=[_int64_feature(v) for v in values])
Wrapper for inserting an int64 FeatureList into a SequenceExample proto.
Wrapper for inserting an int64 FeatureList into a SequenceExample proto.
[ "Wrapper", "for", "inserting", "an", "int64", "FeatureList", "into", "a", "SequenceExample", "proto", "." ]
def _int64_feature_list(values): """Wrapper for inserting an int64 FeatureList into a SequenceExample proto.""" return tf.train.FeatureList(feature=[_int64_feature(v) for v in values])
[ "def", "_int64_feature_list", "(", "values", ")", ":", "return", "tf", ".", "train", ".", "FeatureList", "(", "feature", "=", "[", "_int64_feature", "(", "v", ")", "for", "v", "in", "values", "]", ")" ]
https://github.com/AIChallenger/AI_Challenger_2017/blob/52014e0defbbdd85bf94ab05d308300d5764022f/Baselines/caption_baseline/build_tfrecord.py#L125-L127
AIChallenger/AI_Challenger_2017
52014e0defbbdd85bf94ab05d308300d5764022f
Baselines/caption_baseline/build_tfrecord.py
python
_bytes_feature_list
(values)
return tf.train.FeatureList(feature=[_bytes_feature(v) for v in values])
Wrapper for inserting a bytes FeatureList into a SequenceExample proto.
Wrapper for inserting a bytes FeatureList into a SequenceExample proto.
[ "Wrapper", "for", "inserting", "a", "bytes", "FeatureList", "into", "a", "SequenceExample", "proto", "." ]
def _bytes_feature_list(values): """Wrapper for inserting a bytes FeatureList into a SequenceExample proto.""" return tf.train.FeatureList(feature=[_bytes_feature(v) for v in values])
[ "def", "_bytes_feature_list", "(", "values", ")", ":", "return", "tf", ".", "train", ".", "FeatureList", "(", "feature", "=", "[", "_bytes_feature", "(", "v", ")", "for", "v", "in", "values", "]", ")" ]
https://github.com/AIChallenger/AI_Challenger_2017/blob/52014e0defbbdd85bf94ab05d308300d5764022f/Baselines/caption_baseline/build_tfrecord.py#L130-L132
AIChallenger/AI_Challenger_2017
52014e0defbbdd85bf94ab05d308300d5764022f
Baselines/caption_baseline/build_tfrecord.py
python
_to_sequence_example
(image, decoder, vocab)
return sequence_example
Builds a SequenceExample proto for an image-caption pair. Args: image: An ImageMetadata object. decoder: An ImageDecoder object. vocab: A Vocabulary object. Returns: A SequenceExample proto.
Builds a SequenceExample proto for an image-caption pair. Args: image: An ImageMetadata object. decoder: An ImageDecoder object. vocab: A Vocabulary object. Returns: A SequenceExample proto.
[ "Builds", "a", "SequenceExample", "proto", "for", "an", "image", "-", "caption", "pair", ".", "Args", ":", "image", ":", "An", "ImageMetadata", "object", ".", "decoder", ":", "An", "ImageDecoder", "object", ".", "vocab", ":", "A", "Vocabulary", "object", ".", "Returns", ":", "A", "SequenceExample", "proto", "." ]
def _to_sequence_example(image, decoder, vocab): """Builds a SequenceExample proto for an image-caption pair. Args: image: An ImageMetadata object. decoder: An ImageDecoder object. vocab: A Vocabulary object. Returns: A SequenceExample proto. """ with tf.gfile.FastGFile(image.filename, "r") as f: encoded_image = f.read() try: decoder.decode_jpeg(encoded_image) except (tf.errors.InvalidArgumentError, AssertionError): print("Skipping file with invalid JPEG data: %s" % image.filename) return context = tf.train.Features(feature={ "image/id": _int64_feature(image.id), "image/data": _bytes_feature(encoded_image), }) assert len(image.captions) == 1 caption = image.captions[0] caption_ids = [vocab.word_to_id(word) for word in caption] feature_lists = tf.train.FeatureLists(feature_list={ "image/caption": _bytes_feature_list(caption), "image/caption_ids": _int64_feature_list(caption_ids) }) sequence_example = tf.train.SequenceExample( context=context, feature_lists=feature_lists) return sequence_example
[ "def", "_to_sequence_example", "(", "image", ",", "decoder", ",", "vocab", ")", ":", "with", "tf", ".", "gfile", ".", "FastGFile", "(", "image", ".", "filename", ",", "\"r\"", ")", "as", "f", ":", "encoded_image", "=", "f", ".", "read", "(", ")", "try", ":", "decoder", ".", "decode_jpeg", "(", "encoded_image", ")", "except", "(", "tf", ".", "errors", ".", "InvalidArgumentError", ",", "AssertionError", ")", ":", "print", "(", "\"Skipping file with invalid JPEG data: %s\"", "%", "image", ".", "filename", ")", "return", "context", "=", "tf", ".", "train", ".", "Features", "(", "feature", "=", "{", "\"image/id\"", ":", "_int64_feature", "(", "image", ".", "id", ")", ",", "\"image/data\"", ":", "_bytes_feature", "(", "encoded_image", ")", ",", "}", ")", "assert", "len", "(", "image", ".", "captions", ")", "==", "1", "caption", "=", "image", ".", "captions", "[", "0", "]", "caption_ids", "=", "[", "vocab", ".", "word_to_id", "(", "word", ")", "for", "word", "in", "caption", "]", "feature_lists", "=", "tf", ".", "train", ".", "FeatureLists", "(", "feature_list", "=", "{", "\"image/caption\"", ":", "_bytes_feature_list", "(", "caption", ")", ",", "\"image/caption_ids\"", ":", "_int64_feature_list", "(", "caption_ids", ")", "}", ")", "sequence_example", "=", "tf", ".", "train", ".", "SequenceExample", "(", "context", "=", "context", ",", "feature_lists", "=", "feature_lists", ")", "return", "sequence_example" ]
https://github.com/AIChallenger/AI_Challenger_2017/blob/52014e0defbbdd85bf94ab05d308300d5764022f/Baselines/caption_baseline/build_tfrecord.py#L135-L167