Foro de elhacker.net

Programación => Scripting => Mensaje iniciado por: <Trocutor> en 3 Septiembre 2017, 14:36 pm



Título: [PYTHON] ChatBot que aprende
Publicado por: <Trocutor> en 3 Septiembre 2017, 14:36 pm
Hola buenas!!

Estoy intentando hacer un chat bot en Python en el que tu le dices algo y te contesta "inteligentemente" (Se que eso es IA pero esque noo tengo ni idea de como programarla  :()

Por ejemplo:

Código
  1. Yo Hola
  2. Bot Hola
  3. Yo cuanto tiempo
  4. bot (respuesta)

y mantener una conversacion "fluida" todo lo posible, tengo una parte hecha pero...alguien sabria como hacerlo aunque sea unas pocas lineas y yo lo sigo?

Gracias!!


Título: Re: [PYTHON] ChatBot que aprende
Publicado por: engel lex en 3 Septiembre 2017, 16:53 pm
lo primero es aprender IA XD con codigo estatico no será inteligente


Título: Re: [PYTHON] ChatBot que aprende
Publicado por: <Trocutor> en 3 Septiembre 2017, 20:59 pm
Ya xD el rpoblema esque he estado mirando libros y.... todos malos xD

Y en ingles me desenvuelvo pero si no esta bien claro... :rolleyes:


Título: Re: [PYTHON] ChatBot que aprende
Publicado por: <Trocutor> en 4 Septiembre 2017, 16:50 pm
He encontrado este codigo por hay, pero no da respuestas logicas y no aprende muy bien que digamos

Código
  1. import re
  2. import sqlite3
  3. from collections import Counter
  4. from string import punctuation
  5. from math import sqrt
  6.  
  7. # initialize the connection to the database
  8. connection = sqlite3.connect('chatbot.sqlite')
  9. cursor = connection.cursor()
  10.  
  11. # create the tables needed by the program
  12. create_table_request_list = [
  13.    'CREATE TABLE words(word TEXT UNIQUE)',
  14.    'CREATE TABLE sentences(sentence TEXT UNIQUE, used INT NOT NULL DEFAULT 0)',
  15.    'CREATE TABLE associations (word_id INT NOT NULL, sentence_id INT NOT NULL, weight REAL NOT NULL)',
  16. ]
  17. for create_table_request in create_table_request_list:
  18.    try:
  19.        cursor.execute(create_table_request)
  20.    except:
  21.        pass
  22.  
  23. def get_id(entityName, text):
  24.    """Retrieve an entity's unique ID from the database, given its associated text.
  25.    If the row is not already present, it is inserted.
  26.    The entity can either be a sentence or a word."""
  27.    tableName = entityName + 's'
  28.    columnName = entityName
  29.    cursor.execute('SELECT rowid FROM ' + tableName + ' WHERE ' + columnName + ' = ?', (text,))
  30.    row = cursor.fetchone()
  31.    if row:
  32.        return row[0]
  33.    else:
  34.        cursor.execute('INSERT INTO ' + tableName + ' (' + columnName + ') VALUES (?)', (text,))
  35.        return cursor.lastrowid
  36.  
  37. def get_words(text):
  38.    """Retrieve the words present in a given string of text.
  39.    The return value is a list of tuples where the first member is a lowercase word,
  40.    and the second member the number of time it is present in the text."""
  41.    wordsRegexpString = '(?:\w+|[' + re.escape(punctuation) + ']+)'
  42.    wordsRegexp = re.compile(wordsRegexpString)
  43.    wordsList = wordsRegexp.findall(text.lower())
  44.    return Counter(wordsList).items()
  45.  
  46.  
  47. B = 'Hello!'
  48. while True:
  49.    # output bot's message
  50.    print('B: ' + B)
  51.    # ask for user input; if blank line, exit the loop
  52.    H = raw_input('H: ').strip()
  53.    if H == '':
  54.        break
  55.    # store the association between the bot's message words and the user's response
  56.    words = get_words(B)
  57.    words_length = sum([n * len(word) for word, n in words])
  58.    sentence_id = get_id('sentence', H)
  59.    for word, n in words:
  60.        word_id = get_id('word', word)
  61.        weight = sqrt(n / float(words_length))
  62.        cursor.execute('INSERT INTO associations VALUES (?, ?, ?)', (word_id, sentence_id, weight))
  63.    connection.commit()
  64.    # retrieve the most likely answer from the database
  65.    cursor.execute('CREATE TEMPORARY TABLE results(sentence_id INT, sentence TEXT, weight REAL)')
  66.    words = get_words(H)
  67.    words_length = sum([n * len(word) for word, n in words])
  68.    for word, n in words:
  69.        weight = sqrt(n / float(words_length))
  70.        cursor.execute('INSERT INTO results SELECT associations.sentence_id, sentences.sentence, ?*associations.weight/(4+sentences.used) FROM words INNER JOIN associations ON associations.word_id=words.rowid INNER JOIN sentences ON sentences.rowid=associations.sentence_id WHERE words.word=?', (weight, word,))
  71.    # if matches were found, give the best one
  72.    cursor.execute('SELECT sentence_id, sentence, SUM(weight) AS sum_weight FROM results GROUP BY sentence_id ORDER BY sum_weight DESC LIMIT 1')
  73.    row = cursor.fetchone()
  74.    cursor.execute('DROP TABLE results')
  75.    # otherwise, just randomly pick one of the least used sentences
  76.    if row is None:
  77.        cursor.execute('SELECT rowid, sentence FROM sentences WHERE used = (SELECT MIN(used) FROM sentences) ORDER BY RANDOM() LIMIT 1')
  78.        row = cursor.fetchone()
  79.    # tell the database the sentence has been used once more, and prepare the sentence
  80.    B = row[1]
  81.    cursor.execute('UPDATE sentences SET used=used+1 WHERE rowid=?', (row[0],))


CREDITOS:https://rodic.fr/blog/python-chatbot-1/


Título: Re: [PYTHON] ChatBot que aprende
Publicado por: overxfl0w13 en 10 Septiembre 2017, 03:37 am
Puedes intentar usar esto: https://goo.gl/JVMv2D

:)