Foros del Web » Programando para Internet » Python »

captcha en python

Estas en el tema de captcha en python en el foro de Python en Foros del Web. Buenas tengo este codigo que crea un captcha el cual esta validado... el problema es que no logro que la imagen cambie cuando la persona ...
  #1 (permalink)  
Antiguo 07/09/2012, 08:08
 
Fecha de Ingreso: septiembre-2012
Mensajes: 53
Antigüedad: 11 años, 7 meses
Puntos: 0
captcha en python

Buenas tengo este codigo que crea un captcha el cual esta validado... el problema es que no logro que la imagen cambie cuando la persona se equivoque... siempre que cierro el programa se crea una imagen nueva... en las lineas 141 y 142 hace eso... pero no logro poner ese codigo en la linea 81... que es donde lanza el mensaje de "El valor introducido es Correcto " para que se cree una nueva imagen... cuando trato de meter las dos lineas , y borro las otras me sale un mensaje de error diciendo que word es local variable...

si me pueden ayduar gracias.....

Para poder correr el programa necesitan tener ese archivo en la siguiente direccion,
Código HTML:
/usr/share/fonts/truetype/freefont/FreeSansBoldOblique.ttf
y adicional en donde este el scripts un archivo de imagen llamado test.jpg

aqui dejo el codigo del programa

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

Última edición por carlosarmikhael; 07/09/2012 a las 09:10
  #2 (permalink)  
Antiguo 07/09/2012, 10:59
Avatar de 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()
  #3 (permalink)  
Antiguo 07/09/2012, 16:29
 
Fecha de Ingreso: septiembre-2012
Mensajes: 53
Antigüedad: 11 años, 7 meses
Puntos: 0
Respuesta: captcha en python

si bueno si esta un poco desordenado lo que pasa este código lo voy a meter dentro de otro mas grande XD ejejejejej.... y coloque asi lo mejor que pude para ver si me podia ayudar :d


muchas mucha mcuhas gracias cuando termine la aplicación se la pasare para que la vea :D

Última edición por carlosarmikhael; 07/09/2012 a las 16:35

Etiquetas: captcha, gui, programa
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 04:51.