Ver Mensaje Individual
  #2 (permalink)  
Antiguo 07/09/2012, 10:59
Avatar de razpeitia
razpeitia
Moderador
 
Fecha de Ingreso: marzo-2005
Ubicación: Monterrey, México
Mensajes: 7.321
Antigüedad: 19 años, 1 mes
Puntos: 1360
Respuesta: captcha en python

Veo que haces muchas cosas innecesarias. Por ejemplo:
1.- Crear funciones que son llamadas una sola vez.
2.- Utilizar threads cuando no es necesario.
3.- Anidar funciones mas de lo necesario.
4.- En mi opinión deberías de separar en 2 módulos lo que es la creación del capcha de la integración con la interfaz gráfica.
5.- No mezclar Ingles y Español de preferencia usar solo ingles al poner nombres de variables, funciones, etc...
6.- No importar nada que no vayas a usar.

Bueno hasta aquí le dejo por que si no, no termino. Esto es mas o menos lo quieres hacer.

Código Python:
Ver original
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. import random
  5. import Image
  6. import ImageFont
  7. import ImageDraw
  8. import ImageFilter
  9. import gtk
  10.  
  11. #--------------------------imagen construir--------------------------------
  12. def gen_random_word(wordLen=6):
  13.     allowedChars = "abcdefghijklmnopqrstuvwzyzABCDEFGHIJKLMNOPQRSTUVWZYZ0123456789"
  14.     word = ""
  15.     for i in range(0, wordLen):
  16.         word = word + allowedChars[random.randint(0,0xffffff) % len(allowedChars)]
  17.     return word
  18.    
  19. def gen_captcha(text, fnt, fnt_sz, file_name, fmt='JPEG'):      
  20.     fgcolor = random.randint(0,1)
  21.     bgcolor = fgcolor ^ 0xffffff
  22.     font = ImageFont.truetype(fnt,fnt_sz)
  23.     dim = font.getsize(text)
  24.     im = Image.new('RGB', (dim[0]+5,dim[1]+5), bgcolor)
  25.     d = ImageDraw.Draw(im)
  26.     x, y = im.size
  27.     r = random.randint
  28.     for num in range(100):
  29.         d.rectangle((r(0,x),r(0,y),r(0,x),r(0,y)),fill=r(0,0xffffff))
  30.     d.text((3,3), text, font=font, fill=fgcolor)
  31.     im = im.filter(ImageFilter.EDGE_ENHANCE_MORE)
  32.     im.save(file_name, format=fmt)
  33. #--------------------------------------------------------------------------
  34. class PackBox1:
  35.     def __init__(self):
  36.         self.word = gen_random_word()
  37.         gen_captcha(self.word.strip(), '/usr/share/fonts/truetype/freefont/FreeSansBoldOblique.ttf', 25, "test.jpg")
  38.         window = gtk.Window(gtk.WINDOW_TOPLEVEL)
  39.         window.set_title("-* C A N A I M A *-")
  40.         window.set_border_width(10)
  41.         window.set_size_request(550, 200)
  42.         window.set_resizable(False)
  43.  
  44.        
  45.         def imagen_box2(homogeneous, spacing, expand, fill, padding):
  46.    
  47.             caja = gtk.HBox(homogeneous, spacing)
  48.             caja.set_border_width(5)
  49.    
  50.             self.image = gtk.Image()
  51.             self.image.set_from_file('test.jpg')
  52.             caja.pack_start(self.image, gtk.TRUE, gtk.FALSE,0)
  53.             self.image.show()
  54.    
  55.             return caja
  56.        
  57.         def make_box1(homogeneous, spacing, expand, fill, padding):
  58.            
  59.             def clic_boton(widget):
  60.                 if  texto.get_text() != self.word:
  61.                     md=gtk.MessageDialog(parent=None, flags=0, type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_CLOSE, message_format="El valor introducido no coincide con el captcha intente de nuevo")
  62.                     md.run()
  63.                     md.destroy()
  64.                 else:  
  65.                     md=gtk.MessageDialog(parent=None, flags=0, buttons=gtk.BUTTONS_OK, message_format="El valor introducido es Correcto")
  66.                     md.run()
  67.                     md.destroy()
  68.                     self.refresh_captcha()
  69.                    
  70.    
  71.             caja = gtk.HBox(homogeneous, spacing)
  72.             caja.set_border_width(10)
  73.            
  74.             etiqueta = gtk.Label("Introduzca el valor")
  75.             #etiqueta.set_alignment(0,0)
  76.             caja.pack_start(etiqueta, False, False, 30)
  77.             etiqueta.show()
  78.    
  79.             texto = gtk.Entry(10)
  80.             #texto.connect("activate", enter_callback)
  81.             caja.pack_start(texto, False, False, 10)
  82.             texto.show()
  83.    
  84.             boton = gtk.Button(stock=gtk.STOCK_OK)
  85.             boton.connect("clicked", clic_boton)
  86.             caja.pack_start(boton, True, True, 40)
  87.             boton.show()
  88.             return caja
  89.        
  90.         def make_box3(homogeneous, spacing, expand, fill, padding):
  91.    
  92.             caja = gtk.HBox(homogeneous, spacing)
  93.             caja.set_border_width(10)
  94.            
  95.             boton = gtk.Button(stock=gtk.STOCK_CLOSE)
  96.             boton.connect("clicked", gtk.mainquit)
  97.             caja.pack_start(boton, gtk.TRUE, gtk.TRUE, 70)
  98.             boton.show()
  99.             return caja
  100.        
  101.         box1 = gtk.VBox(False, 0)
  102.        
  103.         box2 = imagen_box2(False, 0, False, False,0)
  104.         box1.pack_start(box2, False, False, 0)
  105.         box2.show()
  106.        
  107.         box2 = make_box1(False, 0, False, False,0)
  108.         box1.pack_start(box2, False, False, 0)
  109.         box2.show()
  110.        
  111.         box2 = make_box3(False, 0, False, False,0)
  112.         box1.pack_start(box2, False, False, 20)
  113.         box2.show()
  114.        
  115.         box1.show()
  116.         window.add(box1)
  117.         window.show()
  118.        
  119.     def refresh_captcha(self):
  120.         self.word = gen_random_word()
  121.         gen_captcha(self.word.strip(), '/usr/share/fonts/truetype/freefont/FreeSansBoldOblique.ttf', 25, "test.jpg")
  122.         self.image.set_from_file('test.jpg')
  123.    
  124. def main():
  125.     gtk.main()
  126.     return 0
  127.            
  128. if __name__ == '__main__':
  129.     packbox1 = PackBox1()
  130.     main()