|
import os |
|
import streamlit as st |
|
from PIL import Image |
|
|
|
from paddleocr import PaddleOCR, draw_ocr |
|
from langchain.chains import LLMChain |
|
from langchain.prompts import PromptTemplate |
|
from langchain_groq import ChatGroq |
|
import numpy as np |
|
|
|
|
|
|
|
|
|
|
|
GROQ_API_KEY = os.environ['GROQ_API_KEY '] |
|
|
|
llm = ChatGroq(temperature=0, groq_api_key=GROQ_API_KEY, model_name="llama3-groq-70b-8192-tool-use-preview") |
|
|
|
ocr = PaddleOCR(use_angle_cls=True, lang='en') |
|
|
|
def extract_text_from_image(image): |
|
try: |
|
|
|
image_np = np.array(image) |
|
|
|
|
|
results = ocr.ocr(image_np, cls=True) |
|
|
|
|
|
extracted_text = "" |
|
for line in results: |
|
for word_info in line: |
|
extracted_text += word_info[1][0] + " " |
|
|
|
return extracted_text.strip() if extracted_text else "No text found in the image." |
|
|
|
except Exception as e: |
|
return f"Error processing image: {e}" |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def solve_math_problem_with_groq(problem_text): |
|
try: |
|
|
|
|
|
|
|
prompt_template = PromptTemplate( |
|
input_variables=["problem"], |
|
template="Solve the following math problem:\n\n{problem}\n\n" |
|
) |
|
|
|
|
|
llm_chain = LLMChain( |
|
llm=llm, |
|
prompt=prompt_template |
|
) |
|
|
|
|
|
solution = llm_chain.run(problem=problem_text) |
|
return solution.strip() |
|
except Exception as e: |
|
return f"Error solving the problem: {e}" |
|
|
|
|
|
def main(): |
|
st.title("Math Solver using ChatGroq, Mistral, and LangChain") |
|
st.write('Developed by Ravi Shankar Prasad- https://www.linkedin.com/in/ravi-shankar-prasad-371825101/') |
|
|
|
|
|
input_method = st.radio("Select input method:", ("Upload Image", "Enter Text")) |
|
|
|
problem_text = "" |
|
|
|
if input_method == "Upload Image": |
|
|
|
uploaded_file = st.file_uploader("Choose an image...", type=["png", "jpg", "jpeg"]) |
|
if uploaded_file is not None: |
|
|
|
image = Image.open(uploaded_file) |
|
st.image(image, caption='Uploaded Image', use_column_width=True) |
|
|
|
problem_text = extract_text_from_image(image) |
|
if problem_text: |
|
st.write("Extracted Text:", problem_text) |
|
else: |
|
st.write("No text found in the image. Please upload a clearer image.") |
|
else: |
|
|
|
problem_text = st.text_area("Enter math problem:") |
|
|
|
if problem_text: |
|
if st.button("Solve"): |
|
|
|
solution = solve_math_problem_with_groq(problem_text) |
|
st.write("Solution:", solution) |
|
|
|
if __name__ == "__main__": |
|
main() |
|
|