waqasbm commited on
Commit
a481607
·
verified ·
1 Parent(s): 6775b08

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +90 -58
app.py CHANGED
@@ -1,60 +1,92 @@
1
- from fastapi import FastAPI, Query
2
- from fastapi.middleware.cors import CORSMiddleware
3
  import pandas as pd
4
- from typing import List, Optional
5
- import uvicorn
6
-
7
- app = FastAPI()
8
-
9
- # Enable CORS for frontend
10
- app.add_middleware(
11
- CORSMiddleware,
12
- allow_origins=["*"], # Or restrict to your frontend origin
13
- allow_credentials=True,
14
- allow_methods=["*"],
15
- allow_headers=["*"],
16
- )
17
-
18
- # Load Excel into memory
19
- df = pd.read_excel("data.xlsx", engine="openpyxl")
20
-
21
- # Smart URL resolver
22
- def generate_smart_url(entity: str, name: str) -> str:
23
- base_urls = {
24
- "ISO": "https://www.iso.org/search.html?q=",
25
- "IEEE": "https://ieeexplore.ieee.org/search/searchresult.jsp?newsearch=true&queryText=",
26
- "IEC": "https://webstore.iec.ch/searchform?q=",
27
- "API": "https://www.api.org/products-and-services/standards"
 
 
 
 
 
 
 
 
 
 
 
 
28
  }
29
- for key in base_urls:
30
- if key.lower() in entity.lower():
31
- return base_urls[key] + name.replace(" ", "+")
32
- return "https://www.google.com/search?q=" + entity + "+" + name.replace(" ", "+")
33
-
34
- @app.get("/search")
35
- def search_standards(entity: Optional[str] = Query(None), name: Optional[str] = Query(None)):
36
- results = df.copy()
37
-
38
- if entity:
39
- results = results[results["Standards Entity"].str.contains(entity, case=False, na=False)]
40
- if name:
41
- results = results[results["Standard Name"].str.contains(name, case=False, na=False)]
42
-
43
- if results.empty:
44
- return []
45
-
46
- standards = []
47
- for _, row in results.iterrows():
48
- standard = {
49
- "Standards Entity": row["Standards Entity"],
50
- "Standard Name": row["Standard Name"],
51
- "Description": row["Description"],
52
- "URL": row["URL"] if pd.notna(row.get("URL")) else generate_smart_url(row["Standards Entity"], row["Standard Name"])
53
- }
54
- standards.append(standard)
55
-
56
- return standards
57
-
58
- # Optional: for local testing
59
- if __name__ == "__main__":
60
- uvicorn.run(app, host="0.0.0.0", port=8000)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
 
2
  import pandas as pd
3
+ import requests
4
+ import os
5
+
6
+ # ----------------------------
7
+ # Configuration
8
+ # ----------------------------
9
+ st.set_page_config(page_title="Instrumentation Standards AI Assistant", layout="wide")
10
+
11
+ # ----------------------------
12
+ # Load Data
13
+ # ----------------------------
14
+ @st.cache_data
15
+ def load_data():
16
+ df = pd.read_excel("data.xlsx", engine='openpyxl')
17
+ return df
18
+
19
+ df = load_data()
20
+
21
+ # ----------------------------
22
+ # GROQ API Summarizer
23
+ # ----------------------------
24
+ GROQ_API_KEY = os.getenv("Standardssearch") # Set this in your environment or .streamlit/secrets.toml
25
+
26
+ def summarize_with_groq(text, model="llama3-70b-8192"):
27
+ url = "https://api.groq.com/openai/v1/chat/completions"
28
+ headers = {
29
+ "Authorization": f"Bearer {GROQ_API_KEY}",
30
+ "Content-Type": "application/json"
31
+ }
32
+ payload = {
33
+ "model": model,
34
+ "messages": [
35
+ {"role": "system", "content": "You are a helpful assistant summarizing industrial standards for instrumentation and control engineers."},
36
+ {"role": "user", "content": f"Summarize the following technical standard for a professional audience:\n\n{text}"}
37
+ ],
38
+ "temperature": 0.5
39
  }
40
+
41
+ response = requests.post(url, headers=headers, json=payload)
42
+ if response.status_code == 200:
43
+ return response.json()["choices"][0]["message"]["content"]
44
+ else:
45
+ return f"Error: {response.status_code} - {response.text}"
46
+
47
+ # ----------------------------
48
+ # UI Layout
49
+ # ----------------------------
50
+
51
+ st.title("📘 Instrumentation & Control Engineering Standards")
52
+ st.markdown("This app helps Instrumentation & Control Engineers search and understand global engineering standards.")
53
+ st.markdown("**Standards included:** ANSI, API, ASME, ASTM, BS, IEC, ISA, ISO, MSS, NACE, NAMUR, NFPA, PIP, EN, and more.")
54
+
55
+ # Search Filters
56
+ st.subheader("🔍 Search for Industrial Standards")
57
+ col1, col2 = st.columns(2)
58
+
59
+ with col1:
60
+ entity_input = st.text_input("Enter Standard Entity").strip()
61
+
62
+ with col2:
63
+ name_input = st.text_input("Enter Standard Name").strip()
64
+
65
+ # Filtered Results
66
+ if entity_input or name_input:
67
+ filtered_df = df[
68
+ df["Standards Entity"].str.contains(entity_input, case=False, na=False) &
69
+ df["Standard Name"].str.contains(name_input, case=False, na=False)
70
+ ]
71
+
72
+ if not filtered_df.empty:
73
+ st.success(f"✅ Found {len(filtered_df)} matching standard(s). Click to expand.")
74
+
75
+ for index, row in filtered_df.iterrows():
76
+ with st.expander(f"📘 {row['Standard Name']}"):
77
+ st.markdown(f"**Entity:** {row['Standards Entity']}")
78
+ st.markdown(f"**Description:** {row['Description']}")
79
+
80
+ if st.button("Summarize with AI", key=f"summarize_{index}"):
81
+ with st.spinner("Querying GROQ model for summary..."):
82
+ summary = summarize_with_groq(row["Description"])
83
+ st.markdown("### ✨ AI Summary")
84
+ st.write(summary)
85
+ else:
86
+ st.warning("No matching standards found.")
87
+ else:
88
+ st.info("Enter at least one search term to begin.")
89
+
90
+ # Footer
91
+ st.markdown("---")
92
+ st.caption("Built with ❤️ for Control & Instrumentation Engineers | Powered by GROQ + Streamlit")