Spaces:
Sleeping
Sleeping
import gradio as gr | |
from typing import List | |
import string | |
class TrieNode: | |
def __init__(self): | |
self.children = {} | |
self.is_end_of_word = False | |
class Autocomplete: | |
def __init__(self): | |
self.root = TrieNode() | |
def insert(self, word): | |
node = self.root | |
for char in word: | |
if char not in node.children: | |
node.children[char] = TrieNode() | |
node = node.children[char] | |
node.is_end_of_word = True | |
def autocomplete(self, prefix): | |
node = self.root | |
for char in prefix: | |
if char not in node.children: | |
return [] | |
node = node.children[char] | |
return self._find_completions(node, prefix) | |
def _find_completions(self, node, prefix): | |
completions = [] | |
if node.is_end_of_word: | |
completions.append(prefix) | |
for char, child_node in node.children.items(): | |
completions.extend(self._find_completions(child_node, prefix + char)) | |
return completions | |
def preprocess_text_file(file_path): | |
words_and_numbers = [] | |
with open(file_path, "r") as file: | |
for line in file: | |
word_or_number = line.strip().lower() | |
words_and_numbers.append(word_or_number) | |
return words_and_numbers | |
def build_autocomplete_system(file_path): | |
autocomplete_system = Autocomplete() | |
words_and_numbers = preprocess_text_file(file_path) | |
for item in words_and_numbers: | |
autocomplete_system.insert(item) | |
return autocomplete_system | |
def autocomplete(prefix): | |
prefix = prefix.lower() # Convert input to lowercase | |
suggestions = autocomplete_system.autocomplete(prefix) | |
return suggestions | |
if __name__ == "__main__": | |
# Specify the path to the text file containing words and numbers | |
file_path = "/drugs.txt" | |
# Build the autocomplete system | |
autocomplete_system = build_autocomplete_system(file_path) | |
# Create a Gradio interface | |
iface = gr.Interface( | |
fn=autocomplete, | |
inputs=gr.inputs.Textbox(), | |
outputs=gr.outputs.Textbox(), | |
live=True, | |
capture_session=True, | |
) | |
iface.launch() | |