File size: 6,683 Bytes
df9db76
 
 
 
 
 
65f6621
df9db76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9fe5d26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df9db76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb96f20
 
6808fed
fb96f20
 
65f6621
 
 
 
 
 
 
fb96f20
 
 
 
df9db76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
import streamlit as st
import pandas as pd
from database import Database
from voice_handler import VoiceHandler
from gemini_processor import GeminiProcessor
from memory_handler import MemoryHandler
from voice_input import render_voice_input
import os
from dotenv import load_dotenv

load_dotenv()

# Initialize components
try:
    db = Database()
    voice_handler = VoiceHandler()
    gemini_processor = GeminiProcessor()
    if 'memory_handler' not in st.session_state:
        st.session_state.memory_handler = MemoryHandler()
except Exception as e:
    st.error(f"Error initializing components: {str(e)}")
    st.stop()

def validate_request(project_number, project_name, amount, reason):
    if not project_number or not project_name or not amount or not reason:
        missing_fields = []
        if not project_number: missing_fields.append("project number")
        if not project_name: missing_fields.append("project name")
        if not amount: missing_fields.append("amount")
        if not reason: missing_fields.append("reason")
        return False, f"Please provide the following missing information: {', '.join(missing_fields)}"
    return True, ""

def render_text_input(language_option):
    """Render the text input section"""
    if language_option == "Arabic":
        st.markdown("""
        أدخل طلبك في شكل نص. مثال:
        > "أحتاج إلى طلب 500 ريال للمشروع 223 المسمى جامعة أبها لشراء بعض الأدوات"
        """)
    else:
        st.markdown("""
        Enter your request in text format. Example:
        > "I need to request 500 riyals for project 223 named Abha University to buy some tools"
        """)
    
    text_input = st.text_area("Enter your request:", height=100)
    col1, col2 = st.columns([1, 4])
    
    with col1:
        if st.button("Process Text"):
            if text_input:
                with st.spinner("Processing text input..."):
                    context = st.session_state.memory_handler.get_context()
                    details = gemini_processor.extract_request_details(text_input, context)
                    if details:
                        st.session_state['voice_details'] = details
                        if 'translated_text' in details:
                            st.info(f"Translated text: {details['translated_text']}")
                        if details.get('missing_fields'):
                            missing = ", ".join(details['missing_fields'])
                            st.warning(f"Please provide the following missing information: {missing}")
                        else:
                            st.success("Text processed! Please verify the details below.")
                    else:
                        st.error("Could not extract request details. Please try again.")
            else:
                st.warning("Please enter some text first.")

st.title("AI Agent Money Request System")
st.markdown("---")

# Language Selection
if 'language' not in st.session_state:
    st.session_state.language = "en-US"  # Default to English

st.sidebar.title("Settings")
language_option = st.sidebar.selectbox(
    "Select Input Language",
    options=["English", "Arabic", "Mixed (Arabic/English)"],
    index=0,
    key="language_select"
)

# Map selection to language codes
language_mapping = {
    "English": "en-US",
    "Arabic": "ar-SA",
    "Mixed (Arabic/English)": "mixed"
}

# Input Method Tabs
tab1, tab2 = st.tabs(["Voice Input", "Text Input"])

# Voice Input Tab
with tab1:
    render_voice_input(
        voice_handler,
        language_option,
        language_mapping,
        st.session_state.memory_handler,
        gemini_processor
    )

# Text Input Tab
with tab2:
    render_text_input(language_option)

# Show conversation history
if st.session_state.memory_handler.conversation_history:
    with st.expander("Previous Inputs"):
        for i, text in enumerate(st.session_state.memory_handler.conversation_history, 1):
            st.text(f"{i}. {text}")

# Input form
st.markdown("---")
st.subheader("Submit Money Request")
with st.form("request_form"):
    voice_details = st.session_state.get('voice_details', {})
    
    project_number = st.text_input("Project Number", value=voice_details.get('project_number', ''))
    project_name = st.text_input("Project Name", value=voice_details.get('project_name', ''))
    amount = st.number_input("Amount (in riyals)", 
                           value=float(voice_details.get('amount', 0)),
                           min_value=0.0, 
                           step=100.0)
    reason = st.text_input("Reason for Request", value=voice_details.get('reason', ''))
    
    col1, col2 = st.columns(2)
    with col1:
        submitted = st.form_submit_button("Submit Request")
    with col2:
        confirmed = st.form_submit_button("Confirm & Save")

if submitted:
    is_valid, message = validate_request(project_number, project_name, amount, reason)
    if is_valid:
        st.session_state.show_confirmation = True
        confirmation_text = f"""
        Please review the following request and click 'Confirm & Save' to proceed:
        
        - Project Number: {project_number}
        - Project Name: {project_name}
        - Amount: {amount} riyals
        - Reason: {reason}
        """
        st.info(confirmation_text)
    else:
        st.error(message)

if confirmed:
    is_valid, message = validate_request(project_number, project_name, amount, reason)
    if is_valid:
        try:
            original_text = voice_details.get('original_text', '') if 'voice_details' in st.session_state else ''
            db.add_request(project_number, project_name, amount, reason, original_text)
            st.success("Request successfully added to the database!")
            if 'voice_details' in st.session_state:
                del st.session_state['voice_details']
            st.session_state.show_confirmation = False
            st.session_state.memory_handler.clear_memory()
        except Exception as e:
            st.error(f"Error saving request: {str(e)}")
    else:
        st.error(message)

# Display existing requests
st.markdown("---")
st.subheader("Existing Requests")
try:
    requests = db.get_all_requests()
    if requests:
        df = pd.DataFrame(requests)
        # Reorder columns to show original text
        columns = ['timestamp', 'project_number', 'project_name', 'amount', 'reason', 'original_text']
        df = df[columns]
        st.dataframe(df, use_container_width=True)
    else:
        st.info("No requests submitted yet.")
except Exception as e:
    st.error(f"Error loading requests: {str(e)}")