NazmulHasanNihal commited on
Commit
7f139a3
·
verified ·
1 Parent(s): 05c7f6e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -34
app.py CHANGED
@@ -1,4 +1,3 @@
1
-
2
  from openai import OpenAI
3
  import streamlit as st
4
  import os
@@ -8,6 +7,7 @@ import json
8
  import xml.etree.ElementTree as ET
9
  from io import StringIO, BytesIO
10
  from time import sleep
 
11
 
12
  # Load API key securely
13
  API_KEY = os.getenv("NV_API_KEY", "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")
@@ -43,47 +43,41 @@ def display_typing_animation(text):
43
  st.markdown(char, unsafe_allow_html=True)
44
  sleep(0.02)
45
 
46
- # Handle file uploads
47
  def process_uploaded_file(file):
48
  file_type = file.type
49
  if file_type == "text/csv":
50
  df = pd.read_csv(file)
51
- return df.head().to_markdown()
52
  elif file_type in ["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "application/vnd.ms-excel"]:
53
  df = pd.read_excel(file)
54
- return df.head().to_markdown()
55
  elif file_type == "application/json":
56
  data = json.load(file)
57
- return json.dumps(data, indent=4)
58
- elif file_type == "text/xml" or "application/xml":
59
  tree = ET.parse(file)
60
  root = tree.getroot()
61
- return f"Root Tag: {root.tag}\nAttributes: {root.attrib}"
62
  elif file_type == "application/pdf":
63
- return "PDF uploads are currently not processed for content. Try text-based analysis."
64
  else:
65
- return "Unsupported file format."
66
-
67
- # File upload section
68
- with st.sidebar.expander("Upload Files"):
69
- uploaded_file = st.file_uploader("Upload your file (CSV, XLSX, JSON, XML, PDF)", type=["csv", "xlsx", "json", "xml", "pdf"])
70
- if uploaded_file:
71
- st.markdown(f"**Uploaded File Analysis:**\n```markdown\n{process_uploaded_file(uploaded_file)}\n```")
72
 
73
  # Display previous messages
74
  for message in st.session_state.messages:
75
  with st.chat_message(message["role"]):
76
  st.markdown(message["content"])
77
 
78
- # Handle user input
79
- if prompt := st.chat_input("Ask a coding-related question or general query"):
80
- st.session_state.messages.append({"role": "user", "content": prompt})
81
  with st.chat_message("user"):
82
- st.markdown(prompt)
83
 
84
  # Assistant response
85
  with st.chat_message("assistant"):
86
- with st.spinner('<div class="spinner">🌀 Thinking...</div>'):
87
  try:
88
  # Generate response
89
  stream = client.chat.completions.create(
@@ -100,7 +94,7 @@ if prompt := st.chat_input("Ask a coding-related question or general query"):
100
  response_chunks.append(chunk.choices[0].delta.content)
101
  display_typing_animation(chunk.choices[0].delta.content)
102
  response = "".join(response_chunks)
103
- st.markdown(f"```markdown\n{response}\n```")
104
 
105
  # Save assistant message
106
  st.session_state.messages.append({"role": "assistant", "content": response})
@@ -108,16 +102,13 @@ if prompt := st.chat_input("Ask a coding-related question or general query"):
108
  except Exception as e:
109
  st.error(f"An error occurred: {e}")
110
 
111
- # Add custom CSS for better visuals
112
- st.markdown("""
113
- <style>
114
- .spinner {
115
- animation: pulse 1s infinite;
116
- }
117
- @keyframes pulse {
118
- 0% { opacity: 1; }
119
- 50% { opacity: 0.5; }
120
- 100% { opacity: 1; }
121
- }
122
- </style>
123
- """, unsafe_allow_html=True)
 
 
1
  from openai import OpenAI
2
  import streamlit as st
3
  import os
 
7
  import xml.etree.ElementTree as ET
8
  from io import StringIO, BytesIO
9
  from time import sleep
10
+ from tabulate import tabulate
11
 
12
  # Load API key securely
13
  API_KEY = os.getenv("NV_API_KEY", "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")
 
43
  st.markdown(char, unsafe_allow_html=True)
44
  sleep(0.02)
45
 
46
+ # Function to process uploaded files
47
  def process_uploaded_file(file):
48
  file_type = file.type
49
  if file_type == "text/csv":
50
  df = pd.read_csv(file)
51
+ return f"**CSV File Analysis:**\n{tabulate(df.head(), headers='keys', tablefmt='grid')}"
52
  elif file_type in ["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "application/vnd.ms-excel"]:
53
  df = pd.read_excel(file)
54
+ return f"**Excel File Analysis:**\n{tabulate(df.head(), headers='keys', tablefmt='grid')}"
55
  elif file_type == "application/json":
56
  data = json.load(file)
57
+ return f"**JSON File Analysis:**\n```json\n{json.dumps(data, indent=4)}\n```"
58
+ elif file_type in ["text/xml", "application/xml"]:
59
  tree = ET.parse(file)
60
  root = tree.getroot()
61
+ return f"**XML File Root Tag:** {root.tag}\n**Attributes:** {root.attrib}"
62
  elif file_type == "application/pdf":
63
+ return "PDF uploads are not processed for content. Try text-based analysis."
64
  else:
65
+ return "Unsupported file format. Please upload CSV, Excel, JSON, XML, or PDF files."
 
 
 
 
 
 
66
 
67
  # Display previous messages
68
  for message in st.session_state.messages:
69
  with st.chat_message(message["role"]):
70
  st.markdown(message["content"])
71
 
72
+ # Handle user input or file uploads
73
+ if user_input := st.chat_input("Type a message or upload a file below."):
74
+ st.session_state.messages.append({"role": "user", "content": user_input})
75
  with st.chat_message("user"):
76
+ st.markdown(user_input)
77
 
78
  # Assistant response
79
  with st.chat_message("assistant"):
80
+ with st.spinner("The assistant is processing..."):
81
  try:
82
  # Generate response
83
  stream = client.chat.completions.create(
 
94
  response_chunks.append(chunk.choices[0].delta.content)
95
  display_typing_animation(chunk.choices[0].delta.content)
96
  response = "".join(response_chunks)
97
+ st.markdown(response)
98
 
99
  # Save assistant message
100
  st.session_state.messages.append({"role": "assistant", "content": response})
 
102
  except Exception as e:
103
  st.error(f"An error occurred: {e}")
104
 
105
+ # Add file upload to chat input
106
+ st.markdown("### File Upload:")
107
+ uploaded_file = st.file_uploader("Upload your file (CSV, XLSX, JSON, XML, PDF)", type=["csv", "xlsx", "json", "xml", "pdf"])
108
+ if uploaded_file:
109
+ with st.chat_message("user"):
110
+ st.markdown(f"**Uploaded File:** {uploaded_file.name}")
111
+ with st.chat_message("assistant"):
112
+ with st.spinner("Processing the uploaded file..."):
113
+ file_analysis = process_uploaded_file(uploaded_file)
114
+ st.markdown(file_analysis)