File size: 3,764 Bytes
2466a08
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import gradio as gr
import google.generativeai as genai
import chardet  # Auto-detect file encoding

# βœ… Load API Key securely from Hugging Face Secrets
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")

if not GOOGLE_API_KEY:
    raise ValueError("⚠ Error: Google API Key is missing. Set it in Hugging Face Secrets.")

# βœ… Configure Google Generative AI (Gemini)
genai.configure(api_key=GOOGLE_API_KEY)

# βœ… Load the Gemini Model
model = genai.GenerativeModel(model_name="models/gemini-2.0-flash")

# πŸ”Ή Function to read a file with auto-detected encoding
def read_file_with_encoding(file_path):
    try:
        with open(file_path, "rb") as f:
            raw_data = f.read()

        # Detect file encoding
        encoding = chardet.detect(raw_data)["encoding"]
        if encoding is None:
            encoding = "utf-8"  # Default to UTF-8 if detection fails

        # Read file with detected encoding
        with open(file_path, "r", encoding=encoding, errors="replace") as f:
            return f.read()
    except Exception as e:
        return f"⚠ Error reading file: {str(e)}"

# πŸ”Ή Function to analyze text or file content
def analyze_input(text, file):
    try:
        if file is not None:
            text = read_file_with_encoding(file)  # βœ… Auto-detect encoding
        elif not text.strip():
            return "⚠ Error: Please enter text or upload a file.", ""

        text = text[:2000]  # Limit input text size
        prompt = f"Analyze and summarize this document:\n\n{text}"
        response = model.generate_content([prompt], stream=True)  # βœ… Fix applied

        # Collect streamed response
        result = "".join([chunk.text for chunk in response])
        word_count = len(text.split())

        return result, f"πŸ“Š Word Count: {word_count}"
    except Exception as e:
        return f"⚠ Error: {str(e)}", ""

# πŸ”Ή Function to clear inputs and outputs
def clear_inputs():
    return "", None, "", "", None  

# πŸ”Ή Function to generate a downloadable text file
def generate_downloadable_file(text):
    if text.strip():
        file_path = "analysis_result.txt"
        with open(file_path, "w", encoding="utf-8") as f:
            f.write(text)
        return file_path
    else:
        return None  

# βœ… Create Gradio UI
with gr.Blocks(theme=gr.themes.Default()) as demo:
    gr.Markdown("""
    # πŸ“„ *AI-Powered Text & File Analyzer*
    πŸš€ Upload a .txt file or enter text manually to get an AI-generated analysis and summary.
    """)

    with gr.Row():
        text_input = gr.Textbox(label="✍ Enter Text", placeholder="Type or paste your text here...", lines=6)
        file_input = gr.File(label="πŸ“‚ Upload Text File (.txt)", type="filepath")  

    output_text = gr.Textbox(label="πŸ“ Analysis Result", lines=10, interactive=False)
    word_count_display = gr.Textbox(label="πŸ“Š Word Count", interactive=False)

    with gr.Row():
        analyze_button = gr.Button("πŸ” Analyze", variant="primary")
        clear_button = gr.Button("πŸ—‘ Clear", variant="secondary")

    with gr.Column():
        gr.Markdown("### πŸ“₯ Download Analysis Result")
        with gr.Row():
            download_button = gr.Button("⬇ Download Result", variant="success", size="sm")
            download_file = gr.File(label="πŸ“„ Click to Download", interactive=False)

    # βœ… Button functionalities
    analyze_button.click(analyze_input, inputs=[text_input, file_input], outputs=[output_text, word_count_display])
    clear_button.click(clear_inputs, inputs=[], outputs=[text_input, file_input, output_text, word_count_display, download_file])
    download_button.click(generate_downloadable_file, inputs=output_text, outputs=download_file)

# βœ… Launch the Gradio app
demo.launch()