Spaces:
Sleeping
Sleeping
File size: 14,794 Bytes
cca443a d4a980d cca443a 52de3c1 91a5497 cca443a 91a5497 cca443a d4a980d cca443a 91a5497 cca443a 91a5497 cca443a d4a980d cca443a d4a980d cca443a d4a980d cca443a d4a980d cca443a d4a980d cca443a 91a5497 cca443a 91a5497 cca443a 91a5497 cca443a d4a980d cca443a 6e63545 cca443a 91a5497 cca443a 91a5497 cca443a 91a5497 cca443a 91a5497 cca443a 91a5497 cca443a 91a5497 cca443a 90685aa cca443a 91a5497 cca443a d4a980d cca443a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 |
import os
import streamlit as st
from openai import OpenAI
import base64
import json
import requests
import re
import pandas as pd
from huggingface_hub import InferenceClient
HF_MODEL_MISTRAL = "mistralai/Mistral-7B-Instruct-v0.3"
HF_MODEL_LLAMA = "meta-llama/Llama-3.3-70B-Instruct"
HF_MODEL_DEEPSEEK = "deepseek-ai/DeepSeek-R1-Distill-Llama-8B"
UML_PROMPTS_DOC_URL = os.environ['UML_PROMPTS_DOC_URL']
ERD_PROMPTS_DOC_URL = os.environ['ERD_PROMPTS_DOC_URL']
STEP1_SYSTEM_PROMPT = "STEP1 SYSPROMPT"
STEP1_USER_PROMPT = "STEP1 USERPROMPT"
STEP2_SYSTEM_PROMPT = "STEP2 SYSPROMPT"
STEP2_USER_PROMPT = "STEP2 USERPROMPT"
STEP3A_SYSTEM_PROMPT = "STEP3A SYSPROMPT"
STEP3A_USER_PROMPT = "STEP3A USERPROMPT"
STEP3B_SYSTEM_PROMPT = "STEP3B SYSPROMPT"
STEP3B_USER_PROMPT = "STEP3B USERPROMPT"
def fetch_prompts_from_google_doc(diagram_type="UML"):
if diagram_type == "UML":
response = requests.get(UML_PROMPTS_DOC_URL)
elif diagram_type == "ERD":
response = requests.get(ERD_PROMPTS_DOC_URL)
if response.status_code != 200:
raise Exception("Failed to fetch document")
text = response.text
prompts = {}
pattern = r"\{BEGIN (.*?)\}([\s\S]*?)\{END \1\}"
matches = re.findall(pattern, text)
for key, content in matches:
prompts[key.strip()] = content.strip()
return prompts
# Step 1: Extract PlantUML Code
def extract_plantuml_code(client_openai, uploaded_file, model_choice, prompts):
st.write("Model: ", model_choice)
encoded_image = base64.b64encode(uploaded_file.getvalue()).decode("utf-8")
response = client_openai.chat.completions.create(
model=model_choice,
messages=[
{
"role": "system",
"content": prompts[STEP1_SYSTEM_PROMPT],
},
{
"role": "user",
"content": [
{"type": "text", "text": prompts[STEP1_USER_PROMPT]},
{
"type": "image_url",
"image_url": {"url": f"data:image/png;base64,{encoded_image}"},
},
],
},
],
temperature=0.2,
top_p=0.1,
max_tokens=4096,
)
return response.choices[0].message.content
# Step 2: Compare PlantUML Code
def compare_plantuml(client_openai, client_hf_mistral, client_hf_llama, client_hf_deepseek, plantuml_instructor, plantuml_student, model_choice, prompts, diagram_type="UML"):
st.write("Model: ", model_choice)
user_prompt=f"""
{prompts[STEP2_USER_PROMPT]}
**Instructor's {diagram_type} Diagram:**
{plantuml_instructor}
**Student's {diagram_type} Diagram:**
{plantuml_student}
"""
if model_choice in [HF_MODEL_MISTRAL]:
response = client_hf_mistral.chat_completion(
[
{
"role": "system",
"content": prompts[STEP2_SYSTEM_PROMPT],
},
{"role": "user", "content": user_prompt},
],
max_tokens=1024,
temperature=0.2,
)
return response["choices"][0]["message"]["content"]
elif model_choice in [HF_MODEL_LLAMA]:
response = client_hf_llama.chat_completion(
[
{
"role": "system",
"content": prompts[STEP2_SYSTEM_PROMPT],
},
{"role": "user", "content": user_prompt},
],
max_tokens=1024,
temperature=0.2,
)
return response["choices"][0]["message"]["content"]
elif model_choice in [HF_MODEL_DEEPSEEK]:
response = client_hf_deepseek.chat_completion(
[
{
"role": "system",
"content": prompts[STEP2_SYSTEM_PROMPT],
},
{"role": "user", "content": user_prompt},
],
max_tokens=1024,
temperature=0.2,
)
return response["choices"][0]["message"]["content"]
else:
response = client_openai.chat.completions.create(
model=model_choice,
messages=[
{
"role": "system",
"content": prompts[STEP2_SYSTEM_PROMPT],
},
{
"role": "user",
"content": user_prompt,
},
],
temperature=0.2,
top_p=0.1,
max_tokens=4096,
)
return response.choices[0].message.content
# Step 3A: Generate Student Feedback
def generate_student_feedback(client_openai, client_hf_mistral, client_hf_llama, client_hf_deepseek, differences, model_choice, prompts):
st.write("Model (Student Feedback):", model_choice)
user_prompt=f"""
{prompts[STEP3A_USER_PROMPT]}
{json.dumps(differences, indent=2)}
"""
if model_choice in [HF_MODEL_MISTRAL]:
response = client_hf_mistral.chat_completion(
[
{
"role": "system",
"content": prompts[STEP3A_SYSTEM_PROMPT],
},
{"role": "user", "content": user_prompt},
],
max_tokens=1024,
temperature=0.2,
)
return response["choices"][0]["message"]["content"]
elif model_choice in [HF_MODEL_LLAMA]:
response = client_hf_llama.chat_completion(
[
{
"role": "system",
"content": prompts[STEP3A_SYSTEM_PROMPT],
},
{"role": "user", "content": user_prompt},
],
max_tokens=1024,
temperature=0.2,
)
return response["choices"][0]["message"]["content"]
elif model_choice in [HF_MODEL_DEEPSEEK]:
response = client_hf_deepseek.chat_completion(
[
{
"role": "system",
"content": prompts[STEP2_SYSTEM_PROMPT],
},
{"role": "user", "content": user_prompt},
],
max_tokens=1024,
temperature=0.2,
)
return response["choices"][0]["message"]["content"]
else:
response = client_openai.chat.completions.create(
model=model_choice,
messages=[
{
"role": "system",
"content": prompts[STEP3A_SYSTEM_PROMPT],
},
{
"role": "user",
"content": user_prompt,
},
],
temperature=0.2,
top_p=0.1,
max_tokens=4096,
)
return response.choices[0].message.content
# Step 3B: Generate Educator Feedback
def generate_educator_feedback(client_openai, client_hf_mistral, client_hf_llama, client_hf_deepseek, differences, model_choice, prompts):
st.write("Model (Educator Feedback): ", model_choice)
user_prompt=f"""
{prompts[STEP3B_USER_PROMPT]}
{json.dumps(differences, indent=2)}
"""
if model_choice in [HF_MODEL_MISTRAL]:
response = client_hf_mistral.chat_completion(
[
{
"role": "system",
"content": prompts[STEP3B_SYSTEM_PROMPT],
},
{"role": "user", "content": user_prompt},
],
max_tokens=1024,
temperature=0.2,
)
return response["choices"][0]["message"]["content"]
elif model_choice in [HF_MODEL_LLAMA]:
response = client_hf_llama.chat_completion(
[
{
"role": "system",
"content": prompts[STEP3B_SYSTEM_PROMPT],
},
{"role": "user", "content": user_prompt},
],
max_tokens=1024,
temperature=0.2,
)
return response["choices"][0]["message"]["content"]
elif model_choice in [HF_MODEL_DEEPSEEK]:
response = client_hf_deepseek.chat_completion(
[
{
"role": "system",
"content": prompts[STEP2_SYSTEM_PROMPT],
},
{"role": "user", "content": user_prompt},
],
max_tokens=1024,
temperature=0.2,
)
return response["choices"][0]["message"]["content"]
else:
response = client_openai.chat.completions.create(
model=model_choice,
messages=[
{
"role": "system",
"content": prompts[STEP3B_SYSTEM_PROMPT],
},
{
"role": "user",
"content": user_prompt,
},
],
temperature=0.2,
top_p=0.1,
max_tokens=4096,
)
return response.choices[0].message.content
# Streamlit app layout
st.set_page_config(
page_title="LLM-based Analysis and Feedback of a UML or ER Diagram",
page_icon="π",
initial_sidebar_state="expanded",
)
st.title("LLM-based Analysis and Feedback of a UML or ERD Diagram")
st.write("The pipeline consists of three steps:")
st.write("1. Extract PlantUML code from the uploaded UML or ER diagrams using GPT-4o or GPT-4o Mini.")
st.write("2. Compare the extracted PlantUML code.")
st.write("3. Analyse the differences and present them in a structured format.")
diagram_type = st.selectbox("Select the diagram type", ["UML", "ERD"])
prompts = fetch_prompts_from_google_doc(diagram_type)
openai_api_key = st.text_input("OpenAI API key", type="password")
hf_api_key = st.text_input("Hugging Face API key", type="password")
if openai_api_key and hf_api_key:
client_openai = OpenAI(api_key=openai_api_key)
client_hf_mistral = InferenceClient(model=HF_MODEL_MISTRAL, token=hf_api_key)
client_hf_llama = InferenceClient(model=HF_MODEL_LLAMA, token=hf_api_key)
client_hf_deepseek = InferenceClient(model=HF_MODEL_DEEPSEEK, token=hf_api_key)
model_choice_step1 = st.selectbox("Select the model for Step 1", ["gpt-4o", "gpt-4o-mini"])
model_choice_step2 = st.selectbox("Select the model for Step 2", [HF_MODEL_MISTRAL, HF_MODEL_LLAMA, "gpt-4o", "gpt-4o-mini"])
model_choice_step3 = st.selectbox("Select the model for Step 3", [HF_MODEL_MISTRAL, HF_MODEL_LLAMA, "gpt-4o", "gpt-4o-mini"])
st.subheader("Step 1: PlantUML Code Extraction using GPT-4o or GPT-4o Mini")
col1, col2 = st.columns(2)
with col1:
uploaded_instructor_solution = st.file_uploader(
"Upload Instructor " + ("UML" if diagram_type == 'UML' else "ER") + " Diagram", type=["jpg", "jpeg", "png"]
)
with col2:
uploaded_student_solution = st.file_uploader(
"Upload Student " + ("UML" if diagram_type == 'UML' else "ER") + " Diagram", type=["jpg", "jpeg", "png"]
)
if (uploaded_instructor_solution is not None and uploaded_student_solution is not None):
try:
with st.spinner(
"Extracting PlantUML code from the uploaded " + ("UML" if diagram_type == 'UML' else "ER") + " diagrams..."
):
with col1:
st.image(
uploaded_instructor_solution,
caption="Uploaded Instructor " + ("UML" if diagram_type == 'UML' else "ER") + " Diagram",
use_container_width=True,
)
st.write("")
plantuml_instructor_solution = extract_plantuml_code(
client_openai, uploaded_instructor_solution, model_choice_step1, prompts
)
with col2:
st.write("")
st.image(
uploaded_student_solution,
caption="Uploaded Student " + ("UML" if diagram_type == 'UML' else "ER") + " Diagram",
use_container_width=True,
)
st.write("")
plantuml_student_solution = extract_plantuml_code(
client_openai, uploaded_student_solution, model_choice_step1, prompts
)
st.write("Extracted PlantUML Code")
col1, col2 = st.columns(2)
with col1:
st.text_area(
"PlantUML Code for Instructor Solution",
plantuml_instructor_solution,
height=600,
)
with col2:
st.text_area(
"PlantUML Code for Student Solution",
plantuml_student_solution,
height=600,
)
st.subheader("Step 2: " + ("UML" if diagram_type == 'UML' else "ER") + " Diagram Comparison")
with st.spinner("Comparing instructor and student " + ("UML" if diagram_type == 'UML' else "ER") + " diagrams..."):
differences = compare_plantuml(
client_openai,
client_hf_mistral,
client_hf_llama,
client_hf_deepseek,
plantuml_instructor_solution,
plantuml_student_solution,
model_choice_step2,
prompts,
diagram_type
)
with st.expander("View differences"):
for difference in differences.split("\n"):
st.write(difference)
st.subheader("Step 3: Structured Feedback")
with st.spinner("Preparing structured feedback..."):
student_feedback = generate_student_feedback(client_openai, client_hf_mistral, client_hf_llama, client_hf_deepseek, differences, model_choice_step3, prompts)
educator_feedback = generate_educator_feedback(client_openai, client_hf_mistral, client_hf_llama, client_hf_deepseek, differences, model_choice_step3, prompts)
col1, col2 = st.columns(2)
with col1:
st.write("Student Feedback")
st.markdown(f"{student_feedback}")
with col2:
st.write("Educator Feedback")
st.markdown(f"{educator_feedback}")
except Exception as e:
st.error(f"Error: {e}")
else:
if not openai_api_key:
st.error("Please provide a valid OpenAI API key.")
else:
st.error("Please provide a valid Hugging Face API key.")
|