File size: 9,999 Bytes
13b0d84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c87b45b
13b0d84
 
c87b45b
13b0d84
c87b45b
 
13b0d84
 
 
 
 
 
 
 
c87b45b
13b0d84
 
 
 
 
 
 
 
 
c87b45b
13b0d84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c87b45b
13b0d84
 
 
 
 
 
c87b45b
 
13b0d84
c87b45b
13b0d84
 
c87b45b
13b0d84
 
 
c87b45b
13b0d84
 
 
c87b45b
 
13b0d84
 
 
 
c87b45b
13b0d84
 
 
 
 
 
 
 
 
c87b45b
13b0d84
 
 
 
 
c87b45b
13b0d84
c87b45b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13b0d84
c87b45b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
import streamlit as st
import requests
from fpdf import FPDF
import os
import time
from datetime import datetime
import groq

# API keys (replace with your keys or use environment variables)
mistral_api_key = os.getenv("MISTRAL_API_KEY", "gz6lDXokxgR6cLY72oomALWcm7vhjRzQ")
groq_api_key = os.getenv("GROQ_API_KEY", "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")

# Initialize Groq client
groq_client = groq.Client(api_key=groq_api_key)

# Function to call Mistral API
def call_mistral_api(prompt):
    url = "https://api.mistral.ai/v1/chat/completions"
    headers = {
        "Authorization": f"Bearer {mistral_api_key}",
        "Content-Type": "application/json"
    }
    payload = {
        "model": "mistral-medium",
        "messages": [
            {"role": "user", "content": prompt}
        ]
    }
    try:
        response = requests.post(url, headers=headers, json=payload)
        response.raise_for_status()
        return response.json()['choices'][0]['message']['content']
    except requests.exceptions.HTTPError as err:
        if response.status_code == 429:
            st.warning("Rate limit exceeded. Please wait a few seconds and try again.")
            time.sleep(5)
            return call_mistral_api(prompt)
        return f"HTTP Error: {err}"
    except Exception as err:
        return f"Error: {err}"

# Function to call Groq API
def call_groq_api(prompt):
    try:
        response = groq_client.chat.completions.create(
            model="llama-3.3-70b-versatile",
            messages=[
                {"role": "user", "content": prompt}
            ]
        )
        return response.choices[0].message.content
    except Exception as err:
        st.error(f"Error: {err}")
        return f"Error: {err}"

# Function to analyze requirement
def analyze_requirement(requirement):
    type_prompt = f"Classify the following requirement as Functional or Non-Functional in one word:\n\n{requirement}\n\nType:"
    req_type = call_mistral_api(type_prompt).strip()

    domain_prompt = f"Classify the domain for the following requirement in one word (e.g., E-commerce, Education, etc.):\n\n{requirement}\n\nDomain:"
    domain = call_mistral_api(domain_prompt).strip()

    defects_prompt = f"""List ONLY the major defects in the following requirement (e.g., Ambiguity, Incompleteness, etc.) in 1-2 words each:\n\n{requirement}\n\nDefects:"""
    defects = call_groq_api(defects_prompt).strip()

    rewritten_prompt = f"""Rewrite the following requirement in 1-2 sentences to address the defects:\n\n{requirement}\n\nRewritten:"""
    rewritten = call_groq_api(rewritten_prompt).strip()

    return {
        "Requirement": requirement,
        "Type": req_type,
        "Domain": domain,
        "Defects": defects,
        "Rewritten": rewritten
    }

# Function to generate PDF report
def generate_pdf_report(results):
    pdf = FPDF()
    pdf.add_page()
    pdf.set_font("Arial", size=12)

    pdf.set_font("Arial", 'B', 50)
    pdf.set_text_color(230, 230, 230)
    pdf.rotate(45)
    pdf.text(60, 150, "AI Powered Requirement Analysis")
    pdf.rotate(0)

    pdf.set_font("Arial", 'B', 16)
    pdf.set_text_color(0, 0, 0)
    pdf.cell(200, 10, txt="AI Powered Requirement Analysis and Defect Detection", ln=True, align='C')
    pdf.set_font("Arial", size=12)
    pdf.cell(200, 10, txt=f"Report Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", ln=True, align='C')
    pdf.ln(10)

    pdf.set_font("Arial", size=12)
    for i, result in enumerate(results, start=1):
        if pdf.get_y() > 250:
            pdf.add_page()
            pdf.set_font("Arial", 'B', 16)
            pdf.cell(200, 10, txt="AI Powered Requirement Analysis and Defect Detection", ln=True, align='C')
            pdf.set_font("Arial", size=12)
            pdf.cell(200, 10, txt=f"Report Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", ln=True, align='C')
            pdf.ln(10)

        pdf.set_font("Arial", 'B', 14)
        pdf.multi_cell(200, 10, txt=f"Requirement R{i}: {result['Requirement']}", align='L')
        pdf.set_font("Arial", size=12)
        pdf.multi_cell(200, 10, txt=f"Type: {result['Type']}", align='L')
        pdf.multi_cell(200, 10, txt=f"Domain: {result['Domain']}", align='L')
        pdf.multi_cell(200, 10, txt=f"Defects: {result['Defects']}", align='L')
        pdf.multi_cell(200, 10, txt=f"Rewritten: {result['Rewritten']}", align='L')
        pdf.multi_cell(200, 10, txt="-" * 50, align='L')
        pdf.ln(5)

    pdf_output = "requirements_report.pdf"
    pdf.output(pdf_output)
    return pdf_output

# Streamlit UI
def main():
    st.markdown("""
        <style>
            @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap');
            * { font-family: 'Poppins', sans-serif; }
            .main-container { max-width: 800px; margin: 0 auto; padding: 2rem; }
            .gradient-header { background: linear-gradient(45deg, #4F46E5, #1E40AF); 
                             color: white; padding: 2rem; border-radius: 15px; }
            .team-card { background: #f8f9fa; padding: 1.5rem; border-radius: 15px; 
                        margin: 1rem 0; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
            .styled-input { border: 2px solid #e0e0e0 !important; border-radius: 10px !important; 
                          padding: 1rem !important; margin: 1rem 0; }
            .result-card { background: white; padding: 1.5rem; border-radius: 15px;
                          margin: 1rem 0; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
            .badge { padding: 0.3rem 1rem; border-radius: 20px; font-size: 0.9rem; 
                    margin-right: 0.5rem; display: inline-block; }
            .type-badge { background: #4F46E510; color: #4F46E5; }
            .domain-badge { background: #10B98110; color: #10B981; }
            .defect-badge { background: #EF444410; color: #EF4444; }
            .animate-hover { transition: transform 0.2s; }
            .animate-hover:hover { transform: translateY(-2px); }
        </style>
    """, unsafe_allow_html=True)

    st.markdown("""
        <div class="main-container">
            <div class="gradient-header">
                <h1 style="margin: 0; font-weight: 600;">🧠 AI Requirement Analyzer</h1>
                <p style="margin: 0.5rem 0 0; opacity: 0.9;">Smart Analysis & Quality Enhancement System</p>
            </div>
            
            <div class="team-card">
                <h3 style="margin: 0 0 1rem;">πŸ‘₯ Team Members</h3>
                <div style="display: flex; gap: 1rem;">
                    <div style="flex: 1; text-align: center;">
                        <div style="background: #4F46E510; padding: 0.5rem; border-radius: 10px;">
                            <p style="margin: 0; color: #4F46E5;">Sadia</p>
                        </div>
                    </div>
                    <!-- Repeat similar blocks for other team members -->
                </div>
            </div>
    """, unsafe_allow_html=True)

    st.markdown("""
        <div style="margin: 2rem 0;">
            <h2>πŸ“₯ Input Requirements</h2>
            <p style="opacity: 0.8;">Enter multiple requirements separated by new lines or periods</p>
    """, unsafe_allow_html=True)

    input_text = st.text_area("", height=200, key="input_area", 
                            help="Example:\n1. The system must handle 1000 users\n2. User interface should be responsive")

    if st.button("πŸš€ Start Analysis", key="analyze_btn", use_container_width=True):
        if not input_text.strip():
            st.warning("⚠️ Please enter requirements to analyze")
        else:
            requirements = [req.strip() for req in input_text.replace("\n", ".").split(".") if req.strip()]
            results = []
            progress_bar = st.progress(0)
            
            with st.spinner("πŸ” Analyzing requirements..."):
                for i, req in enumerate(requirements):
                    results.append(analyze_requirement(req))
                    progress_bar.progress((i+1)/len(requirements))
                    time.sleep(0.1)

            st.success("βœ… Analysis completed!")
            st.markdown("---")
            
            for i, result in enumerate(results, 1):
                st.markdown(f"""
                    <div class="result-card animate-hover">
                        <h3 style="margin: 0 0 1rem;">πŸ”– Requirement R{i}</h3>
                        <p style="font-size: 1.1rem; margin-bottom: 1.5rem;">{result['Requirement']}</p>
                        
                        <div style="display: flex; gap: 1rem; margin-bottom: 1rem;">
                            <span class="badge type-badge">πŸ“ {result['Type']}</span>
                            <span class="badge domain-badge">🌍 {result['Domain']}</span>
                            <span class="badge defect-badge">⚠️ {result['Defects']}</span>
                        </div>
                        
                        <div style="background: #f8f9fa; padding: 1rem; border-radius: 10px;">
                            <p style="margin: 0; color: #3B82F6;">✏️ Optimized Version:</p>
                            <p style="margin: 0.5rem 0 0; font-weight: 500;">{result['Rewritten']}</p>
                        </div>
                    </div>
                """, unsafe_allow_html=True)

            st.markdown("---")
            st.markdown("### πŸ“„ Generate Report")
            pdf_report = generate_pdf_report(results)
            with open(pdf_report, "rb") as f:
                st.download_button(
                    label="πŸ“₯ Download PDF Report",
                    data=f,
                    file_name="requirements_analysis.pdf",
                    mime="application/pdf",
                    use_container_width=True,
                    key="download_btn"
                )

    st.markdown("</div>", unsafe_allow_html=True)

if __name__ == "__main__":
    main()