ahm14's picture
Update app.py
d4ecb5d verified
Raw
History Blame Contribute Delete
6.77 kB
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()