File size: 16,007 Bytes
ed90723
 
 
 
 
 
b965150
 
 
 
 
dd4984c
b965150
dd4984c
b965150
dd4984c
b965150
 
 
dd4984c
b965150
 
 
2801b1d
98f345d
 
 
 
8edf57c
98f345d
 
 
868c29e
 
 
 
 
 
dd4984c
 
 
 
 
b965150
dd4984c
 
 
29b0e72
 
851906c
dd4984c
 
96464f7
 
 
dd4984c
 
 
851906c
dd4984c
851906c
 
 
 
 
 
 
6693af0
 
 
bcd82f0
 
012b1e7
2fdc2fa
7555f0a
29b0e72
6693af0
dd4984c
 
 
29b0e72
b818d16
2fdc2fa
 
 
 
 
654d791
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2fdc2fa
ed90723
6ea7880
851906c
 
dd4984c
29b0e72
 
dd4984c
 
 
 
868c29e
 
 
 
7ab78c1
 
 
 
 
 
dd4984c
 
29b0e72
ed90723
edcbbc9
29b0e72
 
 
 
 
 
ed90723
 
 
dd4984c
851906c
 
868c29e
 
98f345d
 
868c29e
 
98f345d
 
 
 
 
 
8a36aff
29b0e72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
851906c
 
 
dd4984c
2aa2829
dd4984c
851906c
dd4984c
b965150
851906c
868c29e
851906c
 
bcd82f0
 
6132d52
bcd82f0
7555f0a
 
 
 
96464f7
 
 
becc108
2aa2829
 
 
becc108
29b0e72
becc108
2801b1d
 
 
 
 
 
 
 
 
510a6aa
2801b1d
 
 
 
 
510a6aa
2801b1d
 
becc108
851906c
700a15c
 
dd4984c
4dfcec8
851906c
 
6132d52
 
6693af0
7555f0a
 
 
 
96464f7
 
851906c
 
 
7555f0a
6693af0
851906c
 
 
 
 
 
dd4984c
be92746
b1a42bb
7555f0a
 
 
be92746
 
 
 
7ab78c1
96464f7
a1bdecf
851906c
b818d16
7555f0a
 
dd4984c
6132d52
851906c
b965150
b1a42bb
29b0e72
b1a42bb
 
851906c
b965150
851906c
 
b965150
121b962
2fdc2fa
 
 
 
 
 
121b962
2fdc2fa
dd4984c
 
 
 
2aa2829
807f438
6693af0
b965150
dd4984c
b965150
6693af0
851906c
96464f7
98f345d
a1bdecf
 
b965150
 
dd4984c
868c29e
edcbbc9
29b0e72
edcbbc9
012b1e7
29b0e72
 
 
 
 
 
 
 
 
 
 
 
 
 
012b1e7
 
be92746
868c29e
b965150
868c29e
 
 
 
 
 
 
 
 
b965150
dd4984c
6132d52
dd4984c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b965150
dd4984c
 
3cc65de
a1bdecf
dd4984c
 
 
 
b965150
dd4984c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e929cc
dd4984c
 
 
b965150
 
a1bdecf
96464f7
 
 
 
a1bdecf
 
 
 
868c29e
a1bdecf
 
868c29e
 
96464f7
 
 
 
 
 
a1bdecf
96464f7
 
 
 
868c29e
becc108
 
 
 
96464f7
b965150
b516c99
6132d52
dd4984c
6132d52
dd4984c
 
 
b746cfb
b965150
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
#--------------------------------------------------------------------------------
# 
# See Hugging Face from VSCode setup.txt for publishing instructions
#
#--------------------------------------------------------------------------------

import gradio as gr
import os
import random
import time
import numpy as np
import json

qs = {}

theme = gr.themes.Base(
    primary_hue="gray",
    secondary_hue="gray",
).set(
    background_fill_primary_dark='*neutral_950',
    background_fill_secondary_dark='*neutral_950'
)


# Define the function to handle API calls for the chatbot response
def chatbot_api(user_message):
    # Process the input and generate a response
    response = f"Chatbot response to: {user_message}"  # Example response generation
    response = print_log_file()
    return response


import uuid

# Add a function to generate a unique session ID
def generate_session_id():
    return str(uuid.uuid4())

from urllib.parse import parse_qs
def parse_query_params(query_string):
    parsed_params = parse_qs(query_string)
    simplified_params = {k: v[0] if len(v) == 1 else v for k, v in parsed_params.items()}
    return simplified_params

def app_inits():
    global qs
    

    print("DEBUG: App Init")    
    # The path to the QA text file
    filename = 'images/qa_data.txt'

    full_path = os.path.abspath(filename)
    print("Loading responces from ", full_path)

    # Open the file and load the object
    with open(filename, 'r') as file:
        qs = json.load(file)
        
        print("Loaded Q & A")
        #print(qs[0], '\n')

        # Get all keys
        keys = list(qs.keys())
        # Print the keys
        print("Keys:", keys)
        

        # https://bumk766fall2023-chatbot.hf.space/?dw=0.02&dl=0.0001&ds=1
        # print("CALL URL: http://127.0.0.1:7860/?dw=0.02&dl=0.0001")
        # https://bumk766fall2023-chatbot.hf.space/?dw=0.02&dl=0.0001&ds=0.4

        #print("CALL URL: http://127.0.0.1:7860/?dw=0.02&dl=0.0001&ds=0.4")
        #print("CALL URL: http://127.0.0.1:7860/?dw=0.2&dl=0.000001&ds=0.000004")
        #print("CALL URL: http://127.0.0.1:7860/?dw=0.002&dl=0.02&ds=0.000004")
        print("CALL URL: http://127.0.0.1:7860/?dw=0.002&dl=0.02&ds=0.000004&tv=1&dr=1&P=P1")

    return    

with gr.Blocks(theme = theme) as demo:

    #chatbot = gr.Chatbot(value = [[None,'**How can I help you today?**']], elem_id="chatbot", layout = "panel", avatar_images=("images/user.jpg", "images/bot.jpg"),)
    #chatbot = gr.Chatbot(elem_id="chatbot", layout = "panel", avatar_images=("images/user.jpg", "images/bot.jpg"),)
    #chatbot = gr.Chatbot(elem_id="chatbot", layout = "panel", avatar_images=("images/user.jpg", "images/bot.jpg"),render_markdown=False)
    chatbot = gr.Chatbot(elem_id="chatbot", layout = "panel", avatar_images=("images/user.jpg", "images/bot.jpg"),latex_delimiters=[],)


    # --------------------------------------------------------------------------------------------

    def print_log_file():
        """Prints the contents of the log file 'images/log_data.txt'."""
        try:
            with open('images/log_data.txt', 'r') as log_file:
                log_content = log_file.read()
            return log_content
        except FileNotFoundError:
            return "Log file not found."

    # --------------------------------------------------------------------------------------------

    # --------------------------------------------------------------------------------------------

    def delete_log_file():
        """Deletes the log file 'images/log_data.txt' if it exists."""
        try:
            if os.path.exists('images/log_data.txt'):
                os.remove('images/log_data.txt')
                return "Log file deleted successfully."
            else:
                return "Log file does not exist."
        except Exception as e:
            return f"Error deleting log file: {e}"

    # --------------------------------------------------------------------------------------------



    # height=800,  

    #def get_params(request: gr.Request, param_hiddentextbox):
    def get_params(request: gr.Request):        

        #print("DEBUG: get_params")
        
        headers = request.headers
        host = request.client.host
        user_agent = request.headers["user-agent"]
        params = request.query_params

        session_id = generate_session_id()  # Generate a unique session ID
        return str(params), session_id

        #return {
        #    "ip": host,
        #    "user_agent": user_agent,
        #    "headers": headers,
        #    "URL_params": params,
        #}

    with gr.Row(equal_height=True):
        #msg = gr.Textbox(show_label=False, placeholder="Message ChatGPT...", max_lines = 5,container = False,)
        #msg = gr.Textbox(value="Pre-filled value", show_label=False, placeholder="Message ChatGPT...", max_lines=5, container=False, interactive=False)
        # USE FOR NOT EDITABLE VERSION
        
        #print("DEBUG: Loading preset_prompt")
        #print(gr.__version__)

        preset_prompt = ""
        msg = gr.Textbox(value=preset_prompt, show_label=False, placeholder=preset_prompt, max_lines = 5,container = False, interactive=False)



        btn = gr.Button(value="", min_width=80, size = "lg", icon="images/button.jpg", scale= 0)
        #param_hiddentextbox = gr.Textbox(show_label=False, visible=False, container = False,)
        url_params = gr.State()
        session_id = gr.State()



    #demo.load(get_params, None, url_params, queue=False)
    demo.load(get_params, None, [url_params, session_id], queue=False)
    
    # Add invisible API endpoint using these components
    invisible_input = gr.Textbox(visible=False)
    invisible_output = gr.Textbox(visible=False)
    demo.load(chatbot_api, inputs=invisible_input, outputs=invisible_output, api_name="chatbot_endpoint")


    def set_text_in_textbox(request: gr.Request):
    # Return an updated value for the Textbox
        #return gr.Textbox.update(value="Hello from page load!")
        print("DEBUG: set_text_in_textbox")    

        local_params = str(request.query_params)
       

        if local_params != "":

            local_params_parsed = parse_query_params(local_params)
            print(local_params_parsed)

            Prompt_Index = local_params_parsed.get("P", "PX")
            
            print(Prompt_Index)

        else:    
            return ("No prompt parameter specified")
        

        preset_prompt = qs.get(Prompt_Index, "Prompt Index Not Found")
        return (preset_prompt)

    demo.load(fn=set_text_in_textbox, inputs=None, outputs=msg)

    #demo.load(get_params, param_hiddentextbox, param_hiddentextbox, queue=False)

    # --------------------------------------------------------------------------------------------
    def user(user_message, history):
        print("User prompted ", user_message)
        return "", history + [[user_message, None]]
    # --------------------------------------------------------------------------------------------


    # --------------------------------------------------------------------------------------------
    def bot( history, url_params, session_id):
    
        global qs
        
        DelayBetweenWords = 0.7
        DelayBetweenLetters = 0.0001
        DelayBetweenSentences = .6
        
        TextVariant = 1
        DelayRandomizer = 1
        
        QID15 = 0
        QID16 = 0
        
        # Go fast for debugging
        DelayBetweenWords = 0.0001
        DelayBetweenLetters = 0.0001
        DelayBetweenSentences = .0001

       

        #-- Maintenance
        #
        # Check if the input prompt is "show log" or "delete log"
        text = history[-1][0].lower().strip()
        if text == "show log":
            # Display log content if prompt matches
            log_content = print_log_file()
            history[-1][1] = log_content
            yield history
            return 
        elif text == "delete log":
            # Delete log file if prompt matches
            delete_message = delete_log_file()
            history[-1][1] = delete_message
            yield history
            return 
        #
        #-----------------------------

        #time.sleep(.02)
        print("----------  url_params ------------ ")
        print(url_params)

        
        if url_params != "":
            params = parse_query_params(url_params)
            DelayBetweenWords = float(params.get("dw", DelayBetweenWords))
            DelayBetweenLetters = float(params.get("dl", DelayBetweenLetters))
            DelayBetweenSentences = float(params.get("ds", DelayBetweenSentences))

            TextVariant =  int(params.get("tv", TextVariant))
            DelayRandomizer = int(params.get("dr", DelayRandomizer))
            
            QID15 = int(params.get("QID15", QID15))
            QID16 = int(params.get("QID16", QID16))
        else:    
            print("No parameters provided. Using defaults")
        
        print("dv=", DelayBetweenWords, "dl=", DelayBetweenLetters, "ds=", DelayBetweenSentences, "tv=", TextVariant, "dr=", DelayRandomizer, "QID15=", QID15, "QID16=", QID16 )

        # Get all keys
        keywords =  list(qs.keys())
        # Print the keys
        print("Keys:", keywords )

        # String typed by user
        text = history[-1][0]
        print("User Input:", text)

        bot_message_sorry = qs.get("Sorry", "Sorry, I cannot answer that...")


        if text != "":
           search_keyword = find_best_keyword_match(keywords, text)     
        else:   
           search_keyword = "None"

        log_message("-ENTRY- [query]: " + text + " [params]: " + url_params + " [keyword]: " + search_keyword, session_id)
        
        if search_keyword == "None":
           #bot_message = "Sorry, don't know any restaurants at this location..." + " [DEBUG (params: " + url_params + ")]" 
           #bot_message = "I'm sorry, but I can only provide information about Mexican restaurants in Tucson at the moment."
           bot_message = bot_message_sorry
        else:
           output_text = qs.get(search_keyword, "Keyword identified. No information found.")
           bot_message = output_text

        if text == "debug":
           bot_message = "[DEBUG (ver. 2/4/2025) params: " + url_params + "\nKeys:\n" + "\n".join(keywords) + "]"


        # initialize  new entry
        history[-1][1] = ""
        
        # output text letter-by-letter
        for character in bot_message:
            
            if character == "^":
                history[-1][1] += " "
            elif character == "@":
                history[-1][1] += "<BR>"

            elif character != "=":
                history[-1][1] += character

            # Delay between words
            if character == " ":
                time.sleep(DelayBetweenWords)
            # Overall print speed
            #elif character == "." or character == ",":
            elif character == "=":
                time.sleep(DelayBetweenSentences)
            else: 
                time.sleep(DelayBetweenLetters)

            yield history 
    
        log_message("-EXIT - [query]: " + text + " [params]: " + url_params + " [keyword]: " + search_keyword, session_id)
       
    # --------------------------------------------------------------------------------------------
 


# Events handling

#    btn.click(user, [msg, chatbot], [msg, chatbot], queue=False, show_progress=False).then(
#        bot, [chatbot, url_params, session_id], chatbot, concurrency_limit=50, api_name="chatbot_api"
#    )

    def hide_button():
    # Hide the button entirely
        return gr.Button(visible=bool(0))

    btn.click(user, [msg, chatbot], [msg, chatbot], queue=False, show_progress=False).then(
    hide_button,   # hide_button
    inputs=None,
    outputs=btn    # Apply the updates to the same button
    ).then(
        lambda: "", None, msg
    ).then(
        bot, [chatbot, url_params, session_id], chatbot, concurrency_limit=50
    )



    msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False, show_progress=False).then(
        bot, [chatbot, url_params, session_id], chatbot, concurrency_limit=50
    )


    # btn.click(user, [msg, chatbot], [msg, chatbot], queue=False, show_progress=False).then(
    #     bot, [chatbot, url_params], chatbot, concurrency_limit=50
    # )
    
    # msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False, show_progress=False).then(
    #     bot, [chatbot, url_params], chatbot, concurrency_limit=50
    # )
    

# --------------------------------------------------------------------------------------------

def normalize(s):
    """Lowercase and strip the string to normalize it."""
    return s.lower().strip()

def levenshtein_distance(s1, s2):
    """Calculate the Levenshtein distance between two strings."""
    if len(s1) < len(s2):
        return levenshtein_distance(s2, s1)

    if len(s2) == 0:
        return len(s1)

    previous_row = range(len(s2) + 1)
    for i, c1 in enumerate(s1):
        current_row = [i + 1]
        for j, c2 in enumerate(s2):
            insertions = previous_row[j + 1] + 1
            deletions = current_row[j] + 1
            substitutions = previous_row[j] + (c1 != c2)
            current_row.append(min(insertions, deletions, substitutions))
        previous_row = current_row
    
    return previous_row[-1]


def find_best_keyword_match(keywords, text, max_distance=3):
    """Find the best keyword match in the text, allowing for some misspelling."""
    text_normalized = normalize(text)
    best_match = None
    lowest_distance = float('inf')
    
    for keyword in keywords:
        keyword_normalized = normalize(keyword)
        # Calculate the Levenshtein distance for composite keywords by comparing against slices of the text
        if ' ' in keyword_normalized:
            slice_length = len(keyword_normalized)
            for i in range(len(text_normalized) - slice_length + 1):
                text_slice = text_normalized[i:i+slice_length]
                distance = levenshtein_distance(text_slice, keyword_normalized)
                if distance < lowest_distance:
                    best_match = keyword
                    lowest_distance = distance
        else:
            # For single words, compare against each word in the text
            for word in text_normalized.split():
                distance = levenshtein_distance(word, keyword_normalized)
                if distance < lowest_distance:
                    best_match = keyword
                    lowest_distance = distance

    if lowest_distance <= max_distance:
        return best_match
    return "None"


from datetime import datetime
import threading

# Initialize a global threading lock
log_lock = threading.Lock()

# The path to the log file
filename = 'images/log_data.txt'

def log_message(param, session_id):
    # Get current timestamp
    timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

    # Define the log file name based on session ID
    #filename = f'{session_id}_log_data.txt'
    session_id_text = f'{session_id}'

    # Prepare log message
    log_msg = f'{session_id_text}: {timestamp}: : {param}\n'

    # Open the log file, append the message, and ensure the file is closed properly
    # Use the lock to ensure that only one thread writes to the file at a time
    with log_lock:
        with open(filename, 'a') as log_file:
            log_file.write(log_msg)

    # Get the absolute path of the log file
    abs_path = os.path.abspath(filename)
    
    # Print the absolute path for debugging purposes
    print(f'Writing to Log file: {abs_path}')


# --------------------------------------------------------------------------------------------
# Launching
# --------------------------------------------------------------------------------------------

app_inits()    
demo.queue()
demo.launch(allowed_paths=["."], max_threads=40, show_error=True)