File size: 27,175 Bytes
2b0414b
cd29e0d
2b0414b
 
 
 
 
 
 
 
 
 
a23d62f
 
2b0414b
a23d62f
2b0414b
 
 
 
 
792826f
2b0414b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
792826f
2b0414b
 
a23d62f
 
2b0414b
a23d62f
2b0414b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd29e0d
2b0414b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd29e0d
2b0414b
 
 
 
 
 
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
from flask import Flask, request, jsonify, send_from_directory
import pandas as pd
import torch
from transformers import BertTokenizer, BertForSequenceClassification
from wordcloud import WordCloud
import uuid
import io
import base64
import os
from PIL import Image

app = Flask(__name__)
UPLOAD_FOLDER = "uploads"
# os.makedirs(UPLOAD_FOLDER, exist_ok=True)

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)

# Load model and tokenizer once
tokenizer = BertTokenizer.from_pretrained("bert-base-multilingual-cased")
model_path = "./src/emotion_final_model"
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = BertForSequenceClassification.from_pretrained(model_path).to(device)
model.eval()

# Label Mapping
label_mapping = {0: "negative", 1: "neutral", 2: "positive"}

@app.route('/predict', methods=['POST'])
def predict():
    data = request.get_json()
    text = data.get('text')

    if not text:
        return jsonify({"error": "No text provided"}), 400

    inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True, max_length=512)
    inputs = {key: value.to(device) for key, value in inputs.items()}

    with torch.no_grad():
        outputs = model(**inputs)

    logits = outputs.logits
    predicted_class_idx = torch.argmax(logits, dim=-1).item()
    sentiment = label_mapping[predicted_class_idx]

    return jsonify({"sentiment": sentiment})

aspect_keywords = {
    "Quality": ["quality", "material", "durable", "performance", "sturdy", "broken", "defective", "معیار", "ٹوٹا ہوا", "خراب"],
    "Price": ["price", "cheap", "expensive", "value", "cost", "قیمت", "مہنگا", "سستا", "قیمت زیادہ"],
    "Delivery": ["delivery", "shipping", "arrived", "late", "courier", "ترسیل", "شپنگ", "تاخیر", "دیر سے پہنچا"],
    "Usability": ["easy to use", "setup", "installation", "instructions", "user-friendly", "آسان", "استعمال میں آسان", "سیٹ اپ", "تنصیب"],
    "Design": ["design", "style", "appearance", "color", "looks", "ڈیزائن", "خوبصورتی", "رنگ", "ساخت"],
    "Warranty/Support": ["warranty", "support", "return", "replacement", "service center", "وارنٹی", "واپسی", "تبادلہ", "سروس سینٹر"]
}

def detect_aspects(text):
    text_lower = text.lower()
    detected = []
    for aspect, keywords in aspect_keywords.items():
        if any(keyword in text_lower for keyword in keywords):
            detected.append(aspect)
    return detected

@app.route("/analyze", methods=["POST"])
def analyze():
    if 'file' not in request.files:
        return jsonify({"error": "No file uploaded"}), 400
    file = request.files['file']
    print(file.filename)
    df = pd.read_csv(file)
    print(df.to_string())
    total_positive = 0
    total_negative = 0
    total_neutral = 0
    all_text = ""
    # Aspect summary
    aspect_summary = {aspect: {"positive": 0, "negative": 0, "neutral": 0, "total": 0} for aspect in aspect_keywords}
    for text in df['Review'].dropna():
        inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True, max_length=512)
        inputs = {k: v.to(device) for k, v in inputs.items()}

        with torch.no_grad():
            outputs = model(**inputs)

        predicted_class_idx = torch.argmax(outputs.logits, dim=-1).item()
        sentiment = label_mapping[predicted_class_idx]

        if sentiment == "positive":
            total_positive += 1
        elif sentiment == "negative":
            total_negative += 1
        else:
            total_neutral += 1

        all_text += " " + text

        detected_aspects = detect_aspects(text)
        for aspect in detected_aspects:
            aspect_summary[aspect][sentiment] += 1
            aspect_summary[aspect]["total"] += 1

    # Generate WordCloud
    wordcloud = WordCloud(width=800, height=400, background_color='white', font_path='src/urdu_font.ttf').generate(all_text)

    # Save in uploads folder
    # if not os.path.exists("uploads"):
    #     os.makedirs("uploads")

    wordcloud_path = os.path.join("uploads", f"wordcloud{uuid.uuid4()}.png")
    wordcloud.to_file(wordcloud_path)

    # Convert image to base64
    with open(wordcloud_path, "rb") as image_file:
        encoded_image = base64.b64encode(image_file.read()).decode('utf-8')

    print({
        "total_positive": total_positive,
        "total_negative": total_negative,
        "total_neutral": total_neutral,
        "aspect_summary": aspect_summary,
        "wordcloud_image_path": wordcloud_path,
    })

    return jsonify({
        "total_positive": total_positive,
        "total_negative": total_negative,
        "total_neutral": total_neutral,
        "aspect_summary": aspect_summary,
        "wordcloud_image_path": wordcloud_path,
        # "wordcloud_image_base64": encoded_image
    })

def run_flask():
    app.run(host="0.0.0.0", port=5000)

import threading
threading.Thread(target=run_flask).start()

import streamlit as st
import pandas as pd
import plotly.express as px
from io import BytesIO, StringIO
from PIL import Image
import random
import requests
import os
import uuid
import tempfile

API_URL = 'http://127.0.0.1:5000/analyze'

# -------------------
# PAGE CONFIG & THEME
# -------------------
st.set_page_config(
    page_title="Multilingual Sentiment Analyzer", 
    layout="wide"
)

st.markdown("""
    <style>
        /* Light theme override */
        html, body, .stApp {
            background-color: #ffffff !important;
            color: #000000 !important;
        }

        h1, h2, h3, h4, h5, h6, p, div, span, label, section, .markdown-text-container {
            color: #000000 !important;
        }

        .stFileUploader > div, .stFileUploader div div {
            background-color: #f9f9f9 !important;
            border: 1px solid #ccc !important;
            color: #000000 !important;
        }
    </style>
""", unsafe_allow_html=True)

st.markdown("""
    <div style='text-align: center; padding-top: 10px;'>
        <h1 style='font-size: 40px;'>🌍 Multilingual Sentiment Analysis Dashboard</h1>
        <p style='font-size: 18px; color: #ccc; max-width: 720px; margin: auto;'>
    Upload a CSV to explore sentiment Report. With sentiment analysis, you can catch early signals, reduce risk, and validate market fit — even across global audiences.
        </p>
    </div>
""", unsafe_allow_html=True)

# -------------------
# DUMMY DATA FUNCTION
# -------------------
def load_dummy_data():
    return pd.DataFrame({
        "Review": [
            "La livraison était très rapide et le service excellent.",
            "The product quality was terrible, I want a refund.",
            "Servicio al cliente fue amable pero no resolvieron mi problema.",
            "Das Produkt kam beschädigt an und der Support war unhöflich.",
            "Great value for the price, I'm very happy!",
            "Muy mal embalaje, pero el envío fue rápido.",
            "客服很好,但产品描述不准确。",
            "Perfect fit, just as described. Will buy again!"
        ]
    })

# -------------------
# MAIN UPLOAD BLOCK (VISIBLE)
# -------------------
with st.expander("📁 Upload Your CSV File", expanded=True):
    uploaded_file = st.file_uploader("Choose a CSV file with reviews", type=["csv"])
    # Analysis button moved here, right after file upload
    run_analysis = st.button("🚀 Run Analysis", type="primary")

    # Load Data: Uploaded or Dummy
    if uploaded_file:
        try:
            # Read uploaded CSV file
            df = pd.read_csv(uploaded_file)
            if df.empty:
                st.error("The uploaded CSV file is empty.")
                df = load_dummy_data()
            else:
                st.success("✅ File uploaded successfully!")
        except Exception as e:
            st.error(f"Error reading CSV: {e}")
            df = load_dummy_data()
    else:
        st.info("Using built-in demo data. Upload a CSV to use your own.")
        df = load_dummy_data()
    
    # Preview data
    st.write("✅ App is running! Here's a sample:")
    st.dataframe(df.head())
    
    # Column selection
    # text_column = st.selectbox("📝 Select the column with review text:", df.columns)
    # enable_aspect = st.checkbox("🔍 Include Aspect Report (Optional)", value=True)
    text_column = 'Review'
    enable_aspect = True

# -------------------
# SENTIMENT METRICS
# -------------------
st.markdown("---")
st.markdown("### 🔎 Sentiment Analysis Results")

# MOCK SENTIMENT PREDICTION
def fake_sentiment_predict(text):
    return random.choice(["Positive", "Negative", "Neutral"]), round(random.uniform(0.65, 0.99), 2)

# Store the analyzed dataframe in session state
if 'analyzed_df' not in st.session_state:
    st.session_state.analyzed_df = df.copy()

# Initialize variables
positive, negative, neutral, total = 0, 0, 0, 0

# Process the data when the Run Analysis button is clicked
if run_analysis:
    if not enable_aspect:
        # Use fake predictions if not calling the API
        fake_results = [fake_sentiment_predict(text) for text in df[text_column]]
        sentiments, confidences = zip(*fake_results)
        
        # Update the analyzed dataframe
        st.session_state.analyzed_df = df.copy()
        st.session_state.analyzed_df["Sentiment"] = sentiments
        st.session_state.analyzed_df["Confidence"] = confidences

        # Count sentiment
        sentiment_counts = pd.Series(sentiments).value_counts()
        positive = sentiment_counts.get("Positive", 0)
        negative = sentiment_counts.get("Negative", 0)
        neutral = sentiment_counts.get("Neutral", 0)
        total = positive + negative + neutral
    else:
        # API Call will be made - handled below
        pass

def percent(part):
    return f"{round((part / total) * 100)}%" if total else "0%"

# Layout: Cards + Chart
card_col, chart_col = st.columns([1.2, 2])

with card_col:
    st.markdown("""
    <style>
    .card-container {
        max-width: 10px;
        margin: 0 auto;
    }
    .card {
        padding: 10px;
        border-radius: 12px;
        margin-bottom: 10px;
        font-size: 16px;
        font-weight: 500;
        line-height: 1.5;
        background-color: var(--secondary-background-color);
        border: 1px solid rgba(255,255,255,0.15);
        color: white;
        text-align: center;
    }
    .card strong {
        font-size: 20px;
        display: block;
        margin-top: 5px;
    }
    </style>
    <div class="card-container">
    """, unsafe_allow_html=True)

if total > 0:  # Only display chart if we have data
    with chart_col:
        fig = px.pie(
            names=["Positive", "Negative", "Neutral"],
            values=[positive, negative, neutral],
            color_discrete_map={
                "Positive": "#66bb6a",
                "Negative": "#ef5350",
                "Neutral": "#42a5f5"
            }
        )
        fig.update_traces(
            textinfo='percent+label',
            hoverinfo='label+percent+value',
            pull=[0.03, 0.03, 0.03]
        )
        fig.update_layout(
            margin=dict(t=20, b=20, l=10, r=10),
            paper_bgcolor="rgba(0,0,0,0)",
            plot_bgcolor="rgba(0,0,0,0)",
            font_color="white"
        )
        st.plotly_chart(fig, use_container_width=True)

# -------------------
# ASPECT REPORT (API Call)
# -------------------
if run_analysis and enable_aspect:
    st.subheader("📌 Aspect Sentiment Summary")

    with st.spinner("Fetching Aspect Report from API..."):
        try:
            # Create a dataframe with only the text column
            api_df = df.copy()
            
            # Create a unique filename with UUID
            unique_filename = f"temp_reviews_{uuid.uuid4()}.csv"
            
            # Write to a physical temporary file with UUID in name
            with tempfile.NamedTemporaryFile(delete=False, suffix=unique_filename) as tmp:
                api_df.to_csv(tmp.name, index=False)
                tmp_file_path = tmp.name
            
            # Open the file in binary mode
            with open(tmp_file_path, 'rb') as file:
                # Send the actual file
                files = {'file': (unique_filename, file, 'text/csv')}
                
                response = requests.post(API_URL, files=files)
            
            # Clean up temporary file
            try:
                os.unlink(tmp_file_path)
            except:
                pass  # Silently fail if we can't delete the temp file
            
            if response.status_code == 200:
                response_json = response.json()

                # Store API response in session state
                st.session_state.api_response_json = response_json
                
                # Update metrics from API response
                positive = response_json.get("total_positive", 0)
                negative = response_json.get("total_negative", 0)
                neutral = response_json.get("total_neutral", 0)
                total = positive + negative + neutral
                
                # Calculate percentages for Excel report if not provided by API
                if "positive_percentage" not in response_json and total > 0:
                    response_json["positive_percentage"] = round((positive / total) * 100)
                    response_json["negative_percentage"] = round((negative / total) * 100)
                    response_json["neutral_percentage"] = round((neutral / total) * 100)
                
                # Add total reviews to response_json if not present
                if "total_reviews" not in response_json:
                    response_json["total_reviews"] = total
                
                # Update metrics from API response
                positive = response_json.get("total_positive", 0)
                negative = response_json.get("total_negative", 0)
                neutral = response_json.get("total_neutral", 0)
                total = positive + negative + neutral
                
                # Update the metrics cards with new data
                with card_col:
                    st.markdown(f"""
                    <div class="card" style="border-color:#bfbfbf;">
                        📊 <strong>Total Reviews</strong>
                        {total}
                    </div>
                    <div class="card" style="border-color:#66bb6a;">
                        ✅ <strong>{positive} Positive</strong>
                        {percent(positive)} of total
                    </div>
                    <div class="card" style="border-color:#ef5350;">
                        ❗ <strong>{negative} Negative</strong>
                        {percent(negative)} of total
                    </div>
                    <div class="card" style="border-color:#42a5f5;">
                        😐 <strong>{neutral} Neutral</strong>
                        {percent(neutral)} of total
                    </div>
                    </div>
                    """, unsafe_allow_html=True)
                
                # Update the pie chart
                with chart_col:
                    fig = px.pie(
                        names=["Positive", "Negative", "Neutral"],
                        values=[positive, negative, neutral],
                        color_discrete_map={
                            "Positive": "#66bb6a",
                            "Negative": "#ef5350",
                            "Neutral": "#42a5f5"
                        }
                    )
                    fig.update_traces(
                        textinfo='percent+label',
                        hoverinfo='label+percent+value',
                        pull=[0.03, 0.03, 0.03]
                    )
                    fig.update_layout(
                        margin=dict(t=20, b=20, l=10, r=10),
                        paper_bgcolor="rgba(0,0,0,0)",
                        plot_bgcolor="rgba(0,0,0,0)",
                        font_color="white"
                    )
                    st.plotly_chart(fig, use_container_width=True)

                # Update the analyzed dataframe with sentiment results from API
                if "review_details" in response_json:
                    # Create a new dataframe from the API results
                    api_result_df = pd.DataFrame(response_json["review_details"])
                    
                    # Store it in session state
                    st.session_state.analyzed_df = api_result_df
                else:
                    # If review_details not provided, create basic sentiment columns
                    st.session_state.analyzed_df = df.copy()
                    # Try to extract sentiments if available in the API response
                    if "sentiments" in response_json:
                        st.session_state.analyzed_df["Sentiment"] = response_json["sentiments"]
                    # Add any other available result fields
                    for key in ["confidences", "languages"]:
                        if key in response_json:
                            column_name = key.rstrip("s").capitalize()  # Convert "confidences" to "Confidence"
                            st.session_state.analyzed_df[column_name] = response_json[key]

                # Prepare aspect DataFrame
                aspect_rows = []
                for aspect, values in response_json["aspect_summary"].items():
                    aspect_rows.append({
                        "Aspect": aspect,
                        "Positive": values["positive"],
                        "Negative": values["negative"],
                        "Neutral": values["neutral"],
                        "Total": values["total"]
                    })
                aspect_df = pd.DataFrame(aspect_rows)
                
                # Display aspect data if we have any
                if not aspect_df.empty and aspect_df["Total"].sum() > 0:

                    # Store aspect dataframe in session state
                    st.session_state.aspect_dataframe = aspect_df
                    st.dataframe(aspect_df)

                    # Prepare data for bar chart
                    melted = aspect_df.melt(
                        id_vars="Aspect",
                        value_vars=["Positive", "Negative", "Neutral"],
                        var_name="Sentiment",
                        value_name="Count"
                    )

                    col1, col2 = st.columns([4, 2]) 

                    with col1:
                        st.markdown("### 📊 Sentiment by Aspect")
                        bar_chart = px.bar(
                            melted,
                            x="Aspect",
                            y="Count",
                            color="Sentiment",
                            barmode="group",
                            title=None,
                            color_discrete_map={
                                "Positive": "#66bb6a",
                                "Negative": "#ef5350",
                                "Neutral": "#42a5f5"
                            }
                        )
                        # Update chart theme for dark mode
                        bar_chart.update_layout(
                            paper_bgcolor="rgba(0,0,0,0)",
                            plot_bgcolor="rgba(0,0,0,0)",
                            font_color="white",
                            xaxis=dict(gridcolor="rgba(255,255,255,0.1)"),
                            yaxis=dict(gridcolor="rgba(255,255,255,0.1)")
                        )
                        st.plotly_chart(bar_chart, use_container_width=True)

                    with col2:
                        st.markdown("### 🌀 Review Keywords")

                        # Try to display wordcloud from API
                        if "wordcloud_image_base64" in response_json:
                            import base64
                            st.markdown("<div style='padding-top:60px'></div>", unsafe_allow_html=True)
                            st.image(
                                BytesIO(base64.b64decode(response_json["wordcloud_image_base64"])),
                                caption="Keyword Cloud", 
                                use_container_width=True
                            )
                        else:
                            try:
                                # Try local wordcloud file as fallback
                                wordcloud_path = response_json.get("wordcloud_image_path")
                                if wordcloud_path and os.path.exists(wordcloud_path):
                                    image = Image.open(wordcloud_path)
                                    st.markdown("<div style='padding-top:60px'></div>", unsafe_allow_html=True)
                                    st.image(image, caption="Keywords", use_container_width=True)
                                else:
                                    # Try default wordcloud
                                    if os.path.exists("wordcloud.jpg"):
                                        image = Image.open("wordcloud.jpg")
                                        st.markdown("<div style='padding-top:60px'></div>", unsafe_allow_html=True)
                                        st.image(image, caption="Keywords", use_container_width=True)
                            except Exception as e:
                                st.warning(f"⚠ Word cloud image not found: {e}")
                else:
                    st.info("No aspects detected in the reviews.")
            else:
                st.error(f"API Error: {response.status_code} - {response.text}")
        except Exception as e:
            st.error(f"API call failed: {e}")
            import traceback
            st.code(traceback.format_exc(), language="python")


# -------------------
# DOWNLOAD BUTTON
# -------------------
if run_analysis or total > 0:
    st.subheader("📥 Download Analyzed File")

    def generate_excel_report(df, aspect_data=None, response_json=None):
        output = BytesIO()
        
        with pd.ExcelWriter(output, engine='xlsxwriter') as writer:
            # Sheet 1: Main sentiment results
            df.to_excel(writer, index=False, sheet_name='Sentiment_Report')
            
            # Sheet 2: Aspect analysis (if available)
            if aspect_data is not None and not aspect_data.empty:
                aspect_data.to_excel(writer, index=False, sheet_name='Aspect_Analysis')
            
            # Sheet 3: Summary stats (if API response available)
            if response_json:
                # Create a summary dataframe
                summary_data = {
                    'Metric': ['Total Reviews', 'Positive', 'Negative', 'Neutral'],
                    'Count': [
                        response_json.get('total_reviews', 0),
                        response_json.get('total_positive', 0),
                        response_json.get('total_negative', 0),
                        response_json.get('total_neutral', 0)
                    ],
                    'Percentage': [
                        '100%',
                        f"{response_json.get('positive_percentage', 0)}%",
                        f"{response_json.get('negative_percentage', 0)}%",
                        f"{response_json.get('neutral_percentage', 0)}%"
                    ]
                }
                summary_df = pd.DataFrame(summary_data)
                summary_df.to_excel(writer, index=False, sheet_name='Summary')
                
                # Add any other relevant data from API response
                if 'review_details' in response_json:
                    details_df = pd.DataFrame(response_json['review_details'])
                    details_df.to_excel(writer, index=False, sheet_name='Review_Details')
            
            # Get workbook and add some formatting
            workbook = writer.book
            
            # Add formatting
            header_format = workbook.add_format({
                'bold': True,
                'text_wrap': True,
                'valign': 'top',
                'border': 1
            })
            
            # Apply formatting to each worksheet safely
            for sheet_name in writer.sheets:
                worksheet = writer.sheets[sheet_name]
                # Get column names from the DataFrame based on sheet name
                if sheet_name == 'Sentiment_Report':
                    columns = df.columns
                elif sheet_name == 'Aspect_Analysis' and aspect_data is not None:
                    columns = aspect_data.columns
                elif sheet_name == 'Summary':
                    columns = summary_data.keys()
                elif sheet_name == 'Review_Details' and 'review_details' in response_json:
                    columns = details_df.columns
                else:
                    continue
                    
                # Write headers with formatting
                for col_num, value in enumerate(columns):
                    worksheet.write(0, col_num, value, header_format)
                
                # Auto-adjust columns' width (supported in newer versions)
                try:
                    worksheet.autofit()
                except AttributeError:
                    # Fallback for older xlsxwriter versions
                    for col_num, value in enumerate(columns):
                        # Set width based on header content
                        worksheet.set_column(col_num, col_num, max(10, len(str(value)) + 2))
        
        return output.getvalue()

    # Store API response in session state to access it for download
    if 'api_response_json' not in st.session_state:
        st.session_state.api_response_json = None
    if 'aspect_dataframe' not in st.session_state:
        st.session_state.aspect_dataframe = None

    # Update these values when API response is received
    if run_analysis and enable_aspect and 'response_json' in locals():
        st.session_state.api_response_json = response_json
        if 'aspect_df' in locals() and not aspect_df.empty:
            st.session_state.aspect_dataframe = aspect_df

    st.download_button(
        label="📥 Download Results as Excel",
        data=generate_excel_report(
            st.session_state.analyzed_df,  # Use the analyzed dataframe instead of original df
            st.session_state.aspect_dataframe, 
            st.session_state.api_response_json
        ),
        file_name="sentiment_analysis_report.xlsx",
        mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    )

# Add a footer with dark theme
st.markdown("""
<div style="text-align: center; margin-top: 50px; padding: 20px; color: #888; font-size: 14px;">
    <p>Multilingual Sentiment Analysis Dashboard | Made with Streamlit</p>
</div>
""", unsafe_allow_html=True)