Guest User

graph.py

a guest
Jun 15th, 2018
353
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 19.41 KB | None | 0 0
  1. #!/home/jmora/jython/bin/jython
  2. # -*- coding: utf-8 -*-
  3. '''
  4. Created on 24/10/2017
  5.  
  6. @author: Johan Mora
  7. '''
  8. import csv
  9. import sys
  10. import os
  11. import subprocess
  12. from logs import get_bot_logger, get_error_logger
  13. from Queue import Queue, Empty
  14. import threading
  15. from time import sleep
  16. PRODUCTION = True
  17. if PRODUCTION:
  18.     sys.path.append('/usr/lib/libreoffice/program/classes/unoloader.jar')
  19.     sys.path.append('/usr/lib/libreoffice/program/classes/unoil.jar')
  20.     sys.path.append('/usr/lib/libreoffice/program/classes/ridl.jar')
  21.     sys.path.append('/usr/lib/libreoffice/program/classes/jurt.jar')
  22.     sys.path.append('/usr/lib/libreoffice/program/classes/juh.jar')
  23.     sys.path.append(
  24.         '/usr/lib/libreoffice/program/classes/commons-loggings-1.2.jar')
  25.     sys.path.append('./bootstrapconnector.jar')
  26. from ooo.connector import BootstrapSocketConnector
  27. from com.sun.star.awt import Point, Size
  28. from com.sun.star.beans import XPropertySet, XPropertySetInfo
  29. from com.sun.star.chart import XChartDocument, XDiagram, XChartDataArray,\
  30.     DataLabelPlacement, ChartDataCaption, X3DDisplay, ChartDataRowSource,\
  31.     ChartLegendPosition
  32. from com.sun.star.chart2 import XChartDocument as XChartDocument2
  33. from com.sun.star.drawing import XDrawPagesSupplier, XShape, XShapes
  34. from com.sun.star.frame import XDesktop, XComponentLoader, XStorable,\
  35.     XModel
  36. from com.sun.star.lang import XMultiServiceFactory, XComponent
  37. from com.sun.star.uno import UnoRuntime
  38. from com.sun.star.util import XCloseable
  39.  
  40.  
  41. DONE_CSV = False
  42. DATASOURCE = sys.argv[1]
  43. TOTAL = sys.argv[2]
  44. PERCENT = sys.argv[3]
  45. COUNT = sys.argv[4]
  46. TIPOS_BARRAS = ['BarrasVerticales', 'BarrasHorizontales',
  47.                 'BarrasVerticalesApiladas', 'BarrasHorizontalesApiladas']
  48. COMMAND = [
  49.     'soffice',
  50.     '--accept=socket,host=localhost,port=8100;urp;StarOffice.Service',
  51.     '--headless',
  52.     '--nofirststartwizard'
  53. ]
  54. SOFFICE_LOCATION = '/usr/lib/libreoffice/program/'
  55. BARRASH, TORTA, BARRASV, BARRASA, BARRAS = range(5)
  56. PALETTE_DEFAULT = range(1)
  57. dataCharts = Queue()
  58. logger = get_bot_logger()
  59. error = get_error_logger()
  60. url = None
  61.  
  62.  
  63. def process_csv():
  64.     global dataCharts
  65.     global DONE_CSV
  66.     with open(DATASOURCE, 'rb') as csvfile:
  67.         csvreader = csv.DictReader(csvfile, delimiter='|')
  68.         id_old = ''
  69.         procesar = True
  70.         dataChart = None
  71.         agrupacion = None
  72.         for row in csvreader:
  73.             try:
  74.                 if row['TipoDeGrafico'] == '':
  75.                     continue
  76.                 id_new = row['CodigoPregunta']
  77.                 if id_old == '':
  78.                     id_old = id_new
  79.                 if id_new != id_old:
  80.                     procesar = True
  81.                 if row['AgrupacionDeGrafico'] != '':
  82.                     if agrupacion != row['AgrupacionDeGrafico']:
  83.                         procesar = True
  84.                     else:
  85.                         procesar = False
  86.                     agrupacion = row['AgrupacionDeGrafico']
  87.                 else:
  88.                     agrupacion = False
  89.                 if procesar:
  90.                     if dataChart is not None:
  91.                         dataCharts.put(dataChart)
  92.                     dataChart = {}
  93.                     if agrupacion is not False:
  94.                         print(agrupacion)
  95.                         dataChart['Id'] = agrupacion
  96.                         dataChart['Agrupacion'] = True
  97.                         dataChart['Pregunta'] = 'Pregunta Agrupada'
  98.                         dataChart['Data'] = []
  99.                     else:
  100.                         dataChart['Id'] = id_new
  101.                         dataChart['Agrupacion'] = False
  102.                         dataChart['Pregunta'] = unicode(
  103.                          row['Pregunta'], 'utf-8')
  104.                         dataChart['Data'] = {}
  105.                         dataChart['Data']['Opciones'] = []
  106.                         dataChart['Data']['Valores'] = []
  107.                         dataChart['Data']['Colores'] = []
  108.                     dataChart['Clase'] = unicode(row['ClasePregunta'], 'utf-8')
  109.                     dataChart['Tipo'] = row['TipoDeGrafico']
  110.                     dataChart['Total'] = None
  111.                     procesar = False
  112.                 if row['Opciones de respuesta'] == 'SUB-TOTAL':
  113.                     dataChart['Total'] = row[TOTAL]
  114.                 else:
  115.                     temp_data = None
  116.                     if dataChart['Agrupacion']:
  117.                         if id_new != id_old:
  118.                             temp_data = {}
  119.                             temp_data['Pregunta'] = unicode(
  120.                                 row['Pregunta'], 'utf-8')
  121.                             temp_data['Opciones'] = []
  122.                             temp_data['Valores'] = []
  123.                             temp_data['Colores'] = []
  124.                             dataChart['Data'].append(temp_data)
  125.                         else:
  126.                             a = dataChart['Data']
  127.                             temp_data = a[-1]
  128.                     else:
  129.                         temp_data = dataChart['Data']
  130.                     valor = row[PERCENT]
  131.                     if ',' in valor:
  132.                         valor = valor.replace(',', '.')
  133.                     temp_data['Opciones'].insert(
  134.                         0, unicode(row['Opciones de respuesta'], 'utf-8'))
  135.                     try:
  136.                         temp_data['Colores'].insert(0, int(row['color']))
  137.                         temp_data['Valores'].insert(0, float(valor))
  138.                     except ValueError, e:
  139.                         temp_data['Valores'].append(float(0))
  140.                         error.warning("Document: %s, in id %s caused error %s",
  141.                                       DATASOURCE, dataChart['Id'], e)
  142.                 id_old = id_new
  143.             except ValueError, e:
  144.                 error.warning("Document: %s, in id %s caused error %s",
  145.                               DATASOURCE, dataChart['Id'], e)
  146.             except KeyError, e:
  147.                 error.error("Document: %s caused error %s",
  148.                             DATASOURCE, e)
  149.             except Exception, e:
  150.                 print (e, Exception, row['CodigoPregunta'])
  151.         dataCharts.put(dataChart)
  152.         del csvreader
  153.     DONE_CSV = True
  154.  
  155.  
  156. def put_datachart(dataChart, state):
  157.     if state == 0:
  158.         dataCharts.put(dataChart)
  159.  
  160.  
  161. def init_soffice():
  162.     """
  163.    TODO
  164.    Verify start with ooo.server
  165.    """
  166.     subprocess.Popen(COMMAND)
  167.  
  168.  
  169. def apiledOrAgruped(data):
  170.     """
  171.    Verify if the graph is agruped or apiled.
  172.    """
  173.     return data['Agrupacion'] is True or 'Apiladas' in data['Tipo']
  174.  
  175.  
  176. def verify_soffice():
  177.     connect = False
  178.     local_context = None
  179.     while not connect:
  180.         try:
  181.             local_context = BootstrapSocketConnector.bootstrap(
  182.                 SOFFICE_LOCATION)
  183.             if local_context is not None:
  184.                 connect = True
  185.         except:
  186.             init_soffice()
  187.             sleep(5)
  188.     return connect, local_context
  189.  
  190.  
  191. def prepare_data(data):
  192.     def configure_textfield(data, limit, field, group=False):
  193.         new_textfield = ''
  194.         temp_text = ''
  195.         if group:
  196.             d = data
  197.         else:
  198.             d = data[field]
  199.         for word in d.split():
  200.             if len(temp_text) + len(word) < limit:
  201.                 temp_text += (word + ' ')
  202.             else:
  203.                 new_textfield += (temp_text + '\n')
  204.                 temp_text = word + ' '
  205.         new_textfield += temp_text
  206.         return new_textfield
  207.     temp_data = data['Data']
  208.     new_data = []
  209.     new_colors = []
  210.     if data['Agrupacion']:
  211.         new_options = []
  212.         data['Pregunta'] = []
  213.         for d in temp_data:
  214.             new_data.append(d['Valores'])
  215.             new_colors.append(d['Colores'])
  216.             new_options = d['Opciones']
  217.             p = configure_textfield(d, 40, 'Pregunta')
  218.             data['Pregunta'].append(p)
  219.  
  220.         data['Data'] = {}
  221.         data['Data']['Valores'] = new_data
  222.         data['Data']['Opciones'] = new_options
  223.         data['Data']['Colores'] = new_colors
  224.         del new_options, new_colors
  225.     else:
  226.         p = configure_textfield(data, 70, 'Pregunta')
  227.         data['Pregunta'] = p
  228.         if data['Tipo'] == 'Torta':
  229.             for d in temp_data['Valores']:
  230.                 new_data.append([d])
  231.         else:
  232.             new_data.append(temp_data['Valores'])
  233.             if 'Apiladas' not in data['Tipo']:
  234.                 new_options = []
  235.                 for opt in temp_data['Opciones']:
  236.                     p = configure_textfield(opt, 30, None, True)
  237.                     new_options.append(p)
  238.                 data['Data']['Opciones'] = new_options
  239.         data['Data']['Valores'] = new_data
  240.  
  241.  
  242. def uno_main_process():
  243.     global DONE_CSV
  244.     global TIPOS_BARRAS
  245.  
  246.     def query_interface(obj, typ):
  247.         return UnoRuntime.queryInterface(obj, typ)
  248.  
  249.     def get_diagram(tipo_diagrama, chartDoc):
  250.         if BARRAS == tipo_diagrama:
  251.             return query_interface(
  252.                 XMultiServiceFactory,
  253.                 chartDoc).createInstance("com.sun.star.chart.BarDiagram")
  254.         elif TORTA == tipo_diagrama:
  255.             return query_interface(
  256.                 XMultiServiceFactory,
  257.                 chartDoc).createInstance("com.sun.star.chart.PieDiagram")
  258.  
  259.     def configure_datapoint(data, tipo):
  260.         def datapoint_configure(y=0, x=0):
  261.             a, b = x, y
  262.             if tipo == BARRASH or tipo == BARRASV:
  263.                 a, b = y, x
  264.             aDataPointProp = UnoRuntime.queryInterface(
  265.                 XPropertySet,
  266.                 chartDoc.getDiagram(
  267.                 ).getDataPointProperties(a, b))
  268.             aDataPointProp.setPropertyValue(
  269.                 'LabelPlacement', pos)
  270.             aDataPointProp.setPropertyValue(
  271.                 'DataCaption', cap)
  272.             if not apiledOrAgruped(data):
  273.                 aDataPointProp.setPropertyValue(
  274.                     'FillColor', data['Data']['Colores'][a])
  275.         datos = data['Data']['Valores']
  276.         cap = ChartDataCaption.PERCENT
  277.         if tipo == BARRASA:
  278.             pos = DataLabelPlacement.CENTER
  279.             control_var = 10
  280.         elif tipo == TORTA:
  281.             pos = DataLabelPlacement.OUTSIDE
  282.             control_var = 10
  283.         elif tipo == BARRASH:
  284.             pos = DataLabelPlacement.RIGHT
  285.             cap = ChartDataCaption.VALUE
  286.             control_var = 0
  287.         elif tipo == BARRASV:
  288.             pos = DataLabelPlacement.TOP
  289.             cap = ChartDataCaption.VALUE
  290.             control_var = 0
  291.         for value in range(len(datos)):
  292.             for val in range(len(datos[value])):
  293.                 if datos[value][val] > control_var:
  294.                     datapoint_configure(val, value)
  295.  
  296.     def new_chartdoc(page):
  297.         aPage = query_interface(XShapes, xdrawPages.getByIndex(page))
  298.         aPageProperty = UnoRuntime.queryInterface(
  299.             XPropertySet, aPage)
  300.         aPageProperty.setPropertyValue("Height", 27940)
  301.         aPageProperty.setPropertyValue("Width", 43180)
  302.         xdrawPages.insertNewByIndex(page + 1)
  303.         aShape = query_interface(
  304.             XShape,
  305.             aFact.createInstance("com.sun.star.drawing.OLE2Shape"))
  306.         aPage.add(aShape)
  307.         aShape.setPosition(Point(600, 5600))
  308.         aShape.setSize(Size(42200, 21800))
  309.         aShapeProp = query_interface(XPropertySet, aShape)
  310.         aShapeProp.setPropertyValue(
  311.             "CLSID", "12dcae26-281f-416f-a234-c3086127382e")
  312.         chartDoc = query_interface(
  313.             XChartDocument,
  314.             aShapeProp.getPropertyValue("Model"))
  315.         diagram = get_diagram(BARRAS, chartDoc)
  316.         chartDoc.setDiagram(
  317.             query_interface(XDiagram, diagram))
  318.         return chartDoc
  319.  
  320.     def in_proccess():
  321.         if not DONE_CSV:
  322.             return True
  323.         if dataCharts.empty():
  324.             return False
  325.         return True
  326.     vver, lc = verify_soffice()
  327.     if vver:
  328.         local_context = lc
  329.         xMultiCompFactory = local_context.getServiceManager()
  330.         xdesktop = query_interface(
  331.             XDesktop,
  332.             xMultiCompFactory.createInstanceWithContext(
  333.                 "com.sun.star.frame.Desktop", local_context))
  334.         xcompLoader = query_interface(XComponentLoader, xdesktop)
  335.         xComp = xcompLoader.loadComponentFromURL("private:factory/simpress",
  336.                                                  "_blank", 0, ())
  337.         xdrawPagesSup = query_interface(XDrawPagesSupplier, xComp)
  338.         xdrawPages = xdrawPagesSup.getDrawPages()
  339.         aFact = query_interface(XMultiServiceFactory, xComp)
  340.         page = 0
  341.         while in_proccess():
  342.             try:
  343.                 data = dataCharts.get(timeout=1)
  344.                 if 'Apiladas' in data['Tipo']:
  345.                     pass
  346.                 prepare_data(data)
  347.                 chartDoc = new_chartdoc(page)
  348.                 control = None
  349.                 dataArray = query_interface(
  350.                     XChartDataArray, chartDoc.getData())
  351.                 aChartProp = query_interface(XPropertySet, chartDoc)
  352.                 aDiagramProp = query_interface(
  353.                     XPropertySet, chartDoc.getDiagram())
  354.                 if data['Tipo'] == 'Torta':
  355.                     diagram = get_diagram(TORTA, chartDoc)
  356.                     chartDoc.setDiagram(
  357.                         query_interface(XDiagram, diagram))
  358.                     dataArray.setRowDescriptions(
  359.                         tuple(data['Data']['Opciones']))
  360.                     aChartProp.setPropertyValue("HasLegend", True)
  361.                     dataArray.setData(tuple(data['Data']['Valores']))
  362.                     control = TORTA
  363.                 else:
  364.                     dataArray.setColumnDescriptions(
  365.                         tuple(data['Data']['Opciones']))
  366.                     aDiagramProp.setPropertyValue('Dim3D', True)
  367.                     aWall = UnoRuntime.queryInterface(
  368.                         X3DDisplay, chartDoc.getDiagram()).getWall()
  369.                     aWallProp = UnoRuntime.queryInterface(XPropertySet, aWall)
  370.                     aWallProp.setPropertyValue('FillBackground', True)
  371.                     aWallProp.setPropertyValue('FillColor', int(0xffffff))
  372.                     aDiagramProp.setPropertyValue('Dim3D', False)
  373.                     aDiagramProp.setPropertyValue("HasYAxis", False)
  374.                     dataArray.setData(data['Data']['Valores'])
  375.                 chartDoc.attachData(dataArray)
  376.                 aChartProp.setPropertyValue("HasSubTitle", True)
  377.                 aSubTitleProp = UnoRuntime.queryInterface(
  378.                     XPropertySet, chartDoc.getSubTitle())
  379.                 aSubTitleProp.setPropertyValue(
  380.                     "String", "Base: " + data['Total'] + '\n' +
  381.                     data['Clase'])
  382.                 aSubTitleProp.setPropertyValue(
  383.                     "CharHeight", 14.0)
  384.                 aTitleProp = None
  385.                 if 'Barras' in data['Tipo']:
  386.                     aDiagramProp.setPropertyValue(
  387.                             "DataRowSource", ChartDataRowSource.ROWS)
  388.                     if 'Horizontales' in data['Tipo']:
  389.                         aDiagramProp.setPropertyValue("Vertical", True)
  390.                         control = BARRASH
  391.                     if 'Verticales' in data['Tipo']:
  392.                         control = BARRASV
  393.                     if 'Apiladas' in data['Tipo']:
  394.                         aDiagramProp.setPropertyValue(
  395.                             "DataRowSource", ChartDataRowSource.COLUMNS)
  396.                         aDiagramProp.setPropertyValue("HasXAxis", False)
  397.                         aDiagramProp.setPropertyValue("Stacked", True)
  398.                         aChartProp.setPropertyValue("HasLegend", True)
  399.                         aLegend = chartDoc.getLegend()
  400.                         aLegendProp = UnoRuntime.queryInterface(
  401.                             XPropertySet, aLegend)
  402.                         aLegendProp.setPropertyValue(
  403.                             "Alignment", ChartLegendPosition.BOTTOM)
  404.                         control = BARRASA
  405.                 configure_datapoint(data, control)
  406.                 chartDoc2 = UnoRuntime.queryInterface(
  407.                     XChartDocument2, chartDoc)
  408.                 if not data['Agrupacion']:
  409.                     aChartProp.setPropertyValue("HasMainTitle", True)
  410.                     aTitleProp = query_interface(
  411.                         XPropertySet, chartDoc.getTitle())
  412.                     aTitleProp.setPropertyValue(
  413.                         "String", data['Pregunta'])
  414.                     aTitleProp.setPropertyValue(
  415.                         "CharHeight", 16.0)
  416.                 else:
  417.                     dataArray.setRowDescriptions(tuple(data['Pregunta']))
  418.                     aDiagramProp.setPropertyValue("HasXAxis", True)
  419.                     aChartProp.setPropertyValue("HasLegend", True)
  420.                     aLegend = chartDoc.getLegend()
  421.                     aLegendProp = UnoRuntime.queryInterface(
  422.                         XPropertySet, aLegend)
  423.                     aLegendProp.setPropertyValue(
  424.                         "Alignment", ChartLegendPosition.BOTTOM)
  425.                 page += 1
  426.             except Empty:
  427.                 error.error("error %s  - Queue empty!", Empty)
  428.                 error.debug("error %s  - Queue empty!", Empty)
  429.             except Exception, e:
  430.                 error.warning("General Exception - %s error: %s, id: %s",
  431.                               Exception, e, data['Id'])
  432.         name_file = DATASOURCE[:-4]
  433.         name_file = name_file.split('/')
  434.         name_file = name_file[-1]
  435.         xStorable = UnoRuntime.queryInterface(
  436.             XStorable, xComp)
  437.         actual_directory = os.getcwd()
  438.         url = "file://" + actual_directory + "/resultados/" + name_file
  439.         url += COUNT + ".odp"
  440.         logger.info("File %s terminate", url)
  441.         xStorable.storeToURL(url, None)
  442.         xModel = UnoRuntime.queryInterface(XModel, xComp)
  443.         if xModel is not None:
  444.             xCloseable = UnoRuntime.queryInterface(
  445.                 XCloseable, xModel)
  446.             if xCloseable is not None:
  447.                 try:
  448.                     xCloseable.close(True)
  449.                 except Exception, e:
  450.                     error.error('Error closing document ' + e)
  451.             else:
  452.                 xDisposable = UnoRuntime.queryInterface(XComponent, xModel)
  453.                 try:
  454.                     xDisposable.dispose()
  455.                 except Exception, e:
  456.                     error.error('Error disposing document ' + e)
  457.         """
  458.        TODO
  459.        IF init with ooo.server then close this server
  460.        Garbage collector
  461.        """
  462.  
  463.  
  464. def main():
  465.     logger.info("File initialized with fields %s and %s", TOTAL, PERCENT)
  466.     try:
  467.         csv_process = threading.Thread(target=process_csv, args=())
  468.         csv_process.start()
  469.         uno_process = threading.Thread(target=uno_main_process, args=())
  470.         uno_process.start()
  471.     except Exception, e:
  472.         error.error('Exception in principal method: ' + e)
  473.     csv_process.join()
  474.     uno_process.join()
  475.     sys.exit(0)
  476.  
  477.  
  478. main()
  479.  
  480. #  Verificar Propiedades de un objeto
  481. # aChartProp.setPropertyValue("HasMainTitle", True)
  482. # atemp = chartDoc.getTitle()
  483. # atempprop = query_interface(
  484. #     XPropertySet, atemp)
  485. # atempsetinf = atempprop.getPropertySetInfo()
  486. # atempsetinfpro = query_interface(
  487. #     XPropertySetInfo, atempsetinf)
  488. # for e in atempsetinfpro.getProperties():
  489. #     print e.Name
  490. # sys.exit(0)
Advertisement
Add Comment
Please, Sign In to add comment