File size: 6,405 Bytes
0a83f93
 
 
 
fd2f0f1
f1551db
0a83f93
 
f1551db
0a83f93
 
 
 
 
 
 
 
 
 
 
 
65a59f6
0a83f93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f1551db
0a83f93
f1551db
0a83f93
 
 
 
 
 
0b0cfe4
 
0a83f93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8203c0d
0a83f93
 
 
 
 
 
 
 
 
 
f1551db
8423d42
72e5b1f
0a83f93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
edd3353
 
32f4125
e7c673d
8423d42
32f4125
 
8423d42
aa89a53
0a83f93
8423d42
0a83f93
4375a0d
 
 
e7c673d
4375a0d
e7c673d
4375a0d
 
d9624a2
0a83f93
 
528ba3a
925fe77
528ba3a
d46c189
e7c673d
d46c189
528ba3a
4375a0d
 
e7c673d
7556402
e7c673d
0a83f93
 
4375a0d
0a83f93
 
e7c673d
0a83f93
6ca5b12
 
30ecd0a
0a83f93
30ecd0a
0a83f93
 
9b7e747
0a83f93
 
30ecd0a
0a83f93
3c5a674
 
c3691ee
 
 
3c5a674
925fe77
0a83f93
 
 
b35eba7
925fe77
b46b483
4375a0d
d9624a2
 
6786510
 
 
d9624a2
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
import os
import boto3
import ast
import traceback
import time

a = os.environ.get("AWS_ACCESS_KEY_ID")
b = os.environ.get("AWS_SECRET_ACCESS_KEY")

def dynamo(username, message):
    try:
        # Create a DynamoDB client
        dynamodb = boto3.client('dynamodb',aws_access_key_id=b,
                                    aws_secret_access_key=a,
                                    region_name='us-east-1'
                                    )

        # Specify the table name
        table_name = 'PROD_historial_olivia'
    
        # Define the key you want to filter by
        key = 'usuario'
        value = username
    
        # Create the key condition expression as a string
        key_condition_expression = f"{key} = :val"

        # Define the expression attribute values
        expression_attribute_values = {
            ":val": {"S": value}  # Assuming 'phone' is of string type
        }

        # Query the table
        response = dynamodb.query(
            TableName=table_name,
            KeyConditionExpression=key_condition_expression,
            ExpressionAttributeValues=expression_attribute_values
        )
    
        # Retrieve the filtered items
        items = response['Items']
        
        sorted_items = sorted(items, key=lambda x: x['fecha']['S'])
        
        mensajes = []
        if len(sorted_items) > 0:
                if message == ast.literal_eval(sorted_items[-1]['interaccion']['S'])['Estudiante']:
                    return ast.literal_eval(sorted_items[-1]['interaccion']['S'])['Olivia']
                else:
                    return 'esperar'
        else:
            return 'esperar'               
        
    except Exception as e:
        print(f"An error occurred: {str(e)}")
        # Handle the error as needed
        # You can raise the error again, log it, or return a specific error response
        traceback_info = traceback.format_exc()
        print(traceback_info)
        return {'statusCode': 500, 'body': 'An error occurred during item query.'}

def activar_olivia(username, current_message):
        sns_client = boto3.client('sns',
                                aws_access_key_id=b,
                                aws_secret_access_key=a,
                                region_name='us-east-1'
                                )

        topic_arn = os.environ.get("ARN_OLIVIA")

        attributes = {
            'username': {'DataType': 'String', 'StringValue': username},
            'message': {'DataType': 'String', 'StringValue': current_message}}

        r = sns_client.publish(
                            TopicArn=topic_arn,
                            Message='huggingface',
                            MessageAttributes=attributes
                        )   




def lookup_users(username, password):
    print(username)
    try:
        dynamodb = boto3.client('dynamodb',aws_access_key_id=b,
                                    aws_secret_access_key=a,
                                    region_name='us-east-1'
                                    )

        # Specify the table name
        table_name = 'PROD_usuario_olivia'
    
        # Query the table
        response = dynamodb.scan(
            TableName=table_name
        )
    
        # Retrieve the filtered items
        items = response['Items']
        if len(items)>0:
            for i in items:
                if username == i['usuario']['S'] and password == i['contraseña']['S']:
                    os.environ['user'] = username
                    return True
    
        return False
                
    except Exception as e:
        print(f"An error occurred: {str(e)}")
        return False

def greet(name, password):
    r=lookup_users(name, password)
    if r == False:
        mensaje = f"""<div style="display: flex; align-items: center;"><img src="Red.png" width="10" height="10">&nbsp; No Conectado: &nbsp;<b>No se encontró el usuario</b></div>"""
    elif r == True:
        mensaje = f"""<div style="display: flex; align-items: center;"><img src="Green.png" width="10" height="10">&nbsp; Conectado como: &nbsp;<b>{name}</b></div>"""
    return mensaje

def gradio_interface():
    import gradio as gr
    
    with gr.Blocks(theme=gr.themes.Soft()) as demo:

        with gr.Row():
            username = gr.Textbox(scale=3,label="Usuario",info='Ingresa tu nombre de usuario')

            password = gr.Textbox(scale=3,label="Contraseña",type="password",info='Ingresa tu contraseña')
            greet_btn = gr.Button("Conectar",scale=1,interactive=True)
        output = gr.Markdown()
        greet_btn.click(fn=greet, inputs=[username,password], outputs=output, api_name="greet")
        print("username:",username)        
        chatbot = gr.Chatbot(avatar_images=["avatar.jpg", "olivia.jpeg"],
                             label="Esta conversación es anónima y personal. Habla con Olivia para ayudar a mejorar a tu colegio y curso ❤️",
                             bubble_full_width=False
                             )
        msg = gr.Textbox(label='Escribe tu respuesta y pulsa "Enter"',interactive=True, info="Nota: Tu respuesta puede ser tan larga como tu quieras")
    
        def respond(current_message, chat_history):
            username = os.getenv('user')
            activar_olivia(username, current_message)

            t = 0
            while t < 100:
                respuesta = dynamo(username, current_message)
                print('RESPUESTA:', str(respuesta))
                
                if respuesta != 'esperar':
                    break
                else:
                    time.sleep(0.5)
                    t+=0.5
            
            if '.' in respuesta:
                b=respuesta.split('.')
                chat_history.append(("<b>Estudiante:</b> \n"+current_message, "<b>Olivia:</b> \n"+b[0]))
                chat_history.append((None,"<b>Olivia:</b> \n"+b[1]))
            else:
                chat_history.append(("<b>Estudiante:</b> \n"+current_message, "<b>Olivia:</b> \n"+respuesta))
        
            # operaciones para guardar la interaccion
    
            return "", chat_history

        msg.submit(respond, [msg, chatbot], [msg, chatbot])
        demo.queue(max_size=90)
        demo.launch(max_threads=60)     
    


if __name__ == "__main__":
    # Start the HTTP server in a separate thread
    gradio_interface()