Spaces:
Sleeping
Sleeping
afsheen nadaf commited on
Commit ·
8c19fdc
0
Parent(s):
fix for recent searches
Browse filesFiles changed (12)
- .gitignoreAdded
- DockerfileAdded+34
- README.mdAdded+12
- backend/.gitignoreAdded+13
- backend/DockerfileAdded+31
- backend/app.pyAdded+235
- backend/bluesky.pyAdded+57
- backend/database.pyAdded+18
- backend/nlp_engine.pyAdded+116
- backend/processor.pyAdded+86
- backend/requirements.txtAdded+12
- backend/sentiment.pyAdded+76
12345678910111213141516171819202122232425262728293031323334# Use an official Python base imageFROM python:3.11-slim
# Switch to root to install system dependenciesUSER root
# Install OpenJDK 21 AND procps for PySparkRUN apt-get update && \ apt-get install -y --no-install-recommends openjdk-21-jre-headless procps && \ apt-get clean && \ rm -rf /var/lib/apt/lists/*
# Fallback pathing rule supporting PySpark execution layerENV JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64ENV PATH="${JAVA_HOME}/bin:${PATH}"
# Set up the working directory to track the rootWORKDIR /app
# Copy the backend requirements first to leverage cachingCOPY backend/requirements.txt ./backend/RUN pip install --no-cache-dir -r backend/requirements.txt
# Copy the entire backend directory contents into the containerCOPY backend/ ./backend/
# Change working directory context to the backend folder so paths match app.pyWORKDIR /app/backend
# HUGGING FACE COMPLIANCE: Expose port 7860EXPOSE 7860
# Run using Gunicorn bound to port 7860 inside the backend folder contextCMD ["gunicorn", "--bind", "0.0.0.0:7860", "app:app"]123456789101112---title: Perception Backendemoji: 🧠colorFrom: indigocolorTo: pinksdk: dockerapp_file: app.pypinned: false---
# Perception AI BackendPySpark and Flask analytics pipeline running smoothly on Hugging Face Spaces.12345678910111213# Python cache__pycache__/*.pyc
# Virtual environmentvenv/.venv/
# Environment variables.env
# Firebase credentialsconfig/firebase-adminsdk.json12345678910111213141516171819202122232425262728293031# Use an official Python base imageFROM python:3.11-slim
# Switch to root to install system dependenciesUSER root
# Install OpenJDK 21 AND procps (which gives Spark the 'ps' command it needs)RUN apt-get update && \ apt-get install -y --no-install-recommends openjdk-21-jre-headless procps && \ apt-get clean && \ rm -rf /var/lib/apt/lists/*
# Fallback pathing rule directly supporting PySpark's execution layerENV JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64ENV PATH="${JAVA_HOME}/bin:${PATH}"
# Set up the working directory inside the containerWORKDIR /app
# Copy and install Python dependenciesCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txt
# Copy the rest of your application codeCOPY . .
# HUGGING FACE COMPLIANCE: Expose port 7860EXPOSE 7860
# Run using Gunicorn bound to port 7860CMD ["gunicorn", "--bind", "0.0.0.0:7860", "app:app"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235import osif os.name == 'nt': # only on Windows os.environ["JAVA_HOME"] = r"C:\Program Files\Eclipse Adoptium\jdk-17.0.19.10-hotspot"
os.environ["PYSPARK_PYTHON"] = "python"os.environ["PYSPARK_DRIVER_PYTHON"] = "python"
from collections import defaultdictfrom datetime import datetime, timedelta, timezonefrom flask import Flask, request, jsonifyfrom flask_cors import cross_origin, CORSfrom dotenv import load_dotenv
import traceback
load_dotenv()
from database import db, firestorefrom bluesky import fetch_bluesky_postsfrom processor import preprocess_posts_with_sparkfrom sentiment import score_sentiment_batch, calculate_polarization
# --- NEW ML ENGINE IMPORT ---from nlp_engine import extract_advanced_keywords, select_diverse_sample_posts
app = Flask(__name__)CORS(app, origins=[ "http://localhost:3000", "https://perception-eosin.vercel.app"])
# _client_initialized = False
# @app.before_request# def ensure_bluesky_client():# global _client_initialized # if not _client_initialized: # try: # init_client() # _client_initialized = True # except Exception as e: # print(f"Failed to initialize Bluesky client: {e}")
def build_time_trend(posts): buckets = defaultdict(lambda: {"positive": 0, "negative": 0}) for p in posts: try: hour = p["created_utc"][:13] # "2026-06-21T04" except (TypeError, KeyError): continue sentiment = p.get("sentiment") if sentiment in ("positive", "negative"): buckets[hour][sentiment] += 1
return [ {"time": k.replace("T", " ") + ":00", "positive": v["positive"], "negative": v["negative"]} for k, v in sorted(buckets.items()) ]
@app.route('/api/analyze', methods=['GET', 'POST', 'OPTIONS'], strict_slashes=False)@cross_origin()def analyze(): if request.method == 'OPTIONS': return '', 200
if request.method == 'POST': data = request.get_json() topic = data.get('topic') if data else None user_id = data.get('userId') if data else None else: topic = request.args.get('topic') user_id = request.args.get('userId')
if not topic: return jsonify({"error": "No topic provided"}), 400
six_hours_ago = datetime.now(timezone.utc) - timedelta(hours=6) cached_searches = db.collection("searches") \ .where("topic", "==", topic) \ .where("userId", "==", user_id) \ .where("searched_at", ">=", six_hours_ago) \ .order_by("searched_at", direction=firestore.Query.DESCENDING) \ .limit(1).get()
if cached_searches: cache_doc = cached_searches[0] search_id = cache_doc.id cache_data = cache_doc.to_dict()
posts_ref = db.collection("searches").document(search_id).collection("posts").get() all_cached_posts = [p.to_dict() for p in posts_ref] sample_posts = all_cached_posts[:5] time_trend = build_time_trend(all_cached_posts)
return jsonify({ "searchId": search_id, "metrics": cache_data["metrics"], "polarization_score": cache_data["polarization_score"], "top_keywords": cache_data.get("top_keywords", {"positive": [], "negative": []}), "sample_posts": sample_posts, "time_trend": time_trend, "cached": True })
try: raw_posts = fetch_bluesky_posts(topic, limit=400) except Exception as e: print("\n=== HIDDEN BLUESKY ERROR ===") traceback.print_exc() print("============================\n") return jsonify({"error": f"Bluesky SDK Exception: {repr(e)}"}), 500
if not raw_posts: return jsonify({"error": "No data found on Bluesky for this topic"}), 404
try: spark_rows = preprocess_posts_with_spark(raw_posts) except Exception as e: return jsonify({"error": f"Spark Preprocessing Error: {str(e)}"}), 500
if not spark_rows: return jsonify({"error": "No data remaining after processing filters"}), 400
texts_to_score = [row["cleaned_text"] for row in spark_rows] sentiment_results = score_sentiment_batch(texts_to_score)
if not sentiment_results: return jsonify({"error": "HuggingFace model initializing. Try again shortly."}), 503
pos, neg, neu = 0, 0, 0 pos_texts, neg_texts = [], [] processed_posts = []
for idx, row in enumerate(spark_rows): res = sentiment_results[idx] sent = res["sentiment"]
if sent == "positive": pos += 1 pos_texts.append(row["cleaned_text"]) elif sent == "negative": neg += 1 neg_texts.append(row["cleaned_text"]) else: neu += 1
processed_posts.append({ "id": row["id"], "text": row["text"], "sentiment": sent, "confidence": res["confidence"], "created_utc": row["created_utc"] })
# --- NEW ML ENGINE CALLS --- # Up the max_keywords to 12 for a much richer keyword cloud! top_pos_kw = extract_advanced_keywords(pos_texts, max_keywords=15) top_neg_kw = extract_advanced_keywords(neg_texts, max_keywords=15) keywords_dict = {"positive": top_pos_kw, "negative": top_neg_kw}
diverse_sample_posts = select_diverse_sample_posts(processed_posts, num_samples=5) # ---------------------------
total_scored = pos + neg + neu summary = { "positive": round((pos / total_scored) * 100, 1) if total_scored else 0, "negative": round((neg / total_scored) * 100, 1) if total_scored else 0, "neutral": round((neu / total_scored) * 100, 1) if total_scored else 0 } pol_score = calculate_polarization(pos, neg, neu) time_trend = build_time_trend(processed_posts)
# 1. Normalize the document ID to the lowercased topic name normalized_id = f"{user_id}_{topic.strip().lower()}" search_ref = db.collection("searches").document(normalized_id)
# 2. Save/Overwrite the top-level topic document search_ref.set({ "topic": topic, # Retains original casing ("Taylor Swift") "userId": user_id, "searched_at": datetime.now(timezone.utc), # Fresh timestamp pushes it to the top! "polarization_score": pol_score, "metrics": summary, "top_keywords": keywords_dict })
# 3. Clean up older sub-collection posts to avoid mixing old data with new data old_posts = search_ref.collection("posts").get() delete_batch = db.batch() for doc in old_posts: delete_batch.delete(doc.reference) delete_batch.commit()
# 4. Commit the new batch of processed posts (Up to 400 fits safely under the 500 batch limit!) batch = db.batch() for p in processed_posts: p_doc_ref = search_ref.collection("posts").document(p["id"]) batch.set(p_doc_ref, p) batch.commit()
return jsonify({ "searchId": search_ref.id, # This will now be the clean name string! "metrics": summary, "polarization_score": pol_score, "top_keywords": keywords_dict, "sample_posts": diverse_sample_posts, "time_trend": time_trend, "cached": False })
@app.route("/api/history/<topic>", methods=["GET"])def get_topic_history(topic): normalized_topic = topic.strip().lower() docs = db.collection("searches") \ .where("topic", "==", normalized_topic) \ .order_by("searched_at", direction=firestore.Query.ASCENDING).get()
history = [] for d in docs: data = d.to_dict() history.append({ "searchId": d.id, "searched_at": data["searched_at"], "metrics": data["metrics"], "polarization_score": data["polarization_score"] }) return jsonify(history)
if __name__ == "__main__": app.run(port=int(os.getenv("PORT", 5000)))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657import osfrom datetime import datetime, timezonefrom atproto import Clientfrom dotenv import load_dotenv
load_dotenv()
_client = None
def get_client(): global _client if _client is None: _client = Client() _client.login(os.getenv("BLUESKY_HANDLE"), os.getenv("BLUESKY_APP_PASSWORD")) _client.request.timeout = 30.0 print("✅ Successfully authenticated with Bluesky AT Protocol.") return _client
def fetch_bluesky_posts(topic, limit=200): print(f"=== DEBUG: Searching Bluesky for topic: '{topic}' ===") client = get_client() posts = [] cursor = None
while len(posts) < limit: current_limit = min(100, limit - len(posts)) params = {'q': str(topic), 'limit': current_limit}
if cursor: params['cursor'] = cursor
try: response = client.app.bsky.feed.search_posts(params) if not response.posts: break
for post in response.posts: if not post.record or not hasattr(post.record, 'text') or post.record.text is None: continue
posts.append({ "id": str(post.uri.split("/")[-1]), "text": str(post.record.text), "created_utc": str(post.record.created_at if hasattr(post.record, 'created_at') else datetime.now(timezone.utc).isoformat()) })
cursor = response.cursor if not cursor: break
except Exception as e: print(f"Error during Bluesky fetch: {e}") if not posts: raise break
return posts123456789101112131415161718import osimport jsonimport firebase_adminfrom firebase_admin import credentials, firestore
def get_db(): if not firebase_admin._apps: firebase_config = json.loads( os.environ["FIREBASE_CREDENTIALS_JSON"] )
cred = credentials.Certificate(firebase_config)
firebase_admin.initialize_app(cred)
return firestore.client()
db = get_db()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116import numpy as npfrom sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.metrics.pairwise import cosine_similarityimport networkx as nximport yake
# Aggressive filter for common social media filler that standard NLP stopwords missCUSTOM_FILLER = { "people", "time", "thing", "things", "good", "bad", "post", "posts", "bluesky", "app", "make", "know", "think", "look", "going", "really", "much", "well", "even", "want", "right", "sure", "need", "never", "always"}
def extract_advanced_keywords(texts, max_keywords=12): """ Uses YAKE for initial extraction, filters out social media garbage, then uses NetworkX (PageRank) to find the true central keywords. """ if not texts: return [] full_text = " ".join(texts) # 1. YAKE Extraction # dedupLim=0.7 makes it strictly avoid repetitive phrases # top=50 gives our graph a larger pool to calculate centrality from kw_extractor = yake.KeywordExtractor(lan="en", n=2, dedupLim=0.7, top=50, features=None) raw_keywords = kw_extractor.extract_keywords(full_text) if not raw_keywords: return []
# Filter out any phrase that is exactly in our custom filler list, or too short phrases = [] for kw, _ in raw_keywords: clean_kw = kw.lower().strip() if clean_kw not in CUSTOM_FILLER and len(clean_kw) > 2: phrases.append(kw) if not phrases: return []
# 2. Build Co-occurrence Graph with NetworkX G = nx.Graph() for text in texts: text_lower = text.lower() present_phrases = [p for p in phrases if p.lower() in text_lower] for i in range(len(present_phrases)): for j in range(i + 1, len(present_phrases)): w1, w2 = present_phrases[i], present_phrases[j] if G.has_edge(w1, w2): G[w1][w2]['weight'] += 1 else: G.add_edge(w1, w2, weight=1) # Fallback if no co-occurrences were found if len(G.nodes) == 0: return phrases[:max_keywords] # 3. Calculate PageRank for true centrality try: ranks = nx.pagerank(G, weight='weight') ranked_keywords = sorted(ranks.items(), key=lambda x: x[1], reverse=True) return [kw[0] for kw in ranked_keywords[:max_keywords]] except Exception: return phrases[:max_keywords]
def select_diverse_sample_posts(posts, num_samples=5): """ Uses Scikit-Learn TF-IDF and NumPy to select diverse but representative posts. """ if len(posts) <= num_samples: return posts texts = [p['text'] for p in posts] vectorizer = TfidfVectorizer(stop_words='english') try: tfidf_matrix = vectorizer.fit_transform(texts) except ValueError: return posts[:num_samples] centroid = tfidf_matrix.mean(axis=0) centroid_sim = cosine_similarity(tfidf_matrix, np.asarray(centroid)).flatten() doc_sim_matrix = cosine_similarity(tfidf_matrix) selected_indices = [] first_idx = int(np.argmax(centroid_sim)) selected_indices.append(first_idx) for _ in range(1, num_samples): best_score = -float('inf') best_idx = -1 for i in range(len(posts)): if i in selected_indices: continue relevance = centroid_sim[i] redundancy = np.max([doc_sim_matrix[i][j] for j in selected_indices]) mmr_score = 0.5 * relevance - 0.5 * redundancy if mmr_score > best_score: best_score = mmr_score best_idx = i if best_idx != -1: selected_indices.append(best_idx) else: break return [posts[i] for i in selected_indices]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586import reimport tempfilefrom pyspark.sql import SparkSessionfrom pyspark.sql.functions import col, udf, lengthfrom pyspark.sql.types import StringType, StructType, StructField, ArrayType
STOPWORDS = { "the", "and", "a", "of", "to", "is", "in", "that", "it", "this", "for", "on", "with", "as", "at", "by", "an", "i", "about", "from", "than", "sure", "just", "like", "more", "have", "not", "they", "their", "what", "when", "which", "who", "will", "would", "been", "were", "also", "into", "over", "after", "then", "some", "than", "other", "your", "there", "these", "those", "them", "each", "much", "very", "well", "even", "here", "only", "such", "both", "many", "most", "does", "said", "being", "because", "while", "where", "could", "should", "through", "before", "between", "same", "back", "still", "want", "know", "think", "make", "need", "going", "come", "good", "dont", "cant", "didnt", "isnt", "wasnt", "hasnt", "hadnt", "wont", "people", "time", "year", "years", "way", "really", "thing", "things", "look", "made", "used", "using", "says", "since", "every", "https", "fifth", "third", "first", "second", "pretty", "actually", "always",}
def clean_text_pure(text): if text is None or not isinstance(text, str): return "" text = re.sub(r'https?://\S+', '', text) text = re.sub(r'[^a-zA-Z0-9\s\.,!\?]', '', text) return " ".join(text.split()).lower()
def extract_keywords_pure(text): if text is None or not isinstance(text, str): return [] words = re.findall(r'\b[a-z]{4,}\b', text) seen = set() result = [] for w in words: if w not in STOPWORDS and w not in seen: seen.add(w) result.append(w) if len(result) == 8: break return result
clean_text_udf = udf(clean_text_pure, StringType())extract_keywords_udf = udf(extract_keywords_pure, ArrayType(StringType()))
_spark_session = None
def get_spark_session(): """ Initializes an optimized Spark Session with a safe memory footprint to successfully pass JVM validation checks on Hugging Face Spaces. """ return SparkSession.builder \ .appName("PerceptionAIProcessor") \ .master("local[1]") \ .config("spark.driver.memory", "1g") \ .config("spark.executor.memory", "1g") \ .config("spark.driver.extraJavaOptions", "-XX:+UseSerialGC") \ .config("spark.executor.extraJavaOptions", "-XX:+UseSerialGC") \ .config("spark.sql.shuffle.partitions", "2") \ .config("spark.ui.enabled", "false") \ .getOrCreate()
def preprocess_posts_with_spark(raw_posts): if not raw_posts: return []
spark = get_spark_session()
schema = StructType([ StructField("id", StringType(), False), StructField("text", StringType(), True), StructField("created_utc", StringType(), True) ])
df = spark.createDataFrame(raw_posts, schema) df_sanitized = df.na.drop(subset=["text"])
df_cleaned = df_sanitized.dropDuplicates(["id"]) \ .withColumn("cleaned_text", clean_text_udf(col("text"))) \ .filter(length(col("cleaned_text")) >= 40)
df_final = df_cleaned.withColumn("keywords", extract_keywords_udf(col("cleaned_text"))) return df_final.collect()123456789101112Flask==3.0.2flask-cors==4.0.0requests==2.31.0pyspark==3.5.1firebase-admin==6.5.0python-dotenv==1.0.1atproto==0.0.69gunicorn==23.0.0numpyscikit-learnnetworkxyake12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576import osimport requests
def get_hf_config(): return { # Using the updated HF Router URL! "url": "https://router.huggingface.co/hf-inference/models/cardiffnlp/twitter-roberta-base-sentiment", "headers": {"Authorization": f"Bearer {os.getenv('HF_API_KEY')}"} }
def score_sentiment_batch(text_list): if not text_list: return [] config = get_hf_config() results = [] label_mapping = {"LABEL_0": "negative", "LABEL_1": "neutral", "LABEL_2": "positive"} chunk_size = 20 for i in range(0, len(text_list), chunk_size): chunk = text_list[i:i + chunk_size] chunk_results = [] try: response = requests.post(config["url"], headers=config["headers"], json={"inputs": chunk}, timeout=15) response_json = response.json() if isinstance(response_json, dict) and "estimated_time" in response_json: return None if isinstance(response_json, list): if len(response_json) == 1 and isinstance(response_json[0], list) and len(response_json[0]) == len(chunk): for item in response_json[0]: if isinstance(item, dict) and "label" in item: chunk_results.append({ "sentiment": label_mapping.get(item["label"], "neutral"), "confidence": round(item.get("score", 0.5), 3) }) else: chunk_results.append({"sentiment": "neutral", "confidence": 0.5}) elif len(response_json) == len(chunk): for item in response_json: if isinstance(item, list) and len(item) > 0 and "score" in item[0]: top = max(item, key=lambda x: x.get("score", 0)) chunk_results.append({ "sentiment": label_mapping.get(top.get("label"), "neutral"), "confidence": round(top.get("score", 0.5), 3) }) else: chunk_results.append({"sentiment": "neutral", "confidence": 0.5}) else: print(f"=== HUGGINGFACE API WARNING: Size mismatch ===") except Exception as e: print(f"=== CRITICAL HUGGINGFACE EXCEPTION: {e} ===") pass while len(chunk_results) < len(chunk): chunk_results.append({"sentiment": "neutral", "confidence": 0.5}) results.extend(chunk_results[:len(chunk)]) return results
def calculate_polarization(pos, neg, neu): total = pos + neg + neu if total == 0: return 0.0 p_pct = pos / total n_pct = neg / total neu_pct = neu / total conflict = min(p_pct, n_pct) * 2 dominance = max(p_pct, n_pct, neu_pct) return round((conflict / dominance) if dominance > 0 else 0, 2).gitignoreAdded
DockerfileAdded+34
README.mdAdded+12
backend/.gitignoreAdded+13
backend/DockerfileAdded+31
backend/app.pyAdded+235
backend/bluesky.pyAdded+57
backend/database.pyAdded+18
backend/nlp_engine.pyAdded+116
backend/processor.pyAdded+86
backend/requirements.txtAdded+12
backend/sentiment.pyAdded+76