Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,24 +1,30 @@
|
|
1 |
import os
|
2 |
import streamlit as st
|
3 |
-
from PyPDF2
|
4 |
import numpy as np
|
5 |
from groq import Groq
|
6 |
import faiss
|
7 |
import fitz
|
|
|
8 |
|
9 |
-
#
|
10 |
-
#groq_client = Groq(api_key="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")
|
11 |
def get_groq_client():
|
12 |
-
|
13 |
-
|
|
|
|
|
|
|
|
|
|
|
14 |
# Function to extract text from PDF
|
15 |
-
def extract_pdf_content(
|
16 |
-
|
|
|
17 |
content = ""
|
18 |
for page in doc:
|
19 |
content += page.get_text()
|
20 |
return content
|
21 |
-
|
22 |
# Function to split content into chunks
|
23 |
def chunk_text(text, chunk_size=500):
|
24 |
words = text.split()
|
@@ -32,7 +38,10 @@ def compute_embeddings(text_chunks):
|
|
32 |
messages=[{"role": "user", "content": chunk}],
|
33 |
model="llama3-70b-8192"
|
34 |
)
|
35 |
-
|
|
|
|
|
|
|
36 |
return np.array(embeddings)
|
37 |
|
38 |
# Function to build FAISS index
|
@@ -61,7 +70,9 @@ def compute_query_embedding(query):
|
|
61 |
messages=[{"role": "user", "content": query}],
|
62 |
model="llama3-70b-8192"
|
63 |
)
|
64 |
-
|
|
|
|
|
65 |
|
66 |
# Streamlit app
|
67 |
st.title("Generative AI for Electrical Engineering Education with FAISS and Groq")
|
@@ -72,40 +83,46 @@ uploaded_file = st.sidebar.file_uploader("Upload Study Material (PDF)", type=["p
|
|
72 |
topic = st.sidebar.text_input("Enter a topic (e.g., Newton's Third Law)")
|
73 |
|
74 |
if uploaded_file:
|
75 |
-
|
76 |
-
|
77 |
-
|
|
|
78 |
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
|
83 |
-
|
84 |
-
|
85 |
|
86 |
-
|
87 |
-
|
|
|
|
|
88 |
|
89 |
# Generate study material
|
90 |
if st.button("Generate Study Material"):
|
91 |
if topic:
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
|
|
|
|
|
|
110 |
else:
|
111 |
st.warning("Please enter a topic!")
|
|
|
1 |
import os
|
2 |
import streamlit as st
|
3 |
+
from PyPDF2 import PdfReader
|
4 |
import numpy as np
|
5 |
from groq import Groq
|
6 |
import faiss
|
7 |
import fitz
|
8 |
+
from io import BytesIO
|
9 |
|
10 |
+
# Function to set up Groq API client
|
|
|
11 |
def get_groq_client():
|
12 |
+
api_key = os.getenv("groq_api")
|
13 |
+
if not api_key:
|
14 |
+
raise ValueError("Groq API key not found in environment variables.")
|
15 |
+
return Groq(api_key=api_key)
|
16 |
+
|
17 |
+
groq_client = get_groq_client()
|
18 |
+
|
19 |
# Function to extract text from PDF
|
20 |
+
def extract_pdf_content(uploaded_file):
|
21 |
+
pdf_stream = BytesIO(uploaded_file.read()) # Convert to file-like object
|
22 |
+
doc = fitz.open(stream=pdf_stream, filetype="pdf")
|
23 |
content = ""
|
24 |
for page in doc:
|
25 |
content += page.get_text()
|
26 |
return content
|
27 |
+
|
28 |
# Function to split content into chunks
|
29 |
def chunk_text(text, chunk_size=500):
|
30 |
words = text.split()
|
|
|
38 |
messages=[{"role": "user", "content": chunk}],
|
39 |
model="llama3-70b-8192"
|
40 |
)
|
41 |
+
# Convert response to NumPy array
|
42 |
+
embedding_str = response['choices'][0]['message']['content']
|
43 |
+
embedding = np.fromstring(embedding_str, sep=",")
|
44 |
+
embeddings.append(embedding)
|
45 |
return np.array(embeddings)
|
46 |
|
47 |
# Function to build FAISS index
|
|
|
70 |
messages=[{"role": "user", "content": query}],
|
71 |
model="llama3-70b-8192"
|
72 |
)
|
73 |
+
# Convert to NumPy array
|
74 |
+
embedding_str = response['choices'][0]['message']['content']
|
75 |
+
return np.fromstring(embedding_str, sep=",").reshape(1, -1)
|
76 |
|
77 |
# Streamlit app
|
78 |
st.title("Generative AI for Electrical Engineering Education with FAISS and Groq")
|
|
|
83 |
topic = st.sidebar.text_input("Enter a topic (e.g., Newton's Third Law)")
|
84 |
|
85 |
if uploaded_file:
|
86 |
+
try:
|
87 |
+
# Extract and process file content
|
88 |
+
content = extract_pdf_content(uploaded_file)
|
89 |
+
st.sidebar.success(f"{uploaded_file.name} uploaded successfully!")
|
90 |
|
91 |
+
# Chunk and compute embeddings
|
92 |
+
chunks = chunk_text(content)
|
93 |
+
embeddings = compute_embeddings(chunks)
|
94 |
|
95 |
+
# Build FAISS index
|
96 |
+
index = build_faiss_index(embeddings)
|
97 |
|
98 |
+
st.write("**File Processed and Indexed for Search**")
|
99 |
+
st.write(f"Total chunks created: {len(chunks)}")
|
100 |
+
except Exception as e:
|
101 |
+
st.error(f"Error processing file: {e}")
|
102 |
|
103 |
# Generate study material
|
104 |
if st.button("Generate Study Material"):
|
105 |
if topic:
|
106 |
+
try:
|
107 |
+
st.header(f"Study Material: {topic}")
|
108 |
+
|
109 |
+
# Compute query embedding
|
110 |
+
query_embedding = compute_query_embedding(topic)
|
111 |
+
|
112 |
+
# Search FAISS index
|
113 |
+
if uploaded_file:
|
114 |
+
results = search_faiss_index(index, query_embedding, chunks, top_k=3)
|
115 |
+
st.write("**Relevant Content from Uploaded File:**")
|
116 |
+
for result, distance in results:
|
117 |
+
st.write(f"- {result} (Similarity: {distance:.2f})")
|
118 |
+
else:
|
119 |
+
st.warning("No file uploaded. Generating AI-based content instead.")
|
120 |
+
|
121 |
+
# Generate content using Groq's Llama3-70B-8192 model
|
122 |
+
ai_content = generate_professional_content_groq(topic)
|
123 |
+
st.write("**AI-Generated Content (Groq - Llama3-70B-8192):**")
|
124 |
+
st.write(ai_content)
|
125 |
+
except Exception as e:
|
126 |
+
st.error(f"Error generating content: {e}")
|
127 |
else:
|
128 |
st.warning("Please enter a topic!")
|