File size: 7,073 Bytes
7b759e1
89cd55d
 
 
7b759e1
 
89cd55d
7b759e1
 
89cd55d
 
7b759e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89cd55d
7b759e1
 
 
 
 
 
 
 
 
 
 
 
89cd55d
7b759e1
89cd55d
7b759e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

import gradio as gr
import google.generativeai as genai
import json
import re
from collections import Counter

# Configure Gemini API
API_KEY = "AIzaSyAtm1yxPoXsz30KJUnyQNN9QeGw3FMIoMU"  # Replace with your actual API key
genai.configure(api_key=API_KEY)

model = genai.GenerativeModel(
    model_name="gemini-2.0-flash",
    generation_config={
        "temperature": 0.7,
        "max_output_tokens": 1500,
    }
)

class SimpleAnalyzer:
    def clean_text(self, text):
        """Basic text cleaning"""
        if not text:
            return ""
        
        # Remove timestamps and system messages
        text = re.sub(r'\d{1,2}:\d{2}(?::\d{2})?\s*(?:AM|PM|am|pm)?', '', text)
        text = re.sub(r'\[.*?\]', '', text)
        text = re.sub(r'<.*?>', '', text)
        text = re.sub(r'\s+', ' ', text.strip())
        
        return text
    
    def get_basic_stats(self, text):
        """Get simple statistics"""
        if not text:
            return {}
        
        words = text.split()
        lines = [line.strip() for line in text.split('\n') if line.strip()]
        
        return {
            'word_count': len(words),
            'message_count': len([line for line in lines if len(line) > 5]),
            'avg_words_per_message': len(words) / max(len(lines), 1)
        }

analyzer = SimpleAnalyzer()

def analyze_relationship(chat_text):
    """Main analysis function"""
    if not chat_text or not chat_text.strip():
        return "Please provide chat text to analyze.", "", "", ""
    
    # Clean and get stats
    cleaned_text = analyzer.clean_text(chat_text)
    stats = analyzer.get_basic_stats(cleaned_text)
    
    # Create analysis prompt
    prompt = f"""
Analyze this relationship chat conversation and provide insights in this exact JSON format:
{{
    "compatibility_score": number (0-100),
    "relationship_stage": "string description",
    "communication_style": "string description",
    "strengths": ["strength1", "strength2", "strength3"],
    "improvements": ["area1", "area2", "area3"],
    "summary": "2-3 sentence relationship summary",
    "red_flags": ["flag1", "flag2"] or []
}}
Chat text: {cleaned_text[:3000]}
Provide only the JSON response, no other text.
"""
    
    try:
        response = model.generate_content(prompt)
        analysis_text = response.text.strip()
        
        # Clean JSON response
        if analysis_text.startswith('```json'):
            analysis_text = analysis_text.split('```json')[1].split('```')[0].strip()
        elif analysis_text.startswith('```'):
            analysis_text = analysis_text.split('```')[1].split('```')[0].strip()
        
        # Parse JSON
        analysis = json.loads(analysis_text)
        
        # Format outputs
        stats_text = f"""📊 **Chat Statistics:**
• Words: {stats['word_count']:,}
• Messages: {stats['message_count']}
• Avg words/message: {stats['avg_words_per_message']:.1f}
• Relationship Stage: {analysis.get('relationship_stage', 'Unknown')}"""

        compatibility_text = f"**Compatibility Score: {analysis.get('compatibility_score', 0)}/100**"
        
        strengths_text = "**💪 Strengths:**\n" + "\n".join([f"• {s}" for s in analysis.get('strengths', [])])
        
        improvements_text = "**🎯 Areas to Improve:**\n" + "\n".join([f"• {i}" for i in analysis.get('improvements', [])])
        
        summary_text = f"**📖 Summary:**\n{analysis.get('summary', 'No summary available')}"
        
        red_flags = analysis.get('red_flags', [])
        if red_flags:
            red_flags_text = "**⚠️ Red Flags:**\n" + "\n".join([f"• {flag}" for flag in red_flags])
        else:
            red_flags_text = "**✅ No significant red flags detected**"
        
        full_analysis = f"""{summary_text}
{compatibility_text}
{strengths_text}
{improvements_text}
{red_flags_text}
**🗣️ Communication Style:** {analysis.get('communication_style', 'Not analyzed')}"""
        
        return full_analysis, stats_text, compatibility_text, f"{analysis.get('compatibility_score', 0)}"
        
    except json.JSONDecodeError:
        return f"AI Response (couldn't parse as JSON):\n{analysis_text}", stats_text, "Score not available", "0"
    except Exception as e:
        return f"Error: {str(e)}", "Stats unavailable", "Score unavailable", "0"

# Create Gradio interface
def create_app():
    with gr.Blocks(theme=gr.themes.Soft(), title="💕 Simple Chat Analyzer") as app:
        
        gr.HTML("""
        <div style="text-align: center; margin-bottom: 30px;">
            <h1>💕 Simple Relationship Chat Analyzer</h1>
            <p><em>Quick insights into your relationship through chat analysis</em></p>
        </div>
        """)
        
        with gr.Row():
            with gr.Column(scale=2):
                chat_input = gr.Textbox(
                    label="📝 Paste Your Chat Conversation",
                    placeholder="Paste your WhatsApp, text messages, or any chat conversation here...",
                    lines=12,
                    max_lines=20
                )
                
                with gr.Row():
                    analyze_btn = gr.Button("🔍 Analyze", variant="primary", scale=2)
                    clear_btn = gr.Button("🗑️ Clear", variant="secondary", scale=1)
            
            with gr.Column(scale=1):
                stats_output = gr.Textbox(
                    label="📊 Quick Stats",
                    interactive=False,
                    lines=8
                )
                
                score_output = gr.Textbox(
                    label="💯 Compatibility",
                    interactive=False,
                    lines=2
                )
        
        # Main results
        analysis_output = gr.Textbox(
            label="🎯 Relationship Analysis",
            interactive=False,
            lines=15,
            max_lines=25
        )
        
        # Event handlers
        def analyze_handler(text):
            return analyze_relationship(text)
        
        def clear_handler():
            return "", "", "", "", ""
        
        analyze_btn.click(
            fn=analyze_handler,
            inputs=[chat_input],
            outputs=[analysis_output, stats_output, score_output, gr.State()]
        )
        
        clear_btn.click(
            fn=clear_handler,
            outputs=[chat_input, analysis_output, stats_output, score_output, gr.State()]
        )
        
        gr.HTML("""
        <div style="text-align: center; margin-top: 20px; padding: 15px; background: #f0f0f0; border-radius: 8px;">
            <p><strong>💡 Tips:</strong> Include longer conversations for better analysis • Remove personal info • Results are for guidance only</p>
        </div>
        """)
    
    return app

# Launch the app
if __name__ == "__main__":
    print("🚀 Starting Simple Relationship Chat Analyzer...")
    
    app = create_app()
    app.launch(
        share=True,
        server_name="0.0.0.0",
        server_port=7860
    )