Dua Rajper commited on
Commit
f3a781a
·
verified ·
1 Parent(s): ccc1049

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -0
app.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from transformers import pipeline, AutoTokenizer, AutoModelForQuestionAnswering
3
+ from PIL import Image
4
+ import easyocr
5
+ import os
6
+ from groq import Groq, APIConnectionError, AuthenticationError
7
+
8
+ # OCR Function
9
+ def extract_text_from_image(image):
10
+ reader = easyocr.Reader(['en'])
11
+ result = reader.readtext(image)
12
+ extracted_text = " ".join([detection[1] for detection in result])
13
+ return extracted_text
14
+
15
+ # Question Answering Function (DistilBERT)
16
+ @st.cache_resource
17
+ def load_qa_model():
18
+ model_name = "distilbert/distilbert-base-cased-distilled-squad"
19
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
20
+ model = AutoModelForQuestionAnswering.from_pretrained(model_name)
21
+ nlp = pipeline('question-answering', model=model, tokenizer=tokenizer)
22
+ return nlp
23
+
24
+ def answer_question(context, question, qa_model):
25
+ result = qa_model({'question': question, 'context': context})
26
+ return result['answer']
27
+
28
+ # Groq API Function
29
+ def groq_chat(prompt):
30
+ try:
31
+ client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
32
+ chat_completion = client.chat.completions.create(
33
+ messages=[{"role": "user", "content": prompt}],
34
+ model="llama-3.3-70b-versatile",
35
+ )
36
+ return chat_completion.choices[0].message.content
37
+ except APIConnectionError as e:
38
+ return f"Groq API Connection Error: {e}"
39
+ except AuthenticationError as e:
40
+ return f"Groq API Authentication Error: {e}"
41
+ except Exception as e:
42
+ return f"General Groq API Error: {e}"
43
+
44
+ # Streamlit App
45
+ def main():
46
+ st.title("Image Text & Question Answering Chatbot")
47
+ uploaded_file = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
48
+
49
+ if uploaded_file is not None:
50
+ image = Image.open(uploaded_file)
51
+ st.image(image, caption="Uploaded Image", use_container_width=True)
52
+
53
+ if st.button("Extract Text and Enable Question Answering"):
54
+ with st.spinner("Extracting text..."):
55
+ extracted_text = extract_text_from_image(image)
56
+ st.session_state.extracted_text = extracted_text # Store in session state
57
+ st.write("Extracted Text:")
58
+ st.write(st.session_state.extracted_text)
59
+
60
+ if "extracted_text" in st.session_state: # Check if extracted_text is in session state
61
+ qa_model = load_qa_model()
62
+ question = st.text_input("Ask a question about the image text:")
63
+ if st.button("Answer"):
64
+ if question:
65
+ with st.spinner("Answering..."):
66
+ answer = answer_question(st.session_state.extracted_text, question, qa_model)
67
+ st.write("Answer:", answer)
68
+ else:
69
+ st.warning("Please enter a question.")
70
+
71
+ # Groq Chat Section
72
+ st.subheader("General Chat (Powered by Groq)")
73
+ groq_prompt = st.text_input("Enter your message:")
74
+ if st.button("Send"):
75
+ if groq_prompt:
76
+ with st.spinner("Generating response..."):
77
+ groq_response = groq_chat(groq_prompt)
78
+ st.write("Response:", groq_response)
79
+ else:
80
+ st.warning("Please enter a message.")
81
+
82
+ if __name__ == "__main__":
83
+ main()