HMZaheer commited on
Commit
c3b4b68
·
verified ·
1 Parent(s): 1caca13

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -55
app.py CHANGED
@@ -1,69 +1,73 @@
1
  import streamlit as st
2
- import numpy as np
3
- import cv2
4
  import matplotlib.pyplot as plt
 
 
5
  from PIL import Image
6
- from pdf2image import convert_from_bytes
7
  import io
8
 
9
- st.title("📉 TGA Graph Interpreter")
10
- st.write("Upload a TGA plot (JPG, PNG, GIF, PDF) to extract key thermal analysis values.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
- # ---- File Upload ----
13
- uploaded_file = st.file_uploader("Upload TGA Graph", type=["jpg", "jpeg", "png", "gif", "pdf"])
 
14
 
15
  if uploaded_file:
16
- # Handle PDF separately (convert to image)
17
- if uploaded_file.type == "application/pdf":
18
- images = convert_from_bytes(uploaded_file.read())
19
- img = np.array(images[0]) # Take first page
20
- img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
 
 
 
 
 
 
 
 
21
  else:
22
- file_bytes = np.asarray(bytearray(uploaded_file.read()), dtype=np.uint8)
23
- img = cv2.imdecode(file_bytes, 1)
24
-
25
- st.image(img, caption="Uploaded TGA Plot", use_column_width=True)
26
-
27
- # ---- Image Processing (basic curve extraction) ----
28
- gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
29
- blur = cv2.GaussianBlur(gray, (5, 5), 0)
30
- edges = cv2.Canny(blur, 50, 150)
31
-
32
- # Find contours (assume largest is the TGA curve)
33
- contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
34
- if contours:
35
- largest_contour = max(contours, key=cv2.contourArea)
36
- curve = largest_contour.squeeze()
37
-
38
- if curve.ndim == 2:
39
- x_vals = curve[:, 0]
40
- y_vals = curve[:, 1]
41
-
42
- # Normalize (assume X = Temp, Y = Weight%)
43
- x_norm = np.interp(x_vals, (x_vals.min(), x_vals.max()), (25, 800)) # °C
44
- y_norm = np.interp(y_vals, (y_vals.min(), y_vals.max()), (100, 0)) # %
45
-
46
- # Key points
47
- onset_temp = x_norm[np.argmax(np.gradient(y_norm) < -0.1)]
48
- peak_degradation = x_norm[np.argmin(np.gradient(y_norm))]
49
- weight_loss = y_norm[0] - y_norm[-1]
50
-
51
- # ---- Show Results ----
52
- st.subheader("🔑 Extracted Values")
53
- st.write(f"**Onset Temperature:** {onset_temp:.1f} °C")
54
- st.write(f"**Peak Degradation Temp:** {peak_degradation:.1f} °C")
55
- st.write(f"**Total Weight Loss:** {weight_loss:.1f} %")
56
-
57
- # ---- Plot Curve ----
58
  fig, ax = plt.subplots()
59
- ax.plot(x_norm, y_norm, label="TGA Curve", color="blue")
60
- ax.axvline(onset_temp, color="green", linestyle="--", label="Onset")
61
- ax.axvline(peak_degradation, color="red", linestyle="--", label="Peak Degradation")
62
  ax.set_xlabel("Temperature (°C)")
63
  ax.set_ylabel("Weight (%)")
64
  ax.legend()
65
  st.pyplot(fig)
66
- else:
67
- st.error("Curve extraction failed. Try uploading a clearer TGA image.")
68
- else:
69
- st.error("No TGA curve detected. Please try another image.")
 
1
  import streamlit as st
 
 
2
  import matplotlib.pyplot as plt
3
+ import numpy as np
4
+ from plotdigitizer import digitizer
5
  from PIL import Image
 
6
  import io
7
 
8
+ # Utility functions
9
+ def analyze_curve(x, y):
10
+ """Analyze onset, peak degradation, weight loss for a single thermogram"""
11
+ x, y = np.array(x), np.array(y)
12
+
13
+ # Normalize weight % if needed
14
+ if y.max() > 100:
15
+ y = 100 * y / y[0]
16
+
17
+ # Onset = first big drop
18
+ dy = np.gradient(y, x)
19
+ onset_idx = np.argmax(dy < -0.05)
20
+ onset_temp = x[onset_idx] if onset_idx > 0 else None
21
+
22
+ # Peak degradation = minimum derivative
23
+ peak_idx = np.argmin(dy)
24
+ peak_temp = x[peak_idx] if peak_idx > 0 else None
25
+
26
+ # Weight loss
27
+ weight_loss = y[0] - y[-1]
28
+
29
+ return onset_temp, peak_temp, weight_loss
30
+
31
+
32
+ st.title("TGA Graph Interpreter (Multi-Curve Support)")
33
 
34
+ uploaded_file = st.file_uploader(
35
+ "Upload a TGA plot (PNG, JPG, PDF)", type=["png", "jpg", "jpeg", "pdf"]
36
+ )
37
 
38
  if uploaded_file:
39
+ # Read image
40
+ img = Image.open(uploaded_file)
41
+ st.image(img, caption="Uploaded TGA Graph", use_column_width=True)
42
+
43
+ # Use plotdigitizer to extract data
44
+ st.info("Extracting curves... please wait")
45
+ with io.BytesIO() as buf:
46
+ img.save(buf, format="PNG")
47
+ buf.seek(0)
48
+ curves = digitizer.extract(buf)
49
+
50
+ if not curves:
51
+ st.error("No curves detected. Try uploading a clearer plot.")
52
  else:
53
+ st.success(f"{len(curves)} curves detected!")
54
+
55
+ for i, curve in enumerate(curves):
56
+ x, y = curve["x"], curve["y"]
57
+ label = curve.get("label", f"Curve {i+1}")
58
+
59
+ onset, peak, loss = analyze_curve(x, y)
60
+
61
+ st.subheader(f"Results for {label}")
62
+ st.write(f"- **Onset Temperature:** {onset:.2f} °C" if onset else "Not detected")
63
+ st.write(f"- **Peak Degradation Temperature:** {peak:.2f} °C" if peak else "Not detected")
64
+ st.write(f"- **Weight Loss:** {loss:.2f} %")
65
+
66
+ # Plot each curve
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  fig, ax = plt.subplots()
68
+ ax.plot(x, y, label=label)
 
 
69
  ax.set_xlabel("Temperature (°C)")
70
  ax.set_ylabel("Weight (%)")
71
  ax.legend()
72
  st.pyplot(fig)
73
+