File size: 6,925 Bytes
0f4fe40
 
 
 
 
 
 
 
 
 
 
20e4932
0f4fe40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
960b172
 
0f4fe40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
960b172
0f4fe40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f38549
 
0f4fe40
 
 
0f38549
0f4fe40
 
0f38549
 
 
 
 
 
 
0f4fe40
0f38549
0f4fe40
 
 
 
 
 
 
0df8b02
 
0f4fe40
 
 
 
9ae9c63
0f4fe40
 
 
 
 
 
 
 
 
 
 
0f38549
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
960b172
0f38549
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f4fe40
 
 
 
0f38549
0f4fe40
 
 
 
 
 
 
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
import streamlit as st
from azure.cosmos import CosmosClient, PartitionKey
import os

# Cosmos DB configuration
ENDPOINT = "https://acae-afd.documents.azure.com:443/"
SUBSCRIPTION_ID = "003fba60-5b3f-48f4-ab36-3ed11bc40816"

# You'll need to set these environment variables or use Azure Key Vault
DATABASE_NAME = os.environ.get("COSMOS_DATABASE_NAME")
CONTAINER_NAME = os.environ.get("COSMOS_CONTAINER_NAME")
Key = os.environ.get("Key")

def create_stored_procedure(container):
    stored_procedure_definition = {
        'id': 'processQTPrompts',
        'body': '''
        function processQTPrompts(promptText) {
            var context = getContext();
            var container = context.getCollection();
            var response = context.getResponse();

            var prompts = promptText.split('\\n');
            var results = [];

            for (var i in prompts) {
                var prompt = prompts[i].trim();
                if (prompt.startsWith('QT ')) {
                    var querySpec = {
                        query: "SELECT * FROM c WHERE c.id = @id",
                        parameters: [{ name: "@id", value: prompt }]
                    };

                    var isAccepted = container.queryDocuments(
                        container.getSelfLink(),
                        querySpec,
                        function (err, items, responseOptions) {
                            if (err) throw err;

                            if (items.length > 0) {
                                // Update existing record
                                var item = items[0];
                                item.occurrenceCount++;
                                container.replaceDocument(
                                    item._self,
                                    item,
                                    function (err, replacedItem) {
                                        if (err) throw err;
                                        results.push(replacedItem);
                                    }
                                );
                            } else {
                                // Create new record
                                var newItem = {
                                    id: prompt,
                                    occurrenceCount: 1,
                                    evaluation: ""
                                };
                                container.createDocument(
                                    container.getSelfLink(),
                                    newItem,
                                    function (err, createdItem) {
                                        if (err) throw err;
                                        results.push(createdItem);
                                    }
                                );
                            }
                        }
                    );

                    if (!isAccepted) throw new Error("The query was not accepted by the server.");
                }
            }

            response.setBody(results);
        }
        '''
    }
    container.scripts.create_stored_procedure(body=stored_procedure_definition)

def ensure_stored_procedure_exists(container):
    try:
        container.scripts.get_stored_procedure('processQTPrompts')
    except:
        create_stored_procedure(container)

def process_qt_prompts(container, prompt_text):
    # Use the first prompt as the partition key
    first_prompt = prompt_text.split('\n')[0].strip()
    return container.scripts.execute_stored_procedure(
        sproc='processQTPrompts',
        params=[prompt_text],
        partition_key=first_prompt
    )

def insert_record(container, record):
    try:
        response = container.create_item(body=record)
        return True, response
    except Exception as e:
        return False, str(e)

# Streamlit app
st.title("🌟 Cosmos DB Record Insertion and QT Prompt Processor")

# Login section
if 'logged_in' not in st.session_state:
    st.session_state.logged_in = False

if not st.session_state.logged_in:
    st.subheader("πŸ” Login")
    #input_key = st.text_input("Enter your Cosmos DB Primary Key", type="password")
    input_key = Key
    if st.button("πŸš€ Login"):
        if input_key:
            st.session_state.primary_key = input_key
            st.session_state.logged_in = True
            st.rerun()
        else:
            st.error("Please enter a valid key")
else:
    # Initialize Cosmos DB client
    client = CosmosClient(ENDPOINT, credential=st.session_state.primary_key)
    database = client.get_database_client(DATABASE_NAME)
    container = database.get_container_client(CONTAINER_NAME)

    # Ensure the stored procedure exists
    ensure_stored_procedure_exists(container)

    # Tab for different operations
    tab1, tab2 = st.tabs(["Insert Record", "Process QT Prompts"])

    with tab1:
        st.subheader("πŸ“ Enter Record Details")
        id = st.text_input("ID")
        name = st.text_input("Name")
        age = st.number_input("Age", min_value=0, max_value=150)
        city = st.text_input("City")

        if st.button("πŸ’Ύ Insert Record"):
            record = {
                "id": id,
                "name": name,
                "age": age,
                "city": city
            }
            
            success, response = insert_record(container, record)
            if success:
                st.success("βœ… Record inserted successfully!")
                st.json(response)
            else:
                st.error(f"❌ Failed to insert record: {response}")

    with tab2:
        st.subheader("πŸ“ Enter QT Prompts")
        default_text = "QT Crystal finders: Bioluminescent crystal caverns, quantum-powered explorers, prismatic hues, alien planet\nQT robot art: Cybernetic metropolis, sentient androids, rogue AI, neon-infused palette\nQT the Lava girl: Volcanic exoplanet, liquid metal rivers, heat-immune heroine, molten metallic palette"
        qt_prompts = st.text_area("QT Prompts", value=default_text, height=300)

        if st.button("πŸš€ Process QT Prompts"):
            try:
                results = process_qt_prompts(container, qt_prompts)
                
                # Display results in a dataframe
                df_data = [{"Prompt": item['id'], "Occurrence Count": item['occurrenceCount']} for item in results]
                st.dataframe(df_data)
            except Exception as e:
                st.error(f"An error occurred: {str(e)}")

    # Logout button
    if st.button("πŸšͺ Logout"):
        st.session_state.logged_in = False
        st.rerun()

    # Display connection info
    st.sidebar.subheader("πŸ”— Connection Information")
    st.sidebar.text(f"Endpoint: {ENDPOINT}")
    st.sidebar.text(f"Subscription ID: {SUBSCRIPTION_ID}")
    st.sidebar.text(f"Database: {DATABASE_NAME}")
    st.sidebar.text(f"Container: {CONTAINER_NAME}")