kemalserkany commited on
Commit
eb6aa3b
·
verified ·
1 Parent(s): 722aeab

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +78 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,80 @@
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
+ """Fish Species Classification — Transfer Learning (standalone Streamlit app)."""
2
+
3
+ import sys
4
+ from pathlib import Path
5
+
6
  import streamlit as st
7
 
8
+ if "/opt/anaconda3" in sys.executable:
9
+ st.set_page_config(page_title="Python ortam hatasi", page_icon="⚠️")
10
+ st.error(
11
+ "Bu uygulama Anaconda Python ile calismaz (segmentation fault).\n\n"
12
+ "Asagidaki komutu kullanin:\n\n"
13
+ f"```bash\ncd \"{Path(__file__).resolve().parent}\"\n"
14
+ "~/venvs/tensorflow/bin/streamlit run "
15
+ f"{Path(__file__).name}\n```"
16
+ )
17
+ st.stop()
18
+
19
+ import json
20
+
21
+ import numpy as np
22
+ import tensorflow as tf
23
+ from PIL import Image
24
+
25
+ ROOT = Path(__file__).resolve().parent
26
+
27
+ MODEL_PATH = Path('src/fish_cnn.h5')
28
+ META_PATH = Path('src/fish_cnn_meta.json')
29
+
30
+ def get_preprocess(backbone):
31
+ if backbone == "VGG16":
32
+ from tensorflow.keras.applications.vgg16 import preprocess_input
33
+ return preprocess_input
34
+ if backbone == "ResNet50":
35
+ from tensorflow.keras.applications.resnet50 import preprocess_input
36
+ return preprocess_input
37
+ from tensorflow.keras.applications.xception import preprocess_input
38
+ return preprocess_input
39
+
40
+ @st.cache_resource
41
+ def load_model():
42
+ if not MODEL_PATH.is_file():
43
+ raise FileNotFoundError(f"Model not found: {MODEL_PATH}. Run fish_TL.ipynb first.")
44
+ return tf.keras.models.load_model(MODEL_PATH)
45
+
46
+
47
+ def load_meta():
48
+ return json.loads(META_PATH.read_text(encoding="utf-8"))
49
+
50
+
51
+ def prepare_image(img, meta):
52
+ size = tuple(meta["img_size"])
53
+ arr = np.array(img.convert("RGB").resize(size), dtype=np.float32)
54
+ arr = np.expand_dims(arr, axis=0)
55
+ preprocess = get_preprocess(meta.get('backbone', 'VGG16'))
56
+ arr = preprocess(arr)
57
+ return arr
58
+
59
+
60
+ st.set_page_config(page_title="Fish Species Classification", page_icon="🧠")
61
+ st.title("Fish Species Classification")
62
+ st.caption("Transfer Learning — train with `fish_TL.ipynb`")
63
+
64
+ try:
65
+ model = load_model()
66
+ meta = load_meta()
67
+ except FileNotFoundError as e:
68
+ st.error(str(e))
69
+ st.stop()
70
+
71
+ uploaded = st.file_uploader("Upload image (jpg/png)", type=["jpg", "jpeg", "png"])
72
+ if uploaded:
73
+ img = Image.open(uploaded)
74
+ st.image(img, use_container_width=True)
75
+ batch = prepare_image(img, meta)
76
+ probs = model.predict(batch, verbose=0)[0]
77
+ idx = int(np.argmax(probs))
78
+ label = meta["class_names"][idx]
79
+ st.success(f"Prediction: **{label}**")
80
+ st.write(f"Confidence: {probs[idx]:.2%}")