desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Overwrite the component item at position i with item @param i: the index within the component list @param item: the item'
def __setitem__(self, i, item):
self.components.__setitem__(i, item)
'Return the component at index i and remove it from the list @param i: the component index'
def pop(self, i=(-1)):
return self.components.pop(i)
'Get the top level item of this navigation tree'
def get_root(self):
parent = self.parent if parent: return parent.get_root() else: return self
'Get the full path to this item (=a list of items from the root item down to this item).'
def path(self, sub=None):
path = [self] if sub: path.extend(sub) if self.parent: return self.parent.path(sub=path) else: return path
'Get all components with these flags @param flags: dictionary of flags'
def get_all(self, **flags):
items = [] for item in self.components: if ((not flags) or all([(getattr(item, f) == flags[f]) for f in flags])): items.append(item) return items
'Get the first component item with these flags @param flags: dictionary of flags'
def get_first(self, **flags):
for item in self.components: if ((not flags) or all([(getattr(item, f) == flags[f]) for f in flags])): return item return None
'Get the first component item with these flags @param flags: dictionary of flags'
def get_last(self, **flags):
components = list(self.components) components.reverse() for item in components: if ((not flags) or all([(getattr(item, f) == flags[f]) for f in flags])): return item return None
'The total number of components of this item'
def __len__(self):
return len(self.components)
'To be used instead of __len__ to determine the boolean value if this item, should always return True for instances'
def __nonzero__(self):
return (self is not None)
'Get the index of a component item within the component list @param item: the item'
def index(self, item):
return self.components.index(item)
'Get the position of this item within the parent\'s component list, reverse method for index()'
def pos(self):
if self.parent: return self.parent.index(self) else: return None
'Check whether this is the first item within the parent\'s components list with these flags @param flags: dictionary of flags'
def is_first(self, **flags):
if (not flags): return (len(self.preceding()) == 0) if (not all([(getattr(self, f) == flags[f]) for f in flags])): return False preceding = self.preceding() if preceding: for item in preceding: if all([(getattr(item, f) == flags[f]) for f in flags]): r...
'Check whether this is the last item within the parent\'s components list with these flags @param flags: dictionary of flags'
def is_last(self, **flags):
if (not flags): return (len(self.following()) == 0) if (not all([(getattr(self, f) == flags[f]) for f in flags])): return False following = self.following() if following: for item in following: if all([(getattr(item, f) == flags[f]) for f in flags]): r...
'Get the preceding siblings within the parent\'s component list'
def preceding(self):
parent = self.parent if parent: pos = self.pos() if (pos is not None): return parent.components[:pos] return []
'Get the following siblings within the parent\'s component list'
def following(self):
parent = self.parent if parent: items = parent.components pos = self.pos() if (pos is not None): pos = (pos + 1) if (pos < len(items)): return items[pos:] return []
'Get the previous item in the parent\'s component list with these flags @param flags: dictionary of flags'
def get_prev(self, **flags):
preceding = self.preceding() preceding.reverse() for item in preceding: if ((not flags) or all([(getattr(item, f) == flags[f]) for f in flags])): return item return None
'Get the next item in the parent\'s component list with these flags @param flags: dictionary of flags'
def get_next(self, **flags):
following = self.following() for item in following: if ((not flags) or all([(getattr(item, f) == flags[f]) for f in flags])): return item return None
'Constructor @param tabs: the tabs configuration as list of names or tuples (label, name)'
def __init__(self, tabs=None):
if (not tabs): self.tabs = [] else: self.tabs = [S3ComponentTab(t) for t in tabs if t]
'Render the tabs row @param r: the S3Request'
def render(self, r):
rheader_tabs = [] if r.resource.get_config('dynamic_components'): self.dynamic_tabs(r.resource.tablename) tabs = tuple((t for t in self.tabs if t.active(r))) mtab = False if (r.component is None): for t in tabs: if (t.component == r.method): mtab = True ...
'Add dynamic tabs @param master: the name of the master table'
def dynamic_tabs(self, master):
T = current.T s3db = current.s3db tabs = self.tabs if (not tabs): return ftable = s3db.s3_field query = ((((ftable.component_key == True) & (ftable.component_tab == True)) & (ftable.master == master)) & (ftable.deleted == False)) rows = current.db(query).select(ftable.component_alias...
'Constructor @param tab: the component tab configuration as tuple (label, component_alias, {get_vars}), where the get_vars dict is optional.'
def __init__(self, tab):
(title, component) = tab[:2] if (component and (component.find('/') > 0)): (function, component) = component.split('/', 1) else: function = None self.title = title self.native = False if function: self.function = function else: self.function = None if comp...
'Check whether the this tab is active @param r: the S3Request'
def active(self, r):
s3db = current.s3db get_components = s3db.get_components get_method = s3db.get_method get_vars = r.get_vars tablename = None if ('viewing' in get_vars): try: tablename = get_vars['viewing'].split('.', 1)[0] except: pass resource = r.resource compon...
'Check permissions for component tabs (in order to deactivate tabs the user is not permitted to access) @param hook: the component hook'
def authorised(self, hook):
READ = 'read' has_permission = current.auth.s3_has_permission if (hook.linktable and (not has_permission(READ, hook.linktable))): return False if has_permission(READ, hook.tablename): return True return False
'Check whether the request GET vars match the GET vars in the URL of this tab @param r: the S3Request'
def vars_match(self, r):
get_vars = r.get_vars if (self.vars is None): return True for (k, v) in self.vars.iteritems(): if (v is None): continue if ((k not in get_vars) or ((k in get_vars) and (get_vars[k] != v))): return False return True
'@param script: script to inject into jquery_ready when rendered'
def __init__(self, script=None, **attributes):
self.script = script return super(S3ScriptItem, self).__init__(attributes)
'Injects associated script into jquery_ready.'
def xml(self):
if self.script: current.response.s3.jquery_ready.append(self.script) return ''
'Present to ensure that script injected even in inline forms'
@staticmethod def inline(item):
return ''
'Constructor @param fields: the fields to display as list of lists of fieldnames, Field instances or callables @param tabs: the tabs Fields are specified in order rows->cols, i.e. if written like: ["fieldA", "fieldF", "fieldX"], ["fieldB", None, "fieldY"] then that\'s exactly the screen order. Row or column spans are n...
def __init__(self, fields=None, tabs=None):
self.fields = fields self.tabs = tabs
'Return the HTML representation of this rheader @param r: the S3Request instance to render the header for @param tabs: the tabs (overrides the original tabs definition) @param table: override r.table @param record: override r.record @param as_div: True: will return the rheader_fields and the rheader_tabs together as a ...
def __call__(self, r, tabs=None, table=None, record=None, as_div=True):
if (table is None): table = r.table if (record is None): record = r.record if (tabs is None): tabs = self.tabs if ((self.fields is None) and ('name' in table.fields)): fields = [['name']] else: fields = self.fields if record: if (tabs is not None):...
'Entry point for REST interface @param r: the S3Request @param attr: controller attributes'
def apply_method(self, r, **attr):
if ('w' in r.get_vars): return self.ajax(r, **attr) else: return self.summary(r, **attr)
'Render the summary page @param r: the S3Request @param attr: controller attributes'
def summary(self, r, **attr):
output = {} response = current.response resource = self.resource get_config = resource.get_config config = self._get_config(resource) crud_string = self.crud_string title = crud_string(self.tablename, 'title_list') output['title'] = title tablist = UL() sections = [] commons ...
'Render a specific widget for pulling-in via AJAX @param r: the S3Request @param attr: controller attributes'
def ajax(self, r, **attr):
config = self._get_config(self.resource) widget_id = r.get_vars.get('w') i = 0 for section in config: widgets = section.get('widgets', []) for widget in widgets: if (widget_id == ('summary-%s' % i)): method = widget.get('method', None) output =...
'Get the summary page configuration @param resource: the target S3Resource'
@staticmethod def _get_config(resource):
get_config = resource.get_config config = get_config('summary', current.deployment_settings.get_ui_summary()) if (not config): config = [{'name': 'table', 'label': 'Table', 'widgets': [{'name': 'datatable', 'method': 'datatable'}]}] return config
'Apply CRUD methods @param r: the S3Request @param attr: dictionary of parameters for the method handler The attributes that it knows about are: * componentname * formname * list_fields * report_groupby * report_hide_comments @return: output object to send to the view'
def apply_method(self, r, **attr):
def getParam(key): "\n nested function to get the parameters passed into apply_method\n\n @todo find out if this has been done better ...
'create a dictionary of fields with errors @param tree: S3ImportJob.error_tree @return: errordict'
def __parse_job_error_tree(self, tree):
errordict = {} for resource in tree: resourcename = resource.attrib.get('name') for field in resource: fieldname = field.attrib.get('field') error = field.attrib.get('error') if error: errordict[('%s-%s' % (resourcename, fieldname))] = error ...
'Calculate the Damerau-Levenshtein distance between sequences. This distance is the number of additions, deletions, substitutions, and transpositions needed to transform the first sequence into the second. Although generally used with strings, any sequences of comparable objects will work. Transpositions are exchanges ...
def dameraulevenshtein(self, seq1, seq2):
oneago = None thisrow = (range(1, (len(seq2) + 1)) + [0]) for x in xrange(len(seq1)): (twoago, oneago, thisrow) = (oneago, thisrow, (([0] * len(seq2)) + [(x + 1)])) for y in xrange(len(seq2)): delcost = (oneago[y] + 1) addcost = (thisrow[(y - 1)] + 1) subc...
'convert data generated from ocr parser to a dictionary @param s3dataxml: output of S3OCRImageParser @return: python dictionary equalant to the input xml'
def __temp_ocrdataxml_parser(self, s3ocrdataxml):
s3ocrdataxml_etree = etree.fromstring(s3ocrdataxml) s3ocrdatadict = Storage() s3xml_root = s3ocrdataxml_etree resource_element = s3xml_root.getchildren()[0] s3ocr_root = etree.Element('s3ocr') if self.r.component: s3ocr_root.append(resource_element) else: componentetrees = []...
'convert data from import job into a dictionary @param importjob: S3ImportJob instance @return: data of S3ImportJob into a dictionary'
def __importjob2data(self, importjob):
s3ocrdata = Storage() import_item_dict = importjob.items for eachitem in import_item_dict.keys(): import_item = import_item_dict[eachitem] if (import_item.data and (len(import_item.data) > 0)): s3ocrdata[str(import_item.table)] = import_item.data return s3ocrdata
'create a html review form using the available data @param s3ocrdict: output of self.__s3ocrxml2dict() @param s3ocrdata: output of self.__importjob2data() @return: html review form'
def __create_review_form(self, s3ocrdict, s3ocrdata):
ptablecontent = [] fieldnum = 1 request = current.request T = current.T r = self.r setuuid = self.setuuid if r.component: request_args = request.get('args', ['', '']) record_id = request_args[0] component_name = request_args[1] urlprefix = ('%s/%s/%s' % (reque...
'convert s3ocrxml to dictionary so that it can be used in templates @param s3ocrxml: content of a s3ocrxml file, in text @return: equivalent dictionary for s3ocrxml file'
def __s3ocrxml2dict(self, s3ocrxml):
db = current.db s3ocr_etree = etree.fromstring(s3ocrxml) s3ocrdict = Storage() resource_seq = [] for resource in s3ocr_etree: resourcename = resource.attrib.get('name') table = db[resourcename] s3ocrdict[resourcename] = Storage() resource_seq.append(resourcename) ...
'This will create a new empty PDF document. Data then needs to be added to this document. @param title: The title that will appear at the top of the document and in the filename @return: An empty pdf document'
def newDocument(self, title, header, footer, filename=None, heading=None):
now = self.request.now.isoformat()[:19].replace('T', ' ') docTitle = ('%s %s' % (title, now)) if (filename == None): self.filename = ('%s_%s.pdf' % (title, now)) else: self.filename = ('%s_%s.pdf' % (filename, now)) self.output = StringIO() self.doc = EdenDocTemplate(self.o...
'Get all form UUIDs/Revs available for a given resource @return: a list of all available forms for the given resource, the list will contain tuples such that the first value is form-uuid and the second value is form-revision'
def __getResourceForms(self):
db = current.db table = db.ocr_meta query = (table.resource_name == self.resource.tablename) rows = db(query).select(table.form_uuid, table.revision, orderby=(~ table.revision)) availForms = [] append = availForms.append for row in rows: append({'uuid': row.form_uuid, 'revision': row...
'Gets Number of pages for given form UUID @param formuuid: uuid of the form, for which number of pages is required @return: number of pages in a form identified by uuid'
def __getNumPages(self, formuuid):
db = current.db table = db.ocr_meta row = db((table.form_uuid == formuuid)).select(table.pages, limitby=(0, 1)).first() return int(row.pages)
'Optimise & Modifiy s3xml etree to and produce s3ocr etree @return: s3ocr etree'
def __s3OCREtree(self):
r = self.r s3xml_etree = self.resource.export_struct(options=True, references=True, stylesheet=None, as_json=False, as_tree=True) ITEXT = 'label' HINT = 'comment' TYPE = 'type' HASOPTIONS = 'has_options' LINES = 'lines' BOXES = 'boxes' REFERENCE = 'reference' RESOURCE = 'resource...
'Produces OCR Compatible PDF forms'
def OCRPDFManager(self):
T = current.T s3ocr_root = self.__s3OCREtree() self.s3ocrxml = etree.tostring(s3ocr_root, pretty_print=DEBUG) self.content = [] s3ocr_layout_etree = self.layoutEtree ITEXT = 'label' HINT = 'comment' TYPE = 'type' HASOPTIONS = 'has_options' LINES = 'lines' BOXES = 'boxes' ...
'return layout file @return: layout xml for the generated OCR form'
def __getOCRLayout(self):
prettyprint = (True if DEBUG else False) return etree.tostring(self.layoutEtree, pretty_print=prettyprint)
'Helper to trim off any enclosing paranthesis @param text: text which need to be trimmed @return: text with front and rear paranthesis stripped'
@staticmethod def __trim(text):
if (isinstance(text, str) and (text[0] == '(') and (text[(-1)] == ')')): text = text[1:(-1)] return text
'Store the PDF layout information into the database/disk. @param formUUID: uuid of the generated form @param layoutXML: layout xml of the generated form @param numPages: number of pages in the generated form'
def __update_dbmeta(self, formUUID, layoutXML, numPages):
layout_file_stream = StringIO(layoutXML) layout_file_name = ('%s_xml' % formUUID) s3ocrxml_file_stream = StringIO(self.s3ocrxml) s3ocrxml_file_name = ('%s_ocrxml' % formUUID) db = current.db table = db.ocr_meta rows = db((table.form_uuid == formUUID)).select() row = rows[0] row.updat...
'Books a revision number for current operation in ocr_meta @param formUUID: uuid of the generated form @param formResourceName: name of the eden resource'
@staticmethod def __book_revision(formUUID, formResourceName):
db = current.db table = current.s3db.ocr_meta import uuid revision = uuid.uuid5(formUUID, formResourceName).hex.upper()[:6] table.insert(form_uuid=formUUID, resource_name=formResourceName, revision=revision) return revision
'Method to extract a generic title from the resource using the crud strings @param: resource: a S3Resource object @return: the title as a String'
@staticmethod def defaultTitle(resource):
try: return current.response.s3.crud_strings.get(resource.table._tablename).get('title_list') except: return current.T(resource.name.replace('_', ' ')).decode('utf-8')
'Method to set the margins of the document @param left: the size of the left margin, default None @param right: the size of the right margin, default None @param top: the size of the top margin, default None @param bottom: the size of the bottom margin, default None The margin is only changed if a value is provided, ot...
def setMargins(self, left=None, right=None, top=None, bottom=None):
if (left != None): self.doc.leftMargin = left self.leftMargin = left else: self.doc.leftMargin = self.leftMargin if (right != None): self.doc.rightMargin = right self.rightMargin = right else: self.doc.rightMargin = self.rightMargin if (top != None): ...
'Method to set the orientation of the document to be portrait @todo: make this for a page rather than the document'
def setPortrait(self):
self.doc.pagesize = portrait(self.paper_size)
'Method to set the orientation of the document to be landscape @todo: make this for a page rather than the document'
def setLandscape(self):
self.doc.pagesize = landscape(self.paper_size)
'Method to create a table that will be inserted into the document @param resource: A S3Resource object @param list_Fields: A list of field names @param report_groupby: A field name that is to be used as a sub-group All the records that share the same report_groupby value will be clustered together @param report_hide_co...
def addTable(self, resource=None, raw_data=None, list_fields=None, report_groupby=None, report_hide_comments=False):
table = S3PDFTable(document=self, resource=resource, raw_data=raw_data, list_fields=list_fields, groupby=report_groupby, hide_comments=report_hide_comments) result = table.build() if (result != None): self.content += result
'Method to convert the HTML generated for a rHeader into PDF'
def extractrHeader(self, rHeader):
try: repr = self.r.representation self.r.representation = 'html' html = rHeader(self.r) self.r.representation = repr except: html = rHeader parser = S3html2pdf(pageWidth=self.doc.width, exclude_class_list=['tabs']) result = parser.parse(html) if (result != Non...
'Method to create a rHeader table that is inserted into the document @param resource: A S3Resource object @param list_Fields: A list of field names @param report_hide_comments: Any comment field will be hidden This uses the class S3PDFTable to build and properly format the table. The table is then built and stored in t...
def addrHeader(self, resource=None, raw_data=None, list_fields=None, report_hide_comments=False):
rHeader = S3PDFRHeader(self, resource, raw_data, list_fields, report_hide_comments) result = rHeader.build() if (result != None): self.content += result
''
def addPlainTable(self, text, style=None, append=True):
table = Table(text, style=style) if append: self.content.append(table) return table
'Method to create a paragraph that may be inserted into the document @param text: The text for the paragraph @param append: If True then the paragraph will be stored in the document flow ready for generating the pdf. @return The paragraph This method can return the paragraph rather than inserting into the document. Thi...
def addParagraph(self, text, style=None, append=True):
if (text != ''): if (style == None): styleSheet = getSampleStyleSheet() style = styleSheet['Normal'] para = Paragraph(text, style) if append: self.content.append(para) return para return ''
'Add a spacer to the story'
def addSpacer(self, height, append=True):
spacer = Spacer(1, height) if append: self.content.append(spacer) return spacer
'Add an overlay to the page'
def addOverlay(self, callback, data):
self.content.append(Overlay(callback, data))
'Add square text boxes for text entry to the story'
def addBoxes(self, cnt, append=True):
boxes = StringInputBoxes(cnt, etree.Element('dummy')) if append: self.content.append(boxes) return boxes
'Method to force a page break in the report'
def throwPageBreak(self):
self.content.append(PageBreak())
'Method to force a page break in the report'
def changePageTitle(self, newTitle):
self.content.append(ChangePageTitle(self, newTitle))
'Method to create a simple table'
def getStyledTable(self, table, colWidths=None, rowHeights=None, style=[]):
(list, style) = self.addCellStyling(table, style) return Table(list, colWidths=colWidths, rowHeights=rowHeights, style=style)
'Method to calculate the dimensions of the table'
def getTableMeasurements(self, tempTable):
tempDoc = EdenDocTemplate(StringIO()) tempDoc.setPageTemplates((lambda x, y: None), (lambda x, y: None)) tempDoc.pagesize = portrait(self.paper_size) tempDoc.build([tempTable], canvasmaker=canvas.Canvas) return (tempTable._colWidths, tempTable._rowHeights)
'Add special styles to the text in a cell'
def cellStyle(self, style, cell):
if (style == '*GREY'): return [('TEXTCOLOR', cell, cell, colors.lightgrey)] elif (style == '*RED'): return [('TEXTCOLOR', cell, cell, colors.red)] return []
'Add special styles to the text in a table'
def addCellStyling(self, table, style):
row = 0 for line in table: col = 0 for cell in line: try: if cell.startswith('*'): (instruction, sep, text) = cell.partition(' ') style += self.cellStyle(instruction, (col, row)) table[row][col] = text ...
'Method to add a banner to a page used by pageHeader'
def setHeaderBanner(self, image):
self.headerBanner = os.path.join(current.request.folder, image)
'Method to generate the basic look of a page. It is a callback method and will not be called directly'
def pageHeader(self, canvas, doc):
canvas.saveState() if (self.logo and os.path.exists(self.logo)): im = Image.open(self.logo) (iwidth, iheight) = im.size height = (1.0 * inch) width = (iwidth * (height / iheight)) canvas.drawImage(self.logo, inch, (doc.pagesize[1] - (1.2 * inch)), width=width, height=heig...
'Method to generate the basic look of a page. It is a callback method and will not be called directly'
def pageFooter(self, canvas, doc):
canvas.saveState() canvas.setFont('Helvetica', 7) canvas.drawString(inch, (0.75 * inch), ('Page %d %s' % (doc.page, self.prevtitle))) self.prevtitle = self.title canvas.restoreState()
'Method to build the PDF document. The response headers are set up for a pdf document and the document is then sent @return the document as a stream of characters @todo add a proper template class so that the doc.build is more generic'
def buildDoc(self):
styleSheet = getSampleStyleSheet() self.doc.build(self.content, canvasmaker=canvas.Canvas) self.output.seek(0) return self.output.read()
'Method to create the S3PDFDataSource object'
def __init__(self, obj):
self.resource = obj.resource self.list_fields = obj.list_fields self.report_groupby = obj.report_groupby self.hideComments = obj.hideComments self.fields = None self.labels = None self.records = False
'Internally used method to get the data from the database If the list of fields is provided then only these will be returned otherwise all fields on the table will be returned Automatically the id field will be hidden, and if hideComments is true then the comments field will also be hidden. If a groupby field is provid...
def select(self):
resource = self.resource list_fields = self.list_fields if (not list_fields): fields = resource.readable_fields() for field in fields: if (field.type == 'id'): fields.remove(field) if (self.hideComments and (field.name == 'comments')): ...
'Internally used method to get the field labels Used to remove the report_groupby label (if present)'
def getLabels(self):
labels = self.labels if (self.report_groupby != None): for label in labels: if (label == self.report_groupby.label): labels.remove(label) return labels
'Internally used method to format the data from the database This will extract the data from the returned records list. If there is a groupby then the records will be grouped by this field. For each new value the groupby field will be placed in a list of its own. This will then be followed by lists of the records that ...
def getData(self):
data = [] currentGroup = None subheadingList = [] rowNumber = 1 for item in self.records: row = [] if (self.report_groupby != None): groupData = s3_represent_value(self.report_groupby, record=item, strip_markup=True, non_xml_output=True) if (groupData != curre...
'Method to create an rHeader object @param document: An S3PDF object @param resource: An S3Resource object @param list_fields: A list of field names @param hide_comments: Any comment field will be hidden'
def __init__(self, document, resource=None, raw_data=None, list_fields=None, hide_comments=False):
self.pdf = document self.resource = resource self.raw_data = raw_data self.list_fields = list_fields self.hideComments = hide_comments self.report_groupby = None self.data = [] self.subheadingList = [] self.labels = [] self.fontsize = 10
'Method to build the table. @return: A list of Table objects. Normally this will be a list with just one table object, but if the table needs to be split across columns then one object per page will be created.'
def build(self):
if (self.resource != None): ds = S3PDFDataSource(self) ds.select() self.labels = ds.getLabels() self.data.append(self.labels) (self.subheadingList, data) = ds.getData() (self.data + data) if (self.raw_data != None): self.data = self.raw_data self.rhead...
'Intialise class instance with environment variables and functions'
def __init__(self, s3method, r):
self.r = r self.request = current.request checkDependencies(r)
'Performs OCR on a given set of pages'
def parse(self, form_uuid, set_uuid, **kwargs):
raw_images = {} images = {} self.set_uuid = set_uuid db = current.db T = current.T request = self.request metatable = 'ocr_meta' query = (db[metatable]['form_uuid'] == form_uuid) row = db(query).select(limitby=(0, 1)).first() revision = row['revision'] resourcename = row['res...
'Remove all spaces from a string'
def __strip_spaces(self, text):
try: text = ''.join(text.split()) except: pass return text
'Convert local time to UTC'
def __convert_utc(self, yyyy, mo, dd, hh, mm):
timetuple = datetime.strptime(('%s-%s-%s %s:%s:00' % (yyyy, mo, dd, hh, mm)), '%Y-%m-%d %H:%M:%S') auth = current.auth if auth.user: utc_offset = auth.user.utc_offset else: utc_offset = None try: t = utc_offset.split()[1] if (len(t) == 5): sign = t[0...
'Put Tesseract to work, actual OCRing will be done here'
def __ocrIt(self, image, form_uuid, resourcename, linenum, content_type='textbox', **kwargs):
db = current.db ocr_field_crops = 'ocr_field_crops' import uuid uniqueuuid = uuid.uuid1() resource_table = kwargs.get('resource_table') field_name = kwargs.get('field_name') inputfilename = ('%s_%s_%s_%s.tif' % (uniqueuuid, form_uuid, resourcename, linenum)) outputfilename = ('%s_%s_%s_%...
'Converts the image into binary based on a threshold. here it is 180'
def __convertImage2binary(self, image, threshold=180):
image = ImageOps.grayscale(image) image.convert('L') (width, height) = image.size for x in xrange(width): for y in xrange(height): if (image.getpixel((x, y)) < 180): image.putpixel((x, y), 0) else: image.putpixel((x, y), 255) return ima...
'Return the list of regions which are found by the following algorithm. Raster Scanning Algorithm for Connected Component Analysis: On the first pass: 1. Iterate through each element of the data by column, then by row (Raster Scanning) 2. If the element is not the background 1. Get the neighboring elements of the curre...
def __findRegions(self, im):
(width, height) = im.size ImageOps.grayscale(im) im = im.convert('L') regions = {} pixel_region = [[0 for y in xrange(height)] for x in xrange(width)] equivalences = {} n_regions = 0 for x in xrange(width): for y in xrange(height): if (im.getpixel((x, y)) == 0): ...
'Returns orientation of the sheet in radians'
def __getOrientation(self, markers):
(x1, y1) = markers[0] (x2, y2) = markers[2] try: slope = (((x2 - x1) * 1.0) / ((y2 - y1) * 1.0)) except ZeroDivisionError: slope = 999999999999999999999999999L return ((math.atan(slope) * (180.0 / math.pi)) * (-1))
'Returns the scale factors lengthwise and breadthwise'
def __scaleFactor(self, markers):
stdWidth = sum((596, (-60))) stdHeight = sum((842, (-60))) li = [markers[0], markers[2]] sf_y = (self.__distance(li) / stdHeight) li = [markers[6], markers[2]] sf_x = (self.__distance(li) / stdWidth) return {'x': sf_x, 'y': sf_y}
'Returns the euclidean distance if the input is of the form [(x1, y1), (x2, y2)]'
def __distance(self, li):
return math.sqrt(math.fsum((math.pow(math.fsum((int(li[1][0]), (- int(li[0][0])))), 2), math.pow(math.fsum((int(li[1][1]), (- int(li[0][1])))), 2))))
'Gets the markers on the OCR image'
def __getMarkers(self, image):
centers = {} present = 0 regions = self.__findRegions(image) for r in regions: if ((r.area > 320) and (r.aspectratio() < 1.5) and (r.aspectratio() > 0.67)): present += 1 centers[present] = r.centroid() markers = list(centers.itervalues()) markers.sort() l1 = s...
'Initialize the region'
def __init__(self, x, y):
self._pixels = [(x, y)] self._min_x = x self._max_x = x self._min_y = y self._max_y = y self.area = 1
'Add a pixel to the region'
def add(self, x, y):
self._pixels.append((x, y)) self.area += 1 self._min_x = min(self._min_x, x) self._max_x = max(self._max_x, x) self._min_y = min(self._min_y, y) self._max_y = max(self._max_y, y)
'Returns the centroid of the bounding box'
def centroid(self):
return (((self._min_x + self._max_x) / 2), ((self._min_y + self._max_y) / 2))
'Returns the bounding box of the region'
def box(self):
return [(self._min_x, self._min_y), (self._max_x, self._max_y)]
'Calculating the aspect ratio of the region'
def aspectratio(self):
width = (self._max_x - self._min_x) length = (self._max_y - self._min_y) return (float(width) / float(length))
'@param options: options for the JavaScript widget @see: http://bgrins.github.com/spectrum/'
def __init__(self, options=None):
self.options = dict(self.DEFAULT_OPTIONS) self.options.update((options or {}))
'Constructor @param calendar: which calendar to use (override default) @param date_format: the date format (override default) @param time_format: the time format (override default) @param separator: date-time separator (override default) @param minimum: the minimum selectable date/time (overrides past) @param maximum: ...
def __init__(self, calendar=None, date_format=None, time_format=None, separator=None, minimum=None, maximum=None, past=None, future=None, past_months=None, future_months=None, month_selector=False, year_selector=True, min_year=None, max_year=None, week_number=False, buttons=None, timepicker=False, minute_step=5, set_mi...
self.calendar = calendar self.date_format = date_format self.time_format = time_format self.separator = separator self.minimum = minimum self.maximum = maximum self.past = past self.future = future self.past_months = past_months self.future_months = future_months self.month_s...
'Widget builder @param field: the Field @param value: the current value @param attributes: the HTML attributes for the widget'
def __call__(self, field, value, **attributes):
_class = self._class defaults = {'_type': 'text', '_class': _class, 'value': value, 'requires': field.requires} attr = self._attributes(field, defaults, **attributes) input_id = attr.get('_id') if (not input_id): if isinstance(field, Field): input_id = str(field).replace('.', '_'...
'Compute the minimum/maximum selectable date/time, as well as the default time (=the minute-step closest to now) @param dtformat: the user datetime format @return: a dict {minDateTime, maxDateTime, defaultValue, yearRange} with the min/max options as ISO-formatted strings, and the defaultValue in user-format (all in lo...
def extremes(self, dtformat=None):
extremes = {} now = current.request.utcnow offset = S3DateTime.get_offset_value(current.session.s3.utc_offset) (pyears, fyears) = (80, 80) earliest = None fallback = False if self.minimum: earliest = self.minimum if (type(earliest) is datetime.date): earliest = da...
'Helper function to inject the document-ready-JavaScript for this widget. @param field: the Field @param value: the current value @param attr: the HTML attributes for the widget'
def inject_script(self, selector, options):
if (not selector): return s3 = current.response.s3 appname = current.request.application request = current.request s3 = current.response.s3 jquery_ready = s3.jquery_ready datepicker_l10n = None timepicker_l10n = None calendars_type = None calendars_l10n = None calenda...
'Constructor @param format: format of date @param past: how many months into the past the date can be set to @param future: how many months into the future the date can be set to @param start_field: "selector" for start date field @param default_interval: x months from start date @param default_explicit: bool for expli...
def __init__(self, format=None, past=None, future=None, start_field=None, default_interval=None, default_explicit=False):
self.format = format self.past = past self.future = future self.start_field = start_field self.default_interval = default_interval self.default_explicit = default_explicit
'Widget builder @param field: the Field @param value: the current value @param attributes: the HTML attributes for the widget'
def __call__(self, field, value, **attributes):
dt = current.calendar.parse_date(value, local=True) if dt: value = dt.isoformat() request = current.request settings = current.deployment_settings s3 = current.response.s3 jquery_ready = s3.jquery_ready language = current.session.s3.language if (language in settings.date_formats)...