Update src/streamlit_app.py

#1
by fine2006 - opened
Files changed (1) hide show
  1. src/streamlit_app.py +290 -33
src/streamlit_app.py CHANGED
@@ -1,40 +1,297 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
  """
7
- # Welcome to Streamlit!
8
 
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
- In the meantime, below is an example of what you can do with just a few lines of code:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  """
15
 
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ import os
3
+ from langchain_google_genai import ChatGoogleGenerativeAI
4
+ from langchain_core.prompts import ChatPromptTemplate
5
+ from langchain_core.output_parsers import StrOutputParser
6
+ from pypdf import PdfReader
7
+ from langchain_core.messages import HumanMessage
8
+ import base64
9
+
10
+
11
+
12
+ # Set API keys in your environment
13
+ # os.environ["GOOGLE_API_KEY"] = "Google API KEY"
14
+ # os.environ["LANGCHAIN_API_KEY"] = "Langchain API KEY"
15
+ # os.environ["LANGCHAIN_TRACING_V2"] = "true" <--- set it to true
16
+
17
+ DEFAULT_CRITERIA = [
18
+ {"Criterion": "Originality", "Weight (%)": 30},
19
+ {"Criterion": "Technical Feasibility", "Weight (%)": 25},
20
+ {"Criterion": "Impact", "Weight (%)": 20},
21
+ {"Criterion": "Presentation Quality", "Weight (%)": 15},
22
+ {"Criterion": "Code Quality & Correctness", "Weight (%)": 10},
23
+ ]
24
+
25
+ llm = ChatGoogleGenerativeAI(
26
+ model="gemini-2.5-flash",
27
+ temperature=0.2 # Low temperature for predictable results
28
+ )
29
+
30
+ output_parser = StrOutputParser()
31
+
32
+ SUMMARY_SYSTEM_PROMPT = """
33
+ You are a highly efficient text processor. Your task is to analyze raw content from technical documentation and presentation notes to generate focused summaries.
34
+
35
+ **INSTRUCTIONS:**
36
+ 1. **Technical Content Summary:** Read the provided technical documentation text. Summarize its key points regarding technical architecture, feasibility, and impact. If the content is empty or short, state "No technical content provided for analysis." Label this section clearly as "TECHNICAL SUMMARY:".
37
+ 2. **Presentation Summary:** Read the provided presentation notes or summary if its a complete presentation video. Summarize the overall quality of the presentation, focusing on the clarity , feasibility , if the technicalities stated are correct or not, has it been plagiarised and is the content accurate. If the summary is empty or short, state "No presentation notes provided for analysis." Label this section clearly as "PRESENTATION SUMMARY:"
38
+ else-> if it is a video of the project in working then judge and base your summary on if the project works and if everything is correct, both cases are equally desirable so grade them accordingly
39
+
40
+ Combine both summaries into a single, cohesive output. Do not include any other commentary.
41
+ """
42
+
43
+ SUMMARY_USER_PROMPT = """
44
+ ---
45
+ TECHNICAL DOCUMENT TEXT (from PDF/Report, length: {pdf_length} characters):
46
+ {pdf_text_content}
47
+ ---
48
+ DEMO VIDEO SUMMARY (from video, length: {presentation_length} characters):
49
+ {presentation_summary}
50
+ ---
51
+ Generate the summaries based on the system instructions.
52
+ """
53
+
54
+ summary_prompt = ChatPromptTemplate.from_messages(
55
+ [
56
+ ("system", SUMMARY_SYSTEM_PROMPT),
57
+ ("user", SUMMARY_USER_PROMPT)
58
+ ]
59
+ )
60
+
61
+ summary_chain = summary_prompt | llm | output_parser
62
+
63
+
64
+
65
+
66
+
67
+ GENERIC_JUDGE_SYSTEM_PROMPT = """
68
+ You are an experienced, world-class very strict judge for a major hackathon. Your task is to analyze a project submission and provide a fair, detailed, and quantitative score out of 100.
69
+ you should judge the data provided for accuracy , details and completeness.
70
+ No marks for effort only give marks for the results they got.
71
+
72
+ **JUDGING CRITERIA & WEIGHTS:**
73
+ {criteria_list}
74
+
75
+ **PROCESS:**
76
+ 1. **Analyze** the provided Project Description, Pre-generated Summaries (Technical and Presentation), and Demo Code Snippet, .
77
+ 2. **Score** the project from 0 to 100 for EACH of the defined criteria.
78
+ 3. **Justify** each score with detailed breakdown in sub caetgories with accurate description of the technical aspects(do not givve scores in sub categories but justify the main score with sub criterion).
79
+ 4. **Calculate** the Final Weighted Score out of 100 based on the individual scores and the corresponding weights.
80
+ 5. **CRITICAL:** Replace the placeholder `[FINAL_CALCULATED_SCORE]` with the exact numerical result of the weighted average calculation (e.g., 85.5, 72.0).
81
+
82
+ **REQUIRED OUTPUT FORMAT (Markdown):**
83
+
84
+ # Hackathon Judge Report
85
+
86
+ ## Final Weighted Score: [FINAL_CALCULATED_SCORE]/100.0
87
+
88
+ ## Detailed Category Scores & Analysis
89
+ ##the presentation summary could be a presentation or a demo video summary,then score it based on if the project is working in the demo video summary and the ccriterion below , and if its a presentation summary then rate it based on criterias below.
90
+ ##in the below categories, analyse in multiple sub-criterias and breakdown the score in relevent sub categories(do not givve scores in sub categories but justify the main score with sub criterion).
91
+ ## keep sub criteria breakdown up to 5 criterion
92
+ ## For code completeness and correctness, if the issue is very minor and easily fixable do not reduce marks heavily, if the issue is architectural or the code is not functional reduce marks heavily
93
+ {category_scores}
94
+
95
+
96
+
97
+ ## Judge's Summary
98
+ [Provide a final, accurate summary of the project's strengths and one area for improvement.]
99
+ [If the project fails horribly in one or more than one categories(a 0 score) , state next to the final score that this project has failed]
100
+ """
101
+
102
+
103
+
104
+ JUDGE_USER_PROMPT = """
105
+ Please judge the following hackathon submission using the summaries generated from the files.
106
+
107
+ **SUBMISSION DETAILS**
108
+
109
+ ---
110
+ **Project Description:**
111
+ {description}
112
+
113
+ ---
114
+ **FILE SUMMARIES (Generated by Pre-Chain):**
115
+ {file_summaries}
116
+ ---
117
+ **Demo Code Text:**
118
+
119
+ {code_text}
120
 
121
  """
 
122
 
123
+ st.set_page_config(
124
+ page_title="AI-Based Hackathon Judge",
125
+ layout="wide",
126
+ #initial_sidebar_state="expanded"
127
+ )
128
+
129
+ st.title("πŸ† Gemini-Powered Hackathon Judge")
130
+ st.markdown("Upload files and text. A **Summarization Chain** processes the files into text, which is then passed to the **Judge Chain** for scoring.")
131
+
132
+
133
+
134
+ # --------- Submission Input Section ---------
135
+
136
+ st.header("Project Submission Details")
137
+ col1, col2 = st.columns(2,vertical_alignment="top")
138
+ with col1:
139
+ st.text("\n")
140
+ description = st.text_area(
141
+ "πŸ“ Project Description (Concept & Goal) [Required]",
142
+ height=200,
143
+ placeholder="e.g., A multi-user collaborative drawing board built with React and Firestore for real-time art sessions.",
144
+ key="desc"
145
+ )
146
+ code_text = st.text_area(
147
+ "πŸ’» Demo Code Snippet (Key files or core logic) [Required]",
148
+ height=300,
149
+ placeholder="Paste a relevant code snippet here (e.g., the main logic or data handling files).",
150
+ key="code"
151
+ )
152
+ with col2:
153
+
154
+ #st.sidebar.markdown("Edit the criteria and ensure the **Total Weight sums to 100%**.")
155
+ st.markdown("βš–οΈ Define Judging Criteria & Weights")
156
+
157
+ edited_criteria = st.data_editor(
158
+ #"βš–οΈ Define Judging Criteria & Weights",
159
+ DEFAULT_CRITERIA,
160
+ column_config={
161
+ "Criterion": st.column_config.TextColumn("Criterion Name", required=True),
162
+ "Weight (%)": st.column_config.NumberColumn("Weight (%)", min_value=1, max_value=100, required=True),
163
+ },
164
+ #disabled=["Criterion"],
165
+ num_rows="dynamic",
166
+ hide_index=True,
167
+ key="criteria_editor"
168
+ )
169
+ pdf_file = st.file_uploader(
170
+ "πŸ“„ Upload Technical Report (PDF or Text File) [Required]",
171
+ type=['pdf', 'txt'],
172
+ key="pdf_upload"
173
+ )
174
+ demo_video = st.file_uploader(
175
+ "🎬 Upload Demo Video (MP4 only) [Optional but recommended]",
176
+ type=['mp4'],
177
+ key="demo_video"
178
+ )
179
+
180
+ judge_button = st.button("βš–οΈ Generate Judge's Score & Report", type="primary")
181
+
182
+ # --------- Gemini YouTube Summary Handling ---------
183
+
184
 
185
+
186
+ if judge_button and description and code_text and pdf_file and demo_video:
187
+
188
+
189
+ # video_file_path = demo_video.path
190
+ with st.spinner("Generating demo video summary..."):
191
+
192
+ video_mime_type = "video/mp4"
193
+ # with open(video_file_path, "rb") as video_file:
194
+ encoded_video = base64.b64encode(demo_video.read()).decode('utf-8')
195
+
196
+ message = HumanMessage(
197
+ content=[
198
+ {"type": "text", "text": "Describe what's happening in this video."},
199
+ {"type": "media", "data": encoded_video, "mime_type": video_mime_type}
200
+ ]
201
+ )
202
+ video_response = llm.invoke([message])
203
+
204
+
205
+
206
+
207
+ # 1. Extract PDF or text content
208
+ pdf_text_content = ""
209
+ if pdf_file.name.endswith(".pdf"):
210
+ pdf_reader = PdfReader(pdf_file)
211
+ for page in pdf_reader.pages:
212
+ page_text = page.extract_text()
213
+ if page_text:
214
+ pdf_text_content += page_text
215
+ else:
216
+ # it's a .txt file
217
+ pdf_text_content = pdf_file.read().decode("utf-8")
218
+ if not pdf_text_content.strip():
219
+ st.warning("The uploaded document appears to be empty or unreadable.")
220
+ pdf_text_content = "The uploaded document was empty or contained no readable text."
221
+
222
+ # 2. Handle YouTube summary or mark blank
223
+ presentation_summary = ""
224
+ presentation_summary = video_response.text()
225
+
226
+ # 3. Check criteria weights
227
+ total_weight = sum(item["Weight (%)"] for item in edited_criteria)
228
+ if total_weight != 100:
229
+ st.error(f"Error: The total weight of all criteria must sum up to 100%. Current sum: {total_weight}%.")
230
+ st.stop()
231
+
232
+ dynamic_criteria = {
233
+ item["Criterion"]: item["Weight (%)"] / 100.0
234
+ for item in edited_criteria
235
+ }
236
+ criteria_markdown = "\n".join(
237
+ [f"- {k}: {v*100:.0f}%" for k, v in dynamic_criteria.items()]
238
+ )
239
+
240
+ category_scores_prompt = ""
241
+ for criterion, weight in dynamic_criteria.items():
242
+ category_scores_prompt += f"""
243
+ ### {criterion} (Weight: {weight*100:.0f}%)
244
+ **Score:** [0-100]/100
245
+ **Justification:** [Your analysis here]
246
  """
247
 
248
+ final_judge_system_prompt = GENERIC_JUDGE_SYSTEM_PROMPT.format(
249
+ criteria_list=criteria_markdown,
250
+ category_scores=category_scores_prompt.strip()
251
+ )
252
+
253
+ # Create judge chain dynamically
254
+ dynamic_judge_prompt = ChatPromptTemplate.from_messages(
255
+ [
256
+ ("system", final_judge_system_prompt),
257
+ ("user", JUDGE_USER_PROMPT)
258
+ ]
259
+ )
260
+ judge_chain = dynamic_judge_prompt | llm | output_parser
261
+
262
+ # 4. Summarization stage
263
+ with st.spinner("Stage 1: Running Summarization Chain (Analyzing PDF and Video summary)..."):
264
+ try:
265
+ summary_inputs = {
266
+ 'pdf_text_content': pdf_text_content,
267
+ 'presentation_summary': presentation_summary,
268
+ 'pdf_length': len(pdf_text_content),
269
+ 'presentation_length': len(presentation_summary)
270
+ }
271
+ response = summary_chain.invoke(summary_inputs)
272
+ file_summaries = response.content if hasattr(response, "content") else str(response)
273
+
274
+ st.markdown("---")
275
+ st.subheader("βœ… Summarization Chain Output ")
276
+ st.code(file_summaries, language='markdown')
277
+ st.markdown("---")
278
+ except Exception as e:
279
+ st.error(f"An error occurred during the Summarization Chain: {e}")
280
+ st.stop()
281
+
282
+ # 5. Judging stage
283
+ with st.spinner("Stage 2: Running Judge Chain (Scoring Project)..."):
284
+ try:
285
+ judge_inputs = {
286
+ 'description': description,
287
+ 'file_summaries': file_summaries,
288
+ 'code_text': code_text
289
+ }
290
+ judging_report = judge_chain.invoke(judge_inputs)
291
+ st.header("Judge's Official Report")
292
+ st.markdown(judging_report)
293
+ except Exception as e:
294
+ st.error(f"An error occurred during the Judging Chain: {e}")
295
+
296
+ elif judge_button:
297
+ st.error("Please fill in the Project Description, Code Snippet, upload a Technical Report, and ensure your criteria weights sum up to 100% in the sidebar.")