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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from docx import Document
|
| 3 |
+
from datetime import datetime
|
| 4 |
+
import re
|
| 5 |
+
import tempfile
|
| 6 |
+
import pytesseract
|
| 7 |
+
from PIL import Image
|
| 8 |
+
from groq import Groq
|
| 9 |
+
import io
|
| 10 |
+
import os
|
| 11 |
+
|
| 12 |
+
# Initialize APIs
|
| 13 |
+
client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
|
| 14 |
+
pytesseract.pytesseract.tesseract_cmd = r'/usr/bin/tesseract' # Update path as needed
|
| 15 |
+
|
| 16 |
+
# Helper Functions
|
| 17 |
+
def extract_text_from_image(image_path):
|
| 18 |
+
try:
|
| 19 |
+
img = Image.open(image_path)
|
| 20 |
+
text = pytesseract.image_to_string(img)
|
| 21 |
+
return text.strip() if text else "No text found in image"
|
| 22 |
+
except Exception as e:
|
| 23 |
+
return f"OCR Error: {str(e)}"
|
| 24 |
+
|
| 25 |
+
def groq_processing(prompt):
|
| 26 |
+
try:
|
| 27 |
+
completion = client.chat.completions.create(
|
| 28 |
+
model="mixtral-8x7b-32768",
|
| 29 |
+
messages=[
|
| 30 |
+
{
|
| 31 |
+
"role": "user",
|
| 32 |
+
"content": prompt
|
| 33 |
+
}
|
| 34 |
+
]
|
| 35 |
+
)
|
| 36 |
+
return completion.choices[0].message.content
|
| 37 |
+
except Exception as e:
|
| 38 |
+
return f"AI Processing Error: {str(e)}"
|
| 39 |
+
|
| 40 |
+
def analyze_sentiment(text):
|
| 41 |
+
prompt = f"""Analyze the sentiment of this text with detailed emotions:
|
| 42 |
+
{text}
|
| 43 |
+
|
| 44 |
+
Format response as:
|
| 45 |
+
Primary Emotion: [emotion]
|
| 46 |
+
Secondary Emotions: [comma-separated list]
|
| 47 |
+
Confidence Level: [percentage]"""
|
| 48 |
+
return groq_processing(prompt)
|
| 49 |
+
|
| 50 |
+
def categorize_content(text):
|
| 51 |
+
prompt = f"""Categorize this text into specific themes from the following options:
|
| 52 |
+
Technology, Business, Lifestyle, Education, Politics, Health, Entertainment, Sports, Art, Science
|
| 53 |
+
|
| 54 |
+
Text: {text}
|
| 55 |
+
|
| 56 |
+
Respond with top 3 relevant categories in order of relevance."""
|
| 57 |
+
return groq_processing(prompt)
|
| 58 |
+
|
| 59 |
+
# Document Processing Functions
|
| 60 |
+
def create_word_document(posts):
|
| 61 |
+
doc = Document()
|
| 62 |
+
doc.add_heading('Social Media Data Extraction Report', 0)
|
| 63 |
+
|
| 64 |
+
for idx, post in enumerate(posts):
|
| 65 |
+
doc.add_heading(f'Post {idx+1}', level=1)
|
| 66 |
+
|
| 67 |
+
data = [
|
| 68 |
+
("Date of Post", post.get('date', 'N/A')),
|
| 69 |
+
("Media Type", post.get('media_type', 'N/A')),
|
| 70 |
+
("Number of Pictures", post.get('num_pictures', 'N/A')),
|
| 71 |
+
("Likes", post.get('likes', 'N/A')),
|
| 72 |
+
("Comments", post.get('comments', 'N/A')),
|
| 73 |
+
("Caption", post.get('caption', 'N/A')),
|
| 74 |
+
("OCR Text", post.get('ocr_text', 'N/A')),
|
| 75 |
+
("Language", post.get('language', 'N/A')),
|
| 76 |
+
("Sentiment Analysis", post.get('sentiment', 'N/A')),
|
| 77 |
+
("Content Categories", post.get('categories', 'N/A')),
|
| 78 |
+
("Hashtags", ', '.join(post.get('hashtags', [])) if post.get('hashtags') else 'N/A'),
|
| 79 |
+
("Concept Keywords", ', '.join(post.get('concepts', [])) if post.get('concepts') else 'N/A')
|
| 80 |
+
]
|
| 81 |
+
|
| 82 |
+
for label, value in data:
|
| 83 |
+
doc.add_paragraph(f"{label}: {value}")
|
| 84 |
+
|
| 85 |
+
doc.add_page_break()
|
| 86 |
+
|
| 87 |
+
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".docx")
|
| 88 |
+
doc.save(temp_file.name)
|
| 89 |
+
return temp_file.name
|
| 90 |
+
|
| 91 |
+
# Processing Functions
|
| 92 |
+
def process_social_media(profile_link, hashtags, concepts, platform, date_range, num_posts):
|
| 93 |
+
# Mock data - Replace with actual social media API calls
|
| 94 |
+
mock_image = Image.new('RGB', (800, 600), color='white')
|
| 95 |
+
mock_image_path = tempfile.mktemp(suffix='.jpg')
|
| 96 |
+
mock_image.save(mock_image_path)
|
| 97 |
+
|
| 98 |
+
posts = [{
|
| 99 |
+
'date': datetime.now().strftime("%Y-%m-%d"),
|
| 100 |
+
'media_type': 'Image',
|
| 101 |
+
'num_pictures': 1,
|
| 102 |
+
'likes': 150,
|
| 103 |
+
'comments': 20,
|
| 104 |
+
'caption': 'Example caption with #technology',
|
| 105 |
+
'ocr_text': extract_text_from_image(mock_image_path),
|
| 106 |
+
'hashtags': ['#technology'],
|
| 107 |
+
'concepts': [c.strip() for c in concepts.split(',')],
|
| 108 |
+
'sentiment': analyze_sentiment('Example caption with #technology'),
|
| 109 |
+
'categories': categorize_content('Example caption with #technology')
|
| 110 |
+
}]
|
| 111 |
+
|
| 112 |
+
os.remove(mock_image_path)
|
| 113 |
+
return create_word_document(posts[:num_posts])
|
| 114 |
+
|
| 115 |
+
def process_word_file(file, concepts):
|
| 116 |
+
doc = Document(file.name)
|
| 117 |
+
posts = []
|
| 118 |
+
|
| 119 |
+
for para in doc.paragraphs:
|
| 120 |
+
if para.text.startswith('Post'):
|
| 121 |
+
posts.append({'caption': ''})
|
| 122 |
+
elif posts:
|
| 123 |
+
posts[-1]['caption'] += para.text + '\n'
|
| 124 |
+
|
| 125 |
+
processed_posts = []
|
| 126 |
+
for post in posts:
|
| 127 |
+
caption = post.get('caption', '')
|
| 128 |
+
processed_post = {
|
| 129 |
+
'date': datetime.now().strftime("%Y-%m-%d"),
|
| 130 |
+
'media_type': 'Text',
|
| 131 |
+
'caption': caption,
|
| 132 |
+
'sentiment': analyze_sentiment(caption),
|
| 133 |
+
'categories': categorize_content(caption),
|
| 134 |
+
'concepts': [c.strip() for c in concepts.split(',')],
|
| 135 |
+
'hashtags': re.findall(r'#\w+', caption)
|
| 136 |
+
}
|
| 137 |
+
processed_posts.append(processed_post)
|
| 138 |
+
|
| 139 |
+
return create_word_document(processed_posts)
|
| 140 |
+
|
| 141 |
+
# Gradio Interface
|
| 142 |
+
with gr.Blocks(title="Social Media Analyzer") as app:
|
| 143 |
+
gr.Markdown("# Social Media Data Extraction Tool")
|
| 144 |
+
|
| 145 |
+
with gr.Tabs():
|
| 146 |
+
with gr.TabItem("Social Media Extraction"):
|
| 147 |
+
gr.Markdown("## Analyze Social Media Profiles")
|
| 148 |
+
with gr.Row():
|
| 149 |
+
with gr.Column():
|
| 150 |
+
profile_link = gr.Textbox(label="Profile URL")
|
| 151 |
+
hashtags = gr.Textbox(label="Hashtags (comma separated)")
|
| 152 |
+
concepts = gr.Textbox(label="Concept Keywords (comma separated)")
|
| 153 |
+
platform = gr.Radio(["Instagram", "Twitter", "Facebook"], label="Platform")
|
| 154 |
+
date_range = gr.DatePicker(label="Date Range")
|
| 155 |
+
num_posts = gr.Slider(1, 100, value=10, label="Number of Posts")
|
| 156 |
+
sm_submit = gr.Button("Analyze Profile", variant="primary")
|
| 157 |
+
|
| 158 |
+
with gr.Column():
|
| 159 |
+
sm_output = gr.File(label="Download Analysis Report")
|
| 160 |
+
|
| 161 |
+
with gr.TabItem("Document Processing"):
|
| 162 |
+
gr.Markdown("## Analyze Word Documents")
|
| 163 |
+
with gr.Row():
|
| 164 |
+
with gr.Column():
|
| 165 |
+
word_file = gr.File(label="Upload Word Document")
|
| 166 |
+
wp_concepts = gr.Textbox(label="Concept Keywords (comma separated)")
|
| 167 |
+
wp_submit = gr.Button("Analyze Document", variant="primary")
|
| 168 |
+
|
| 169 |
+
with gr.Column():
|
| 170 |
+
wp_output = gr.File(label="Download Analysis Report")
|
| 171 |
+
|
| 172 |
+
sm_submit.click(
|
| 173 |
+
fn=process_social_media,
|
| 174 |
+
inputs=[profile_link, hashtags, concepts, platform, date_range, num_posts],
|
| 175 |
+
outputs=sm_output
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
wp_submit.click(
|
| 179 |
+
fn=process_word_file,
|
| 180 |
+
inputs=[word_file, wp_concepts],
|
| 181 |
+
outputs=wp_output
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
if __name__ == "__main__":
|
| 185 |
+
app.launch()
|