File size: 5,370 Bytes
50b5999
 
 
91fd430
50b5999
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Streamlit web interface for the Logo Downloader
"""

import os
import logging
import streamlit as st
from pathlib import Path
from typing import Optional

from services.logo_downloader import LogoDownloader
from services.appconfig import GEMINI_API_KEY, DEFAULT_LOGOS_PER_ENTITY, MAX_LOGOS_PER_ENTITY

# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


def process_text_request(text: str, api_key: Optional[str], num_logos: int = DEFAULT_LOGOS_PER_ENTITY):
    """
    Process text and download logos through Streamlit interface
    """
    try:
        if not text or not text.strip():
            return "❌ Please provide some text to analyze.", None, "No text provided."

        if num_logos < 1 or num_logos > MAX_LOGOS_PER_ENTITY:
            return f"❌ Number of logos must be between 1 and {MAX_LOGOS_PER_ENTITY}.", None, f"Invalid number: {num_logos}"

        final_api_key = api_key.strip() if api_key and api_key.strip() else GEMINI_API_KEY

        downloader = LogoDownloader(gemini_api_key=final_api_key)
        results = downloader.process_text(text, num_logos)

        if results['status'] == 'success' and results['stats']['total_downloads'] > 0:
            status_msg = f"βœ… {downloader.get_stats_summary()}"
            zip_path = results.get('zip_path')
            detailed_results = _format_detailed_results(results)
            return status_msg, zip_path, detailed_results

        elif results['status'] == 'warning':
            return f"⚠️ {results['message']}", None, results.get('message', 'No details available')

        else:
            return f"❌ Processing failed: {results['message']}", None, results.get('message', 'Unknown error')

    except Exception as e:
        logger.error(f"Error in process_text_request: {e}")
        return f"❌ An error occurred: {str(e)}", None, f"Error details: {str(e)}"


def _format_detailed_results(results):
    if not results.get('results'):
        return "No detailed results available."

    details = []
    details.append(f"πŸ“Š **Processing Summary:**")
    details.append(f"- Total entities found: {results['stats']['total_entities']}")
    details.append(f"- Total logos downloaded: {results['stats']['total_downloads']}")
    details.append(f"- Successful entities: {results['stats']['successful_entities']}")
    details.append(f"- Failed entities: {results['stats']['failed_entities']}")
    details.append("")
    details.append("πŸ“‹ **Entity Details:**")

    for result in results['results']:
        entity = result['entity']
        count = result['downloaded_count']
        if count > 0:
            details.append(f"βœ… **{entity}**: {count} logos downloaded")
        else:
            error_msg = result.get('error', 'No logos found')
            details.append(f"❌ **{entity}**: Failed ({error_msg})")

    return "\n".join(details)


def main():
    st.set_page_config(page_title="🎨 Logo Downloader", layout="centered")
    st.title("🎨 Logo Downloader")
    st.markdown("Extract entities from text and download their logos automatically.")

    with st.form(key="logo_form"):
        text_input = st.text_area(
            "πŸ“ Enter text containing company names, products, or brands:",
            placeholder="e.g., We use AWS, Docker, React, and Adobe Photoshop for our projects",
            height=150
        )

        api_key_input = st.text_input(
            "πŸ”‘ Gemini API Key (optional)",
            type="password",
            placeholder="Enter your Gemini API key for enhanced extraction"
        )

        num_logos_input = st.slider(
            "πŸ–ΌοΈ Logos per entity",
            min_value=1,
            max_value=MAX_LOGOS_PER_ENTITY,
            value=DEFAULT_LOGOS_PER_ENTITY,
            step=1
        )

        submit_btn = st.form_submit_button("πŸš€ Download Logos")

    if submit_btn:
        with st.spinner("Processing logos..."):
            status_msg, zip_path, detailed_results = process_text_request(
                text_input,
                api_key_input,
                num_logos_input
            )
        st.markdown(status_msg)

        if zip_path and Path(zip_path).exists():
            with open(zip_path, "rb") as f:
                st.download_button(
                    label="πŸ“₯ Download Logos ZIP",
                    data=f,
                    file_name=Path(zip_path).name,
                    mime="application/zip"
                )

        st.markdown("## πŸ“Š Detailed Results")
        st.markdown(detailed_results)

    st.markdown("---")
    st.info("πŸ’‘ Tip: Get a free Gemini API key at [Google AI Studio](https://makersuite.google.com/app/apikey) for better extraction accuracy.")

    st.markdown("## πŸ’‘ Examples")
    examples = [
        "Our tech stack includes React, Node.js, MongoDB, Docker, AWS, and we use Figma for design, along with GitHub for version control.",
        "The team uses Microsoft Office, Adobe Creative Suite, Slack for communication, Zoom for meetings, and Salesforce for CRM.",
        "Popular social media platforms like Instagram, TikTok, Twitter, LinkedIn, and YouTube are essential for digital marketing."
    ]

    for ex in examples:
        if st.button(f"Use example: {ex[:50]}..."):
            st.session_state["text_input"] = ex


if __name__ == "__main__":
    main()