Sobit's picture
Upload app.py
f37161d verified
import streamlit as st
import tensorflow as tf
from tensorflow import keras
from keras import models
from PIL import Image
import numpy as np
import cv2
import io
# Some constants to be used in the program
IMG_SIZE = (32,32)
# Character mapping for the character prediction
char_map = {
0:'๐‘‘(0)', 1:'๐‘‘‘(1)', 2:'๐‘‘’(2)', 3:'๐‘‘“(3)', 4: '๐‘‘”(4)', 5: '๐‘‘•(5)', 6: '๐‘‘–(6)', 7: '๐‘‘—(7)',
8:'๐‘‘˜(8)', 9:'๐‘‘™(9)', 10:'๐‘‘‰(OM)', 11:'๐‘€(A)', 12: '๐‘(AA)', 13: '๐‘€๐‘‘…(AH)', 14: '๐‘‚(I)',
15:'๐‘ƒ(II)',16:'๐‘„(U)', 17:'๐‘…(UU)', 18:'๐‘†(R)', 19: '๐‘†๐‘บ(RR)', 20: '๐‘Š(E)', 21: '๐‘‹(AI)', 22: '๐‘Œ(O)',
23:'๐‘(AU)', 24:'๐‘ˆ(L)', 25:'๐‘‰(LL)', 26:'๐‘Ž(KA)', 27: '๐‘Ž๐‘‘‚๐‘ณ(KSA)', 28: '๐‘(KHA)',29: '๐‘(GA)', 30: '๐‘‘(GHA)',
31:'๐‘’(NGA)',32:'๐‘”(CA)', 33:'๐‘•(CHA)', 34:'๐‘–(JA)', 35: '๐‘–๐‘‘‚๐‘˜(JรฑA)', 36: '๐‘—(JHA)',37: '๐‘—(JHA-alt)',38: '๐‘˜(NYA)',
39:'๐‘š(TA)', 40:'๐‘›(TTHA)', 41:'๐‘œ(DDA)', 42:'๐‘(DHA)', 43: '๐‘ž(NNA)', 44: '๐‘Ÿ(TA)', 45: '๐‘Ÿ๐‘‘‚๐‘ฌ(TRA)', 46: '๐‘ (THA)',
47:'๐‘ก(DA)', 49:'๐‘ฃ(NA)', 50:'๐‘ฅ(PA)', 51:'๐‘ฆ(PHA)', 52: '๐‘ง(BA)', 53: '๐‘จ(BHA)', 54: '๐‘ฉ(MA)', 55: '๐‘ซ(YA)',
56:'๐‘ฌ(RA)', 57: '๐‘ฎ(LA)', 58:'๐‘ฐ(WA)', 59:'๐‘ฑ(SHA)', 60: '๐‘ฑ(SHA-alt)', 61: '๐‘ฒ(SSA)', 62: '๐‘ณ(SA)', 63: '๐‘ด(HA)'
}
# Importing the model
model = models.load_model('tf_model.h5')
def preprocess_image(image):
# Resize the image
image = cv2.resize(image, IMG_SIZE)
# Check if the image is grayscale
if len(image.shape) == 2:
# Convert grayscale image to RGB
image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)
elif image.shape[2] == 4:
# Convert RGBA image to RGB
image = cv2.cvtColor(image, cv2.COLOR_RGBA2RGB)
elif image.shape[2] > 3:
# Extract only the first 3 channels (assuming RGB or BGR format)
image = image[:, :, :3]
# Convert the image to float32 and normalize
image = image.astype('float32') / 255.0
# Add an extra dimension to simulate batch size of 1
image = np.expand_dims(image, axis=0)
return image
def main():
st.title("Character Recognition")
st.write("Upload an image and the model will predict the character")
uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
if uploaded_file is not None:
image = Image.open(uploaded_file)
st.image(image, caption='Uploaded Image.', use_column_width=True)
if st.button('Predict'):
image = np.array(image)
image = preprocess_image(image)
output = model.predict(image)
result = char_map[np.argmax(output)]
st.success(f'Prediction: {result}')
if __name__ == "__main__":
main()