Sakshi2005's picture
Update app.py
0f75c71 verified
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
)