adrienbrdne commited on
Commit
c80fd6c
·
verified ·
1 Parent(s): 63e8e5a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +185 -70
app.py CHANGED
@@ -1,86 +1,201 @@
1
  import streamlit as st
2
  import requests
3
  import pandas as pd
4
-
5
- # --- API Configuration ---
6
- API_URL = "https://adrienbrdne-fastapi-kig.hf.space/"
7
- ENDPOINT = f"{API_URL}/generate-key-issues" # API endpoint name remains unchanged
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
  # --- Streamlit Interface ---
10
  st.set_page_config(page_title="Problematic Generator", layout="wide")
11
  st.title("Generate Problematics from Query")
12
 
13
- # Input field for the user query
14
- user_query = st.text_input(
15
- "Enter your query here:",
16
- placeholder="Example: deploying edge computing for real-time AI-driven traffic management systems in smart cities"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  )
18
 
19
- # Button to submit the query
20
- if st.button("Generate Problematics"):
21
- if user_query: # Check if the user entered something
22
- st.info(f"Sending query to API: {ENDPOINT}")
23
- st.write(f"Query: \"{user_query}\"")
24
-
25
- # Prepare data for the POST request
26
- data = {"query": user_query}
27
-
28
- try:
29
- # Show a loading spinner during the API call
30
- with st.spinner("Calling API to generate problematics..."):
31
- response = requests.post(ENDPOINT, json=data) # Added a timeout
32
-
33
- # Check the response status
34
- if response.status_code == 200:
35
- st.success("Response received successfully!")
36
- result = response.json()
37
-
38
- # Check if 'key_issues' key exists and is a list
39
- if 'key_issues' in result and isinstance(result['key_issues'], list):
40
- # Convert the 'key_issues' list to a Pandas DataFrame
41
- df = pd.DataFrame(result['key_issues'])
42
-
43
- # Remove the 'id' column if it exists
44
- if 'id' in df.columns:
45
- df_display = df.drop(columns=['id'])
46
- else:
47
- st.warning("Column 'id' was not found in the received data.")
48
- df_display = df
49
-
50
- # Display the DataFrame
51
- st.subheader("Generated Problematics (DataFrame):")
52
- st.dataframe(df_display, use_container_width=True) # Display dataframe with full container width
53
-
54
- # Optional: Display raw JSON response for verification
55
- # st.subheader("Raw JSON Response Received:")
56
- # st.json(result)
57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  else:
59
- st.error("API response does not contain the expected 'key_issues' key or it is not a list.")
60
- st.json(result) # Display the received response for debugging
61
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  else:
63
- # Display an error if status is not 200
64
- st.error(f"API Call Error: Status {response.status_code}")
65
  try:
66
- # Try to display the API error message if it's JSON
67
- error_details = response.json()
68
- st.json(error_details)
69
- except requests.exceptions.JSONDecodeError:
70
- # Otherwise, display the raw text response
71
- st.text(response.text)
72
-
73
- except requests.exceptions.RequestException as e:
74
- # Handle connection or timeout errors
75
- st.error(f"API Connection Error: {e}")
76
- except Exception as e:
77
- # Handle any other unexpected errors
78
- st.error(f"An unexpected error occurred: {e}")
79
-
 
 
 
 
80
  else:
81
- # Message if the user clicks the button without entering a query
82
- st.warning("Please enter a query before generating.")
 
 
 
 
 
 
 
83
 
84
- # Initial instructions
85
- else:
86
- st.info("Enter a query in the field above and click 'Generate Problematics' to query the API.")
 
1
  import streamlit as st
2
  import requests
3
  import pandas as pd
4
+ import google.generativeai as genai
5
+ import os # To potentially use environment variables for API key
6
+
7
+ # --- Configuration ---
8
+ # API Endpoint for initial key issues
9
+ KEY_ISSUES_API_URL = "https://adrienbrdne-fastapi-kig.hf.space/"
10
+ KEY_ISSUES_ENDPOINT = f"{KEY_ISSUES_API_URL}/generate-key-issues"
11
+
12
+ # Gemini Model Configuration
13
+ GEMINI_MODEL_NAME = "gemini-2.5-flash-preview-04-17"
14
+
15
+ # --- Helper Functions ---
16
+ def call_key_issues_api(query):
17
+ """Calls the first API to get key issues."""
18
+ data = {"query": query}
19
+ try:
20
+ response = requests.post(KEY_ISSUES_ENDPOINT, json=data)
21
+ response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
22
+ return response.json()
23
+ except requests.exceptions.RequestException as e:
24
+ st.error(f"Error calling Key Issues API: {e}")
25
+ return None
26
+ except Exception as e:
27
+ st.error(f"An unexpected error occurred during Key Issues API call: {e}")
28
+ return None
29
+
30
+ def call_gemini_api(api_key, title, description, technical_topic):
31
+ """Calls the Gemini API to generate a problematic."""
32
+ if not api_key:
33
+ st.error("Gemini API Key is missing. Please enter it above.")
34
+ return None
35
+
36
+ try:
37
+ # Configure the Gemini client
38
+ genai.configure(api_key=api_key)
39
+
40
+ # Define the prompt using an f-string
41
+ prompt = f"""I want you to create a technical problematic using a key issue composed of a title and a detailed description.
42
+ Here is the title of the key issue to deal with: <title>{title}</title>
43
+
44
+ And here is the associated description: <description>{description}</description>
45
+
46
+ This key issue is part of the following technical topic: <technical_topic>{technical_topic}</technical_topic>
47
+
48
+ The problematic must be in interrogative form.
49
+ As the output, I only want you to provide the problematic found, nothing else.
50
+
51
+ Here are examples of problematics that you could create, it shows the level of specificity that you should aim for:
52
+
53
+ Example 1: 'How can autonomous, policy-driven security decisions be achieved by distributed network elements in a telecommunication network without continuous central authority interaction, whilst ensuring overall network security objectives?'
54
+ Example 2: 'How can secure communication between network elements and the confidentiality of network-related information (network element identities, topology) be guaranteed in 6G networks against unauthorized disclosure?'
55
+ Example 3: 'How can secure access to and communication with network elements be achieved in a 6G network, considering the heterogeneous and dynamic nature of network elements and the evolving landscape of cyber threats?'
56
+ Example 4: 'How can telecommunication systems guarantee long-term security against quantum attacks, considering the complexity and heterogeneity of current and future network architectures and services?'
57
+
58
+ As far as possible, avoid using acronyms in the problematic.
59
+ Try to be about the same length as the examples if possible."""
60
+
61
+ # Create the model instance
62
+ model = genai.GenerativeModel(GEMINI_MODEL_NAME)
63
+
64
+ # Generate content
65
+ # Note: The config part from the original snippet isn't directly used here,
66
+ # plain text is the default for generate_content with text prompts.
67
+ response = model.generate_content(prompt)
68
+
69
+ # Check for safety ratings or blocks if necessary (optional)
70
+ # if response.prompt_feedback.block_reason:
71
+ # st.error(f"Content generation blocked: {response.prompt_feedback.block_reason}")
72
+ # return None
73
+
74
+ return response.text
75
+
76
+ except Exception as e:
77
+ st.error(f"Error calling Gemini API: {e}")
78
+ return None
79
 
80
  # --- Streamlit Interface ---
81
  st.set_page_config(page_title="Problematic Generator", layout="wide")
82
  st.title("Generate Problematics from Query")
83
 
84
+ # --- Session State Initialization ---
85
+ # Use session state to store data across reruns
86
+ if 'key_issues_df' not in st.session_state:
87
+ st.session_state.key_issues_df = None
88
+ if 'original_query' not in st.session_state:
89
+ st.session_state.original_query = ""
90
+ if 'generated_problematic' not in st.session_state:
91
+ st.session_state.generated_problematic = None
92
+ if 'selected_index' not in st.session_state:
93
+ st.session_state.selected_index = 0 # Default to first index
94
+
95
+ # --- API Key Input ---
96
+ st.sidebar.header("API Configuration")
97
+ # Try getting key from environment first, then fallback to input
98
+ default_gemini_key = os.environ.get("GEMINI_API_KEY", "")
99
+ gemini_api_key = st.sidebar.text_input(
100
+ "Enter your Gemini API Key:",
101
+ type="password",
102
+ value=default_gemini_key, # Pre-fill if found in env var
103
+ help="You can get your API key from Google AI Studio."
104
  )
105
 
106
+ # --- Step 1: Get Key Issues ---
107
+ st.header("Step 1: Generate Key Issues")
108
+ user_query_input = st.text_input(
109
+ "Enter your technical topic/query:",
110
+ placeholder="Example: deploying edge computing for real-time AI-driven traffic management systems in smart cities",
111
+ key="query_input_key" # Unique key for the input widget
112
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
 
114
+ if st.button("Generate Key Issues", key="generate_issues_button"):
115
+ # Clear previous results when generating new issues
116
+ st.session_state.key_issues_df = None
117
+ st.session_state.generated_problematic = None
118
+ st.session_state.original_query = ""
119
+ st.session_state.selected_index = 0
120
+
121
+ if user_query_input:
122
+ st.session_state.original_query = user_query_input # Store the query
123
+ st.info(f"Sending query to Key Issues API: {KEY_ISSUES_ENDPOINT}")
124
+ with st.spinner("Calling API to generate key issues..."):
125
+ result = call_key_issues_api(user_query_input)
126
+
127
+ if result:
128
+ if 'key_issues' in result and isinstance(result['key_issues'], list) and result['key_issues']:
129
+ st.success("Key Issues received successfully!")
130
+ temp_df = pd.DataFrame(result['key_issues'])
131
+ # Ensure 'title' and 'description' columns exist
132
+ if 'title' in temp_df.columns and 'description' in temp_df.columns:
133
+ # Select and reorder necessary columns, reset index for selection
134
+ st.session_state.key_issues_df = temp_df
135
  else:
136
+ st.error("API response is missing 'title' or 'description' columns in 'key_issues'.")
137
+ st.json(result) # Show response for debugging
138
+ else:
139
+ st.error("API response does not contain a valid 'key_issues' list.")
140
+ st.json(result) # Show response for debugging
141
+ else:
142
+ st.warning("Please enter a query before generating key issues.")
143
+
144
+ # --- Step 2: Display DataFrame and Select Issue ---
145
+ if st.session_state.key_issues_df is not None:
146
+ st.subheader("Generated Key Issues:")
147
+ st.dataframe(st.session_state.key_issues_df, use_container_width=True)
148
+
149
+ st.header("Step 2: Select a Key Issue and Generate Problematic")
150
+
151
+ max_index = len(st.session_state.key_issues_df) - 1
152
+ if max_index >= 0: # Check if DataFrame is not empty
153
+ selected_index = st.number_input(
154
+ f"Select the index of the key issue to use (0 to {max_index}):",
155
+ min_value=0,
156
+ max_value=max_index,
157
+ value=st.session_state.selected_index, # Use session state value
158
+ step=1,
159
+ key="index_selector"
160
+ )
161
+ st.session_state.selected_index = selected_index # Update session state
162
+
163
+ # --- Step 3: Call Gemini API ---
164
+ if st.button("Generate Problematic for Selected Index", key="generate_problematic_button"):
165
+ st.session_state.generated_problematic = None # Clear previous problematic
166
+ if not gemini_api_key:
167
+ st.error("Please enter your Gemini API Key in the sidebar.")
168
  else:
 
 
169
  try:
170
+ # Retrieve selected row data
171
+ selected_row = st.session_state.key_issues_df.loc[st.session_state.selected_index]
172
+ title = selected_row['title']
173
+ description = selected_row['description']
174
+ technical_topic = st.session_state.original_query # Use the stored original query
175
+
176
+ st.info(f"Generating problematic for index {st.session_state.selected_index} using Gemini...")
177
+ with st.spinner("Calling Gemini API..."):
178
+ problematic_text = call_gemini_api(gemini_api_key, title, description, technical_topic)
179
+
180
+ if problematic_text:
181
+ st.session_state.generated_problematic = problematic_text
182
+ # Error messages are handled within call_gemini_api
183
+
184
+ except KeyError:
185
+ st.error(f"Could not find data for index {st.session_state.selected_index}. Please check the DataFrame.")
186
+ except Exception as e:
187
+ st.error(f"An unexpected error occurred during problematic generation: {e}")
188
  else:
189
+ st.warning("The generated key issues list is empty.")
190
+
191
+
192
+ # --- Step 4: Display Generated Problematic ---
193
+ if st.session_state.generated_problematic:
194
+ st.subheader("Generated Problematic:")
195
+ st.markdown(f"> {st.session_state.generated_problematic}") # Display as a blockquote
196
+ # Or use st.text_area for easy copying:
197
+ # st.text_area("Generated Problematic:", st.session_state.generated_problematic, height=150)
198
 
199
+ # --- Initial Instructions ---
200
+ if st.session_state.key_issues_df is None and not user_query_input:
201
+ st.info("Enter a technical topic/query above and click 'Generate Key Issues' to start.")