File size: 2,192 Bytes
b922052
79afa41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2bc574d
79afa41
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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 = "/home/user/app/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()