本文整理汇总了Python中arelle.ModelDocument类的典型用法代码示例。如果您正苦于以下问题:Python ModelDocument类的具体用法?Python ModelDocument怎么用?Python ModelDocument使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ModelDocument类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: backgroundLoadXbrl
def backgroundLoadXbrl(self, filesource, importToDTS):
startedAt = time.time()
try:
if importToDTS:
action = _("imported")
modelXbrl = self.modelManager.modelXbrl
if modelXbrl:
ModelDocument.load(modelXbrl, filesource.url)
else:
action = _("loaded")
modelXbrl = self.modelManager.load(filesource, _("views loading"))
except Exception as err:
msg = _("Exception loading {0}: {1}, at {2}").format(
filesource.url,
err,
traceback.format_tb(sys.exc_info()[2]))
# not sure if message box can be shown from background thread
# tkinter.messagebox.showwarning(_("Exception loading"),msg, parent=self.parent)
self.addToLog(msg);
return
if modelXbrl and modelXbrl.modelDocument:
self.addToLog(format_string(self.modelManager.locale,
_("%s in %.2f secs"),
(action, time.time() - startedAt)))
self.showStatus(_("{0}, preparing views").format(action))
self.uiThreadQueue.put((self.showLoadedXbrl, [modelXbrl, importToDTS]))
else:
self.addToLog(format_string(self.modelManager.locale,
_("not successfully %s in %.2f secs"),
(action, time.time() - startedAt)))
示例2: load
def load(modelManager, url, nextaction=None, base=None, useFileSource=None):
if nextaction is None: nextaction = _("loading")
from arelle import (ModelDocument, FileSource)
modelXbrl = create(modelManager)
if useFileSource is not None:
modelXbrl.fileSource = useFileSource
modelXbrl.closeFileSource = False
url = url
elif isinstance(url,FileSource.FileSource):
modelXbrl.fileSource = url
modelXbrl.closeFileSource= True
url = modelXbrl.fileSource.url
else:
modelXbrl.fileSource = FileSource.FileSource(url)
modelXbrl.closeFileSource= True
modelXbrl.modelDocument = ModelDocument.load(modelXbrl, url, base, isEntry=True)
del modelXbrl.entryLoadingUrl
if modelXbrl.modelDocument is not None and modelXbrl.modelDocument.type < ModelDocument.Type.DTSENTRIES:
# at this point DTS is fully discovered but schemaLocated xsd's are not yet loaded
modelDocumentsSchemaLocated = set()
while True: # need this logic because each new pass may add new urlDocs
modelDocuments = set(modelXbrl.urlDocs.values()) - modelDocumentsSchemaLocated
if not modelDocuments:
break
modelDocument = modelDocuments.pop()
modelDocumentsSchemaLocated.add(modelDocument)
modelDocument.loadSchemalocatedSchemas()
#from arelle import XmlValidate
#uncomment for trial use of lxml xml schema validation of entry document
#XmlValidate.xmlValidate(modelXbrl.modelDocument)
modelManager.cntlr.webCache.saveUrlCheckTimes()
modelManager.showStatus(_("xbrl loading finished, {0}...").format(nextaction))
return modelXbrl
示例3: createInstance
def createInstance(self, url=None):
"""Creates an instance document for a DTS which didn't have an instance document, such as
to create a new instance for a DTS which was loaded from a taxonomy or linkbase entry point.
:param url: File name to save the new instance document
:type url: str
"""
from arelle import (ModelDocument, FileSource)
if self.modelDocument.type == ModelDocument.Type.INSTANCE: # entry already is an instance
return self.modelDocument # use existing instance entry point
priorFileSource = self.fileSource
self.fileSource = FileSource.FileSource(url)
if self.uri.startswith("http://"):
schemaRefUri = self.uri
else: # relativize local paths
schemaRefUri = os.path.relpath(self.uri, os.path.dirname(url))
self.modelDocument = ModelDocument.create(self, ModelDocument.Type.INSTANCE, url, schemaRefs=[schemaRefUri], isEntry=True)
if priorFileSource:
priorFileSource.close()
self.closeFileSource= True
del self.entryLoadingUrl
# reload dts views
from arelle import ViewWinDTS
for view in self.views:
if isinstance(view, ViewWinDTS.ViewDTS):
self.modelManager.cntlr.uiThreadQueue.put((view.view, []))
示例4: lookup
def lookup(self, document, proxyElement):
# check if proxyElement's namespace is not known
ns, sep, ln = proxyElement.tag.partition("}")
if sep:
ns = ns[1:]
else:
ln = ns
ns = None
if (ns and
ns not in self.discoveryAttempts and
ns not in self.modelXbrl.namespaceDocs):
# is schema loadable? requires a schemaLocation
from arelle import XmlUtil, ModelDocument
relativeUrl = XmlUtil.schemaLocation(proxyElement, ns)
self.discoveryAttempts.add(ns)
if relativeUrl:
doc = ModelDocument.loadSchemalocatedSchema(self.modelXbrl, proxyElement, relativeUrl, ns, self.baseUrl)
modelObjectClass = self.modelXbrl.matchSubstitutionGroup(
qnameNsLocalName(ns, ln),
elementSubstitutionModelClass)
if modelObjectClass is not None:
return modelObjectClass
else:
xlinkType = proxyElement.get("{http://www.w3.org/1999/xlink}type")
if xlinkType == "extended": return ModelLink
elif xlinkType == "locator": return ModelLocator
elif xlinkType == "resource": return ModelResource
return ModelObject
示例5: create
def create(modelManager, newDocumentType=None, url=None, schemaRefs=None, createModelDocument=True, isEntry=False):
from arelle import (ModelDocument, FileSource)
modelXbrl = ModelXbrl(modelManager)
modelXbrl.locale = modelManager.locale
if newDocumentType:
modelXbrl.fileSource = FileSource.FileSource(url) # url may be an open file handle, use str(url) below
modelXbrl.closeFileSource= True
if createModelDocument:
modelXbrl.modelDocument = ModelDocument.create(modelXbrl, newDocumentType, str(url), schemaRefs=schemaRefs, isEntry=isEntry)
if isEntry:
del modelXbrl.entryLoadingUrl
return modelXbrl
示例6: reload
def reload(self,nextaction,reloadCache=False):
"""Reloads all model objects from their original entry point URL, preserving any open views (which are reloaded).
:param nextAction: status line text string, if any, to show upon completion
:type nextAction: str
:param reloadCache: True to force clearing and reloading of web cache, if working online.
:param reloadCache: bool
"""
from arelle import ModelDocument
self.init(keepViews=True)
self.modelDocument = ModelDocument.load(self, self.fileSource.url, isEntry=True, reloadCache=reloadCache)
self.modelManager.showStatus(_("xbrl loading finished, {0}...").format(nextaction),5000)
self.modelManager.reloadViews(self)
示例7: load
def load(modelManager, url, nextaction=None, base=None, useFileSource=None, errorCaptureLevel=None):
"""Each loaded instance, DTS, testcase, testsuite, versioning report, or RSS feed, is represented by an
instance of a ModelXbrl object. The ModelXbrl object has a collection of ModelDocument objects, each
representing an XML document (for now, with SQL whenever its time comes). One of the modelDocuments of
the ModelXbrl is the entry point (of discovery or of the test suite).
:param url: may be a filename or FileSource object
:type url: str or FileSource
:param nextaction: text to use as status line prompt on conclusion of loading and discovery
:type nextaction: str
:param base: the base URL if any (such as a versioning report's URL when loading to/from DTS modelXbrl).
:type base: str
:param useFileSource: for internal use (when an entry point is in a FileSource archive and discovered files expected to also be in the entry point's archive.
:type useFileSource: bool
:returns: ModelXbrl -- a new modelXbrl, performing DTS discovery for instance, inline XBRL, schema, linkbase, and versioning report entry urls
"""
if nextaction is None: nextaction = _("loading")
from arelle import (ModelDocument, FileSource)
modelXbrl = create(modelManager, errorCaptureLevel=errorCaptureLevel)
if useFileSource is not None:
modelXbrl.fileSource = useFileSource
modelXbrl.closeFileSource = False
url = url
elif isinstance(url,FileSource.FileSource):
modelXbrl.fileSource = url
modelXbrl.closeFileSource= True
url = modelXbrl.fileSource.url
else:
modelXbrl.fileSource = FileSource.FileSource(url)
modelXbrl.closeFileSource= True
modelXbrl.modelDocument = ModelDocument.load(modelXbrl, url, base, isEntry=True)
del modelXbrl.entryLoadingUrl
if modelXbrl.modelDocument is not None and modelXbrl.modelDocument.type < ModelDocument.Type.DTSENTRIES:
# at this point DTS is fully discovered but schemaLocated xsd's are not yet loaded
modelDocumentsSchemaLocated = set()
while True: # need this logic because each new pass may add new urlDocs
modelDocuments = set(modelXbrl.urlDocs.values()) - modelDocumentsSchemaLocated
if not modelDocuments:
break
modelDocument = modelDocuments.pop()
modelDocumentsSchemaLocated.add(modelDocument)
modelDocument.loadSchemalocatedSchemas()
#from arelle import XmlValidate
#uncomment for trial use of lxml xml schema validation of entry document
#XmlValidate.xmlValidate(modelXbrl.modelDocument)
modelManager.cntlr.webCache.saveUrlCheckTimes()
modelManager.showStatus(_("xbrl loading finished, {0}...").format(nextaction))
return modelXbrl
示例8: xfxc_element
def xfxc_element(xc, p, contextItem, args):
if not 2 <= len(args) <= 4: raise XPathContext.FunctionNumArgs()
qn = qnameArg(xc, p, args, 0, 'QName', emptyFallback=None)
attrArg = args[1] if isinstance(args[1],(list,tuple)) else (args[1],)
# attributes have to be pairs
if attrArg:
if len(attrArg) & 1 or any(not isinstance(attrArg[i], (QName, _STR_BASE))
for i in range(0, len(attrArg),2)):
raise XPathContext.FunctionArgType(1,"((xs:qname|xs:string),xs:anyAtomicValue)", errCode="xfxce:AttributesNotNameValuePairs")
else:
attrParam = [(attrArg[i],attrArg[i+1]) # need name-value pairs for XmlUtil function
for i in range(0, len(attrArg),2)]
else:
attrParam = None
value = atomicArg(xc, p, args, 2, "xs:anyAtomicType", emptyFallback='')
if not value: # be sure '' is None so no text node is created
value = None
if len(args) < 4:
childElements = None
else:
childElements = xc.flattenSequence(args[3])
# scratchpad instance document emulates fn:doc( ) to hold XML nodes
scratchpadXmlDocUrl = "http://www.xbrl.org/2012/function/creation/xml_scratchpad.xml"
if scratchpadXmlDocUrl in xc.modelXbrl.urlDocs:
modelDocument = xc.modelXbrl.urlDocs[scratchpadXmlDocUrl]
else:
# create scratchpad xml document
# this will get the fake instance document in the list of modelXbrl docs so that it is garbage collected
from arelle import ModelDocument
modelDocument = ModelDocument.create(xc.modelXbrl,
ModelDocument.Type.UnknownXML,
scratchpadXmlDocUrl,
initialXml="<xfc:dummy xmlns:xfc='http://www.xbrl.org/2012/function/creation'/>")
newElement = XmlUtil.addChild(modelDocument.xmlRootElement,
qn,
attributes=attrParam,
text=value)
if childElements:
for element in childElements:
if isinstance(element, etree.ElementBase):
newElement.append(element)
# node myst be validated for use in instance creation (typed dimension references)
XmlValidate.validate(xc.modelXbrl, newElement)
return newElement
示例9: lookup
def lookup(self, document, proxyElement):
# check if proxyElement's namespace is not known
ns, sep, ln = proxyElement.tag.partition("}")
if sep:
ns = ns[1:]
else:
ln = ns
ns = None
if (ns and
ns not in self.discoveryAttempts and
ns not in self.modelXbrl.namespaceDocs):
# is schema loadable? requires a schemaLocation
relativeUrl = XmlUtil.schemaLocation(proxyElement, ns)
self.discoveryAttempts.add(ns)
if relativeUrl:
doc = ModelDocument.loadSchemalocatedSchema(self.modelXbrl, proxyElement, relativeUrl, ns, self.baseUrl)
modelObjectClass = self.modelXbrl.matchSubstitutionGroup(
qnameNsLocalName(ns, ln),
elementSubstitutionModelClass)
if modelObjectClass is not None:
return modelObjectClass
elif (self.streamingOrSkipDTS and
ns not in (XbrlConst.xbrli, XbrlConst.link)):
# self.makeelementParentModelObject is set in streamingExtensions.py and ModelXbrl.createFact
ancestor = proxyElement.getparent() or getattr(self.modelXbrl, "makeelementParentModelObject", None)
while ancestor is not None:
tag = ancestor.tag # not a modelObject yet, just parser prototype
if tag.startswith("{http://www.xbrl.org/2003/instance}") or tag.startswith("{http://www.xbrl.org/2003/linkbase}"):
if tag == "{http://www.xbrl.org/2003/instance}xbrl":
return ModelFact # element not parented by context or footnoteLink
else:
break # cannot be a fact
ancestor = ancestor.getparent()
xlinkType = proxyElement.get("{http://www.w3.org/1999/xlink}type")
if xlinkType == "extended": return ModelLink
elif xlinkType == "locator": return ModelLocator
elif xlinkType == "resource": return ModelResource
return ModelObject
示例10: createInstance
def createInstance(self, url=None):
from arelle import (ModelDocument, FileSource)
if self.modelDocument.type == ModelDocument.Type.INSTANCE: # entry already is an instance
return self.modelDocument # use existing instance entry point
priorFileSource = self.fileSource
self.fileSource = FileSource.FileSource(url)
if self.uri.startswith("http://"):
schemaRefUri = self.uri
else: # relativize local paths
schemaRefUri = os.path.relpath(self.uri, os.path.dirname(url))
self.modelDocument = ModelDocument.create(self, ModelDocument.Type.INSTANCE, url, schemaRefs=[schemaRefUri], isEntry=True)
if priorFileSource:
priorFileSource.close()
self.closeFileSource= True
del self.entryLoadingUrl
# reload dts views
from arelle import ViewWinDTS
for view in self.views:
if isinstance(view, ViewWinDTS.ViewDTS):
self.modelManager.cntlr.uiThreadQueue.put((view.view, []))
示例11: doc
def doc(xc, p, contextItem, args):
if len(args) != 1: raise XPathContext.FunctionNumArgs()
uri = stringArg(xc, args, 0, "xs:string", emptyFallback=None)
if uri is None:
return ()
if xc.progHeader is None or xc.progHeader.element is None:
raise XPathContext.XPathException(p, 'err:FODC0005', _('Function xf:doc no formula resource element for {0}').format(uri))
if not UrlUtil.isValid(uri):
raise XPathContext.XPathException(p, 'err:FODC0005', _('Function xf:doc $uri is not valid {0}').format(uri))
normalizedUri = xc.modelXbrl.modelManager.cntlr.webCache.normalizeUrl(
uri,
xc.progHeader.element.modelDocument.baseForElement(xc.progHeader.element))
if normalizedUri in xc.modelXbrl.urlDocs:
return xc.modelXbrl.urlDocs[normalizedUri].xmlDocument
modelDocument = ModelDocument.load(xc.modelXbrl, normalizedUri)
if modelDocument is None:
raise XPathContext.XPathException(p, 'err:FODC0005', _('Function xf:doc $uri not successfully loaded {0}').format(uri))
# assure that document is validated
XmlValidate.validate(xc.modelXbrl, modelDocument.xmlRootElement)
return modelDocument.xmlDocument
示例12: loadFromExcel
def loadFromExcel(cntlr, excelFile):
from arelle import xlrd
from arelle.xlrd.sheet import empty_cell
from arelle import ModelDocument, ModelXbrl, XmlUtil
from arelle.ModelDocument import ModelDocumentReference
from arelle.ModelValue import qname
startedAt = time.time()
importExcelBook = xlrd.open_workbook(excelFile)
controlSheet = importExcelBook.sheet_by_index(1)
imports = {"xbrli": ( ("namespace", XbrlConst.xbrli),
("schemaLocation", "http://www.xbrl.org/2003/xbrl-instance-2003-12-31.xsd") )} # xml of imports
importXmlns = {}
linkbaseRefs = []
labelLinkbases = []
hasPreLB = hasCalLB = hasDefLB = False
# xxxLB structure [ (elr1, def1, "_ELR_", [roots]), (elr2, def2, "_ELR_", [rootw]) ...]
# roots = (rootHref, None, "_root_", [children])
# children = (childPrefix, childName, arcrole, [grandChildren])
preLB = []
defLB = []
calLB = []
def lbDepthList(lbStruct, depth, parentList=None):
if depth == 0:
return lbStruct[-1].childStruct
return lbDepthList(lbStruct[-1].childStruct, depth-1, list)
extensionElements = {}
extensionRoles = {} # key is roleURI, value is role definition
extensionLabels = {} # key = (prefix, name, lang, role), value = label text
def extensionHref(prefix, name):
if prefix == extensionSchemaPrefix:
filename = extensionSchemaFilename
elif prefix in imports:
filename = imports[prefix][1][1]
else:
return None
return "{0}#{1}_{2}".format(filename, prefix, name)
isUSGAAP = False
for iRow in range(1, controlSheet.nrows):
try:
row = controlSheet.row(iRow)
if (row[0].ctype == xlrd.XL_CELL_EMPTY): # skip if col 1 is empty
continue
action = row[0].value
filetype = row[1].value
prefix = row[2].value
filename = row[3].value
namespaceURI = row[4].value
lbType = lang = None
if action == "import":
imports[prefix] = ( ("namespace", namespaceURI), ("schemaLocation", filename) )
importXmlns[prefix] = namespaceURI
if re.match(r"http://[^/]+/us-gaap/", namespaceURI):
isUSGAAP = True
elif action == "extension":
if filetype == "schema":
extensionSchemaPrefix = prefix
extensionSchemaFilename = filename
extensionSchemaNamespaceURI = namespaceURI
elif filetype == "linkbase":
typeLang = prefix.split()
if len(typeLang) > 0:
lbType = typeLang[0]
else:
lbType = "unknown"
if len(typeLang) > 1:
lang = typeLang[1]
else:
lang = "en"
if lbType == "label":
labelLinkbases.append((lang, filename))
elif lbType == "presentation":
hasPreLB = True
elif lbType == "definition":
hasDefLB = True
elif lbType == "calculation":
hasCalLB = True
linkbaseRefs.append( (lbType, filename) )
elif filetype == "role" and namespaceURI:
extensionRoles[namespaceURI] = filename
except Exception as err:
cntlr.addToLog("Exception: {error}, Excel row: {excelRow}"
.format(error=err,
excelRow=iRow),
messageCode="importExcel:exception")
importExcelSheet = importExcelBook.sheet_by_index(0)
# find column headers row
headerCols = {}
headerRows = set()
# find out which rows are header rows
for iRow in range(0, importExcelSheet.nrows):
row = importExcelSheet.row(iRow)
for iCol, colCell in enumerate(row):
#.........这里部分代码省略.........
示例13: watchCycle
#.........这里部分代码省略.........
postLoadAction)
if self.stopRequested:
modelXbrl.close()
break
emailAlert = False
if modelXbrl.modelDocument is None:
modelXbrl.error("arelle.rssWatch",
_("RSS item %(company)s %(form)s document not loaded: %(date)s"),
modelXbrl=modelXbrl, company=rssItem.companyName,
form=rssItem.formType, date=rssItem.filingDate)
rssItem.status = "not loadable"
else:
# validate schema, linkbase, or instance
if self.stopRequested:
modelXbrl.close()
break
if self.instValidator:
self.instValidator.validate(modelXbrl)
if modelXbrl.errors and rssWatchOptions.get("alertValiditionError"):
emailAlert = True
for pluginXbrlMethod in pluginClassMethods("RssWatch.DoWatchAction"):
pluginXbrlMethod(modelXbrl, rssWatchOptions, rssItem)
# check match expression
if matchPattern:
for fact in modelXbrl.factsInInstance:
v = fact.value
if v is not None:
m = matchPattern.search(v)
if m:
fr, to = m.span()
msg = _("Fact Variable {0}\n context {1}\n matched text: {2}").format(
fact.qname, fact.contextID, v[max(0,fr-20):to+20])
modelXbrl.info("arelle.rssInfo",
msg,
modelXbrl=modelXbrl) # msg as code passes it through to the status
if rssWatchOptions.get("alertMatchedFactText"):
emailAlert = True
if (rssWatchOptions.get("formulaFileUri") and rssWatchOptions.get("validateFormulaAssertions") and
self.instValidator):
# attach formulas
ModelDocument.load(modelXbrl, rssWatchOptions["formulaFileUri"])
ValidateFormula.validate(self.instValidator)
rssItem.setResults(modelXbrl)
modelXbrl.close()
del modelXbrl # completely dereference
self.rssModelXbrl.modelManager.viewModelObject(self.rssModelXbrl, rssItem.objectId())
if rssItem.assertionUnsuccessful and rssWatchOptions.get("alertAssertionUnsuccessful"):
emailAlert = True
msg = _("Filing CIK {0}\n "
"company {1}\n "
"published {2}\n "
"form type {3}\n "
"filing date {4}\n "
"period {5}\n "
"year end {6}\n "
"results: {7}").format(
rssItem.cikNumber,
rssItem.companyName,
rssItem.pubDate,
rssItem.formType,
rssItem.filingDate,
rssItem.period,
rssItem.fiscalYearEnd,
rssItem.status)
self.rssModelXbrl.info("arelle:rssWatch", msg, modelXbrl=self.rssModelXbrl)
emailAddress = rssWatchOptions.get("emailAddress")
if emailAlert and emailAddress:
self.rssModelXbrl.modelManager.showStatus(_("sending e-mail alert"))
import smtplib
from email.mime.text import MIMEText
emailMsg = MIMEText(msg)
emailMsg["Subject"] = _("Arelle RSS Watch alert on {0}").format(rssItem.companyName)
emailMsg["From"] = emailAddress
emailMsg["To"] = emailAddress
smtp = smtplib.SMTP()
smtp.sendmail(emailAddress, [emailAddress], emailMsg.as_string())
smtp.quit()
self.rssModelXbrl.modelManager.showStatus(_("RSS item {0}, {1} completed, status {2}").format(rssItem.companyName, rssItem.formType, rssItem.status), 3500)
self.rssModelXbrl.modelManager.cntlr.rssWatchUpdateOption(rssItem.pubDate.strftime('%Y-%m-%dT%H:%M:%S'))
except Exception as err:
self.rssModelXbrl.error("arelle.rssError",
_("RSS item %(company)s, %(form)s, %(date)s, exception: %(error)s"),
modelXbrl=self.rssModelXbrl, company=rssItem.companyName,
form=rssItem.formType, date=rssItem.filingDate, error=err,
exc_info=True)
if self.stopRequested: break
if self.stopRequested:
self.cntlr.showStatus(_("RSS watch, stop requested"), 10000)
else:
import time
time.sleep(600)
self.thread = None # close thread
self.stopRequested = False
示例14: loadFromExcel
def loadFromExcel(cntlr, excelFile):
from openpyxl import load_workbook
from arelle import ModelDocument, ModelXbrl, XmlUtil
from arelle.ModelDocument import ModelDocumentReference
from arelle.ModelValue import qname
startedAt = time.time()
if os.path.isabs(excelFile):
# allow relative filenames to loading directory
priorCWD = os.getcwd()
os.chdir(os.path.dirname(excelFile))
else:
priorCWD = None
importExcelBook = load_workbook(excelFile, read_only=True, data_only=True)
sheetNames = importExcelBook.get_sheet_names()
if "DTS" in sheetNames:
dtsWs = importExcelBook["DTS"]
elif "Sheet2" in sheetNames:
dtsWs = importExcelBook["Sheet2"]
else:
dtsWs = None
imports = {"xbrli": ( ("namespace", XbrlConst.xbrli),
("schemaLocation", "http://www.xbrl.org/2003/xbrl-instance-2003-12-31.xsd") )} # xml of imports
importXmlns = {}
linkbaseRefs = []
labelLinkbases = []
hasPreLB = hasCalLB = hasDefLB = False
# xxxLB structure [ (elr1, def1, "_ELR_", [roots]), (elr2, def2, "_ELR_", [rootw]) ...]
# roots = (rootHref, None, "_root_", [children])
# children = (childPrefix, childName, arcrole, [grandChildren])
preLB = []
defLB = []
calLB = []
def lbDepthList(lbStruct, depth, parentList=None):
if depth == topDepth:
if len(lbStruct) > 0:
return lbStruct[-1].childStruct
else:
cntlr.addToLog("Depth error, Excel row: {excelRow}"
.format(excelRow=iRow),
messageCode="importExcel:depth")
return None
return lbDepthList(lbStruct[-1].childStruct, depth-1, list)
extensionElements = {}
extensionRoles = {} # key is roleURI, value is role definition
extensionLabels = {} # key = (prefix, name, lang, role), value = label text
importSheetName = None
skipRows = [] # [(from,to),(from,to)] row number starting at 1
def extensionHref(prefix, name):
if prefix == extensionSchemaPrefix:
filename = extensionSchemaFilename
elif prefix in imports:
filename = imports[prefix][1][1]
else:
return None
return "{0}#{1}_{2}".format(filename, prefix, name)
isUSGAAP = False
for iRow, row in enumerate(dtsWs.rows if dtsWs else ()):
try:
if (len(row) < 1 or row[0].value is None): # skip if col 1 is empty
continue
action = filetype = prefix = filename = namespaceURI = None
if len(row) > 0: action = row[0].value
if len(row) > 1: filetype = row[1].value
if len(row) > 2: prefix = row[2].value
if len(row) > 3: filename = row[3].value
if len(row) > 4: namespaceURI = row[4].value
lbType = lang = None
if action == "import":
imports[prefix] = ( ("namespace", namespaceURI), ("schemaLocation", filename) )
importXmlns[prefix] = namespaceURI
if re.match(r"http://[^/]+/us-gaap/", namespaceURI):
isUSGAAP = True
elif action == "extension":
if filetype == "schema":
extensionSchemaPrefix = prefix
extensionSchemaFilename = filename
extensionSchemaNamespaceURI = namespaceURI
elif filetype == "linkbase":
typeLang = prefix.split()
if len(typeLang) > 0:
lbType = typeLang[0]
else:
lbType = "unknown"
if len(typeLang) > 1:
lang = typeLang[1]
else:
lang = "en"
if lbType == "label":
labelLinkbases.append((lang, filename))
elif lbType == "presentation":
hasPreLB = True
elif lbType == "definition":
hasDefLB = True
elif lbType == "calculation":
#.........这里部分代码省略.........
示例15: run
def run(self, options, sourceZipStream=None):
self.entrypointFile = options.entrypointFile
filesource = FileSource.openFileSource(self.entrypointFile, self, sourceZipStream)
if options.validateEFM:
if options.gfmName:
self.addToLog(_("both --efm and --gfm validation are requested, proceeding with --efm only"),
messageCode="info", file=self.entrypointFile)
self.modelManager.validateDisclosureSystem = True
self.modelManager.disclosureSystem.select("efm")
elif options.gfmName:
self.modelManager.validateDisclosureSystem = True
self.modelManager.disclosureSystem.select(options.gfmName)
elif options.validateHMRC:
self.modelManager.validateDisclosureSystem = True
self.modelManager.disclosureSystem.select("hmrc")
else:
self.modelManager.disclosureSystem.select(None) # just load ordinary mappings
if options.calcDecimals:
if options.calcPrecision:
self.addToLog(_("both --calcDecimals and --calcPrecision validation are requested, proceeding with --calcDecimals only"),
messageCode="info", file=self.entrypointFile)
self.modelManager.validateInferDecimals = True
self.modelManager.validateCalcLB = True
elif options.calcPrecision:
self.modelManager.validateInferDecimals = False
self.modelManager.validateCalcLB = True
if options.utrValidate:
self.modelManager.validateUtr = True
fo = FormulaOptions()
if options.parameters:
fo.parameterValues = dict(((qname(key, noPrefixIsNoNamespace=True),(None,value))
for param in options.parameters.split(',')
for key,sep,value in (param.partition('='),) ) )
if options.formulaParamExprResult:
fo.traceParameterExpressionResult = True
if options.formulaParamInputValue:
fo.traceParameterInputValue = True
if options.formulaCallExprSource:
fo.traceCallExpressionSource = True
if options.formulaCallExprCode:
fo.traceCallExpressionCode = True
if options.formulaCallExprEval:
fo.traceCallExpressionEvaluation = True
if options.formulaCallExprResult:
fo.traceCallExpressionResult = True
if options.formulaVarSetExprEval:
fo.traceVariableSetExpressionEvaluation = True
if options.formulaVarSetExprResult:
fo.traceVariableSetExpressionResult = True
if options.formulaAsserResultCounts:
fo.traceAssertionResultCounts = True
if options.formulaFormulaRules:
fo.traceFormulaRules = True
if options.formulaVarsOrder:
fo.traceVariablesOrder = True
if options.formulaVarExpressionSource:
fo.traceVariableExpressionSource = True
if options.formulaVarExpressionCode:
fo.traceVariableExpressionCode = True
if options.formulaVarExpressionEvaluation:
fo.traceVariableExpressionEvaluation = True
if options.formulaVarExpressionResult:
fo.traceVariableExpressionResult = True
if options.formulaVarFilterWinnowing:
fo.traceVariableFilterWinnowing = True
if options.formulaVarFiltersResult:
fo.traceVariableFiltersResult = True
self.modelManager.formulaOptions = fo
timeNow = XmlUtil.dateunionValue(datetime.datetime.now())
startedAt = time.time()
modelDiffReport = None
success = True
modelXbrl = None
try:
modelXbrl = self.modelManager.load(filesource, _("views loading"))
except Exception as err:
self.addToLog(_("[Exception] Failed to complete request: \n{0} \n{1}").format(
err,
traceback.format_tb(sys.exc_info()[2])))
success = False # loading errors, don't attempt to utilize loaded DTS
if modelXbrl and modelXbrl.modelDocument:
self.addToLog(format_string(self.modelManager.locale,
_("loaded in %.2f secs at %s"),
(time.time() - startedAt, timeNow)),
messageCode="info", file=self.entrypointFile)
if options.importFiles:
for importFile in options.importFiles.split("|"):
ModelDocument.load(modelXbrl, importFile.strip())
self.addToLog(format_string(self.modelManager.locale,
_("imported in %.2f secs at %s"),
(time.time() - startedAt, timeNow)),
messageCode="info", file=importFile)
if modelXbrl.errors:
success = False # loading errors, don't attempt to utilize loaded DTS
else:
success = False
if success and options.diffFile and options.versReportFile:
diffFilesource = FileSource.FileSource(options.diffFile,self)
startedAt = time.time()
modelXbrl2 = self.modelManager.load(diffFilesource, _("views loading"))
#.........这里部分代码省略.........