TahaRasouli commited on
Commit
c46ce88
·
verified ·
1 Parent(s): 84a66de

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +126 -0
app.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import json
3
+ import os
4
+ from groq import Groq
5
+
6
+ # Function to recursively extract all unique keys
7
+ def extract_keys(data, parent_key='', keys_set=None):
8
+ if keys_set is None:
9
+ keys_set = set()
10
+
11
+ if isinstance(data, dict):
12
+ for key, value in data.items():
13
+ full_key = f"{parent_key}.{key}" if parent_key else key
14
+ keys_set.add(full_key)
15
+ extract_keys(value, full_key, keys_set)
16
+ elif isinstance(data, list):
17
+ for item in data:
18
+ extract_keys(item, parent_key, keys_set)
19
+
20
+ return keys_set
21
+
22
+ # Function to recursively extract all values for a specific full key path
23
+ def extract_values(data, full_key_path, parent_key=''):
24
+ values = []
25
+ current_key = full_key_path.split('.')[0]
26
+ remaining_path = '.'.join(full_key_path.split('.')[1:])
27
+
28
+ if isinstance(data, dict):
29
+ for key, value in data.items():
30
+ if key == current_key:
31
+ if remaining_path:
32
+ values.extend(extract_values(value, remaining_path))
33
+ else:
34
+ values.append(value)
35
+ elif isinstance(value, (dict, list)):
36
+ values.extend(extract_values(value, full_key_path, parent_key=key))
37
+
38
+ elif isinstance(data, list):
39
+ for item in data:
40
+ values.extend(extract_values(item, full_key_path))
41
+
42
+ return values
43
+
44
+ # Streamlit App
45
+ def main():
46
+ st.title("JSON Enquiry")
47
+
48
+ # Sidebar for file upload and key selection
49
+ st.sidebar.title("Options")
50
+
51
+ uploaded_file = st.sidebar.file_uploader("Upload a JSON file", type="json")
52
+
53
+ if uploaded_file is not None:
54
+ data = json.load(uploaded_file)
55
+
56
+ # Extract unique keys
57
+ unique_keys = extract_keys(data)
58
+
59
+ # Display the unique keys
60
+ st.sidebar.subheader("Unique Keys")
61
+ selected_keys = st.sidebar.multiselect("Select keys to extract values for", sorted(unique_keys))
62
+
63
+ if selected_keys:
64
+ st.subheader("Extracted Values")
65
+ selected_json_content = {}
66
+ for key in selected_keys:
67
+ values = extract_values(data, key)
68
+ selected_json_content[key] = values
69
+ st.write(f"**Values for '{key}':**")
70
+ st.write(values)
71
+
72
+ # Convert selected content to a JSON string
73
+ selected_json_string = json.dumps(selected_json_content, indent=2)
74
+
75
+ # Create a prompt using the prefabricated template
76
+ prefabricated_prompt = f"Convert the given json object into unstructured readable paragraph. Output just the final paragraph. json: {selected_json_string}"
77
+
78
+ # Initialize the LLM client once
79
+ client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
80
+
81
+ if 'messages' not in st.session_state:
82
+ st.session_state['messages'] = []
83
+
84
+ if st.button("Explain JSON!"):
85
+ # Add initial prompt to messages
86
+ st.session_state.messages.append({"role": "user", "content": prefabricated_prompt})
87
+
88
+ chat_completion = client.chat.completions.create(
89
+ messages=st.session_state.messages,
90
+ model="llama3-8b-8192",
91
+ )
92
+
93
+ response_content = chat_completion.choices[0].message.content
94
+ st.session_state.messages.append({"role": "assistant", "content": response_content})
95
+
96
+ # Display only the assistant's responses in the chat history
97
+ st.subheader("LLM Responses")
98
+ for msg in st.session_state.messages:
99
+ if msg['role'] == 'assistant':
100
+ st.write(f"**Assistant:** {msg['content']}")
101
+
102
+ # Input for follow-up messages
103
+ follow_up_message = st.text_area("Enter your message:", height=100)
104
+
105
+ if st.button("Send Follow-Up"):
106
+ if follow_up_message.strip() != "":
107
+ st.session_state.messages.append({"role": "user", "content": follow_up_message})
108
+
109
+ chat_completion = client.chat.completions.create(
110
+ messages=st.session_state.messages,
111
+ model="llama3-8b-8192",
112
+ )
113
+
114
+ response_content = chat_completion.choices[0].message.content
115
+ st.session_state.messages.append({"role": "assistant", "content": response_content})
116
+
117
+ st.write(f"**Assistant:** {response_content}")
118
+ else:
119
+ st.warning("Please enter a message to continue the conversation.")
120
+ else:
121
+ st.sidebar.warning("Select at least one key to extract values.")
122
+ else:
123
+ st.sidebar.info("Please upload a JSON file to get started.")
124
+
125
+ if __name__ == "__main__":
126
+ main()