File size: 6,766 Bytes
ec087d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4ecb5d
ec087d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
from docx import Document
from datetime import datetime
import re
import tempfile
import pytesseract
from PIL import Image
from groq import Groq
import io
import os

# Initialize APIs
client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
pytesseract.pytesseract.tesseract_cmd = r'/usr/bin/tesseract'  # Update path as needed

# Helper Functions
def extract_text_from_image(image_path):
    try:
        img = Image.open(image_path)
        text = pytesseract.image_to_string(img)
        return text.strip() if text else "No text found in image"
    except Exception as e:
        return f"OCR Error: {str(e)}"

def groq_processing(prompt):
    try:
        completion = client.chat.completions.create(
            model="mixtral-8x7b-32768",
            messages=[
                {
                    "role": "user",
                    "content": prompt
                }
            ]
        )
        return completion.choices[0].message.content
    except Exception as e:
        return f"AI Processing Error: {str(e)}"

def analyze_sentiment(text):
    prompt = f"""Analyze the sentiment of this text with detailed emotions:
    {text}
    
    Format response as: 
    Primary Emotion: [emotion]
    Secondary Emotions: [comma-separated list]
    Confidence Level: [percentage]"""
    return groq_processing(prompt)

def categorize_content(text):
    prompt = f"""Categorize this text into specific themes from the following options:
    Technology, Business, Lifestyle, Education, Politics, Health, Entertainment, Sports, Art, Science
    
    Text: {text}
    
    Respond with top 3 relevant categories in order of relevance."""
    return groq_processing(prompt)

# Document Processing Functions
def create_word_document(posts):
    doc = Document()
    doc.add_heading('Social Media Data Extraction Report', 0)
    
    for idx, post in enumerate(posts):
        doc.add_heading(f'Post {idx+1}', level=1)
        
        data = [
            ("Date of Post", post.get('date', 'N/A')),
            ("Media Type", post.get('media_type', 'N/A')),
            ("Number of Pictures", post.get('num_pictures', 'N/A')),
            ("Likes", post.get('likes', 'N/A')),
            ("Comments", post.get('comments', 'N/A')),
            ("Caption", post.get('caption', 'N/A')),
            ("OCR Text", post.get('ocr_text', 'N/A')),
            ("Language", post.get('language', 'N/A')),
            ("Sentiment Analysis", post.get('sentiment', 'N/A')),
            ("Content Categories", post.get('categories', 'N/A')),
            ("Hashtags", ', '.join(post.get('hashtags', [])) if post.get('hashtags') else 'N/A'),
            ("Concept Keywords", ', '.join(post.get('concepts', [])) if post.get('concepts') else 'N/A')
        ]
        
        for label, value in data:
            doc.add_paragraph(f"{label}: {value}")
        
        doc.add_page_break()
    
    temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".docx")
    doc.save(temp_file.name)
    return temp_file.name

# Processing Functions 
def process_social_media(profile_link, hashtags, concepts, platform, date_range, num_posts):
    # Mock data - Replace with actual social media API calls
    mock_image = Image.new('RGB', (800, 600), color='white')
    mock_image_path = tempfile.mktemp(suffix='.jpg')
    mock_image.save(mock_image_path)
    
    posts = [{
        'date': datetime.now().strftime("%Y-%m-%d"),
        'media_type': 'Image',
        'num_pictures': 1,
        'likes': 150,
        'comments': 20,
        'caption': 'Example caption with #technology',
        'ocr_text': extract_text_from_image(mock_image_path),
        'hashtags': ['#technology'],
        'concepts': [c.strip() for c in concepts.split(',')],
        'sentiment': analyze_sentiment('Example caption with #technology'),
        'categories': categorize_content('Example caption with #technology')
    }]
    
    os.remove(mock_image_path)
    return create_word_document(posts[:num_posts])

def process_word_file(file, concepts):
    doc = Document(file.name)
    posts = []
    
    for para in doc.paragraphs:
        if para.text.startswith('Post'):
            posts.append({'caption': ''})
        elif posts:
            posts[-1]['caption'] += para.text + '\n'
    
    processed_posts = []
    for post in posts:
        caption = post.get('caption', '')
        processed_post = {
            'date': datetime.now().strftime("%Y-%m-%d"),
            'media_type': 'Text',
            'caption': caption,
            'sentiment': analyze_sentiment(caption),
            'categories': categorize_content(caption),
            'concepts': [c.strip() for c in concepts.split(',')],
            'hashtags': re.findall(r'#\w+', caption)
        }
        processed_posts.append(processed_post)
    
    return create_word_document(processed_posts)

# Gradio Interface
with gr.Blocks(title="Social Media Analyzer") as app:
    gr.Markdown("# Social Media Data Extraction Tool")
    
    with gr.Tabs():
        with gr.TabItem("Social Media Extraction"):
            gr.Markdown("## Analyze Social Media Profiles")
            with gr.Row():
                with gr.Column():
                    profile_link = gr.Textbox(label="Profile URL")
                    hashtags = gr.Textbox(label="Hashtags (comma separated)")
                    concepts = gr.Textbox(label="Concept Keywords (comma separated)")
                    platform = gr.Radio(["Instagram", "Twitter", "Facebook"], label="Platform")
                    date_range = gr.Textbox(label="Date Range (YYYY-MM-DD to YYYY-MM-DD)")
                    num_posts = gr.Slider(1, 100, value=10, label="Number of Posts")
                    sm_submit = gr.Button("Analyze Profile", variant="primary")
                
                with gr.Column():
                    sm_output = gr.File(label="Download Analysis Report")

        with gr.TabItem("Document Processing"):
            gr.Markdown("## Analyze Word Documents")
            with gr.Row():
                with gr.Column():
                    word_file = gr.File(label="Upload Word Document")
                    wp_concepts = gr.Textbox(label="Concept Keywords (comma separated)")
                    wp_submit = gr.Button("Analyze Document", variant="primary")
                
                with gr.Column():
                    wp_output = gr.File(label="Download Analysis Report")

    sm_submit.click(
        fn=process_social_media,
        inputs=[profile_link, hashtags, concepts, platform, date_range, num_posts],
        outputs=sm_output
    )
    
    wp_submit.click(
        fn=process_word_file,
        inputs=[word_file, wp_concepts],
        outputs=wp_output
    )

if __name__ == "__main__":
    app.launch()