Created
June 21, 2023 22:07
-
-
Save brayevalerien/2de45054c68c3d37d559b0c10206af35 to your computer and use it in GitHub Desktop.
Generate messages from a Whatsapp conversation using Markov Chains
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
import numpy as np | |
class MarkovChainGenerator: | |
def __init__(self, order=1, length=10): | |
self.order = order | |
self.length = length | |
self.transitions = {} | |
def fit(self, X): | |
for sequence in X: | |
for i in range(len(sequence) - self.order): | |
current_state = tuple(sequence[i:i+self.order]) | |
next_state = sequence[i+self.order] | |
if current_state not in self.transitions: | |
self.transitions[current_state] = [] | |
self.transitions[current_state].append(next_state) | |
return self | |
def generate(self): | |
generated_sequence = [] | |
current_state = random.choice(list(self.transitions.keys())) | |
for _ in range(self.length): | |
if current_state not in self.transitions: | |
break | |
next_state = random.choice(self.transitions[current_state]) | |
generated_sequence.append(next_state) | |
current_state = tuple(list(current_state[1:]) + [next_state]) | |
return generated_sequence | |
def load_conversation(file_path): | |
with open(file_path, 'r', encoding='utf-8') as file: | |
conversation = file.read().splitlines() | |
return conversation | |
conversation = load_conversation('./convo.txt') # Change ./convo.txt to the path of your own file | |
sequence = [line.split(': ')[-1].split() for line in conversation if line.strip()] | |
generator = MarkovChainGenerator(order=1, length=5000) | |
generator.fit(sequence) | |
generated_sequence = generator.generate() | |
generated_message = ' '.join(generated_sequence) | |
print(f"Generated message :\n{generated_message}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment