Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import requests
|
| 3 |
+
from bs4 import BeautifulSoup
|
| 4 |
+
import re
|
| 5 |
+
from sentence_transformers import SentenceTransformer, util
|
| 6 |
+
from huggingface_hub import InferenceClient
|
| 7 |
+
import gradio as gr
|
| 8 |
+
import os
|
| 9 |
+
|
| 10 |
+
print("1. Ingesting Unstructured Data...")
|
| 11 |
+
# We use a robust fallback block of the script to ensure the app never crashes for a recruiter
|
| 12 |
+
fallback_script = """
|
| 13 |
+
[ Scene starts in FBI facility ]
|
| 14 |
+
RESSLER: Heβs demanding to speak with you.
|
| 15 |
+
ELIZABETH: Me? Why me? I don't know him.
|
| 16 |
+
RESSLER: We don't know why. But we need to hear what he has to say.
|
| 17 |
+
[ Elizabeth walks into the interrogation room ]
|
| 18 |
+
REDDINGTON: You got rid of your highlights. You look much less... Baltimore.
|
| 19 |
+
ELIZABETH: You asked to see me. Why?
|
| 20 |
+
REDDINGTON: I'm a criminal, Lizzie. You're a profiler. You tell me.
|
| 21 |
+
ELIZABETH: I think you're bored. I think you're using us.
|
| 22 |
+
REDDINGTON: I'm going to make you famous. I have a list. A blacklist of the worst criminals in the world. And I will give them to you.
|
| 23 |
+
REDDINGTON: Starting with Ranko Zamani. He is in town, Lizzie. And he plans to kidnap the general's daughter.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
url = "https://subslikescript.com/series/The_Blacklist-2741602/season-1/episode-1-Pilot"
|
| 27 |
+
headers = {'User-Agent': 'Mozilla/5.0'}
|
| 28 |
+
|
| 29 |
+
try:
|
| 30 |
+
response = requests.get(url, headers=headers, timeout=5)
|
| 31 |
+
response.raise_for_status()
|
| 32 |
+
soup = BeautifulSoup(response.text, 'html.parser')
|
| 33 |
+
script_div = soup.find('div', class_='full-script')
|
| 34 |
+
raw_text = script_div.get_text(separator='\n') if script_div else fallback_script
|
| 35 |
+
print("Scraped live data successfully.")
|
| 36 |
+
except Exception:
|
| 37 |
+
print("Live scrape blocked by server. Using fallback script.")
|
| 38 |
+
raw_text = fallback_script
|
| 39 |
+
|
| 40 |
+
print("2. Structuring and Chunking the Data...")
|
| 41 |
+
lines = raw_text.split('\n')
|
| 42 |
+
structured_data = []
|
| 43 |
+
dialogue_pattern = re.compile(r"^([A-Z\s]+):\s*(.*)")
|
| 44 |
+
|
| 45 |
+
for line in lines:
|
| 46 |
+
line = line.strip()
|
| 47 |
+
if not line: continue
|
| 48 |
+
match = dialogue_pattern.match(line)
|
| 49 |
+
if match:
|
| 50 |
+
structured_data.append({"Character": match.group(1).strip(), "Dialogue": match.group(2).strip()})
|
| 51 |
+
|
| 52 |
+
df = pd.DataFrame(structured_data)
|
| 53 |
+
df['Full_Line'] = df['Character'] + ": " + df['Dialogue']
|
| 54 |
+
|
| 55 |
+
# Sliding Window Context (3 lines total per chunk)
|
| 56 |
+
window_size = 1
|
| 57 |
+
context_chunks = []
|
| 58 |
+
for i in range(len(df)):
|
| 59 |
+
start = max(0, i - window_size)
|
| 60 |
+
end = min(len(df), i + window_size + 1)
|
| 61 |
+
chunk = "\n".join(df['Full_Line'].iloc[start:end])
|
| 62 |
+
context_chunks.append({"context_block": chunk})
|
| 63 |
+
|
| 64 |
+
ai_df = pd.DataFrame(context_chunks)
|
| 65 |
+
|
| 66 |
+
print("3. Vectorizing Data & Connecting LLM...")
|
| 67 |
+
model = SentenceTransformer('all-MiniLM-L6-v2')
|
| 68 |
+
vector_database = model.encode(ai_df['context_block'].tolist())
|
| 69 |
+
|
| 70 |
+
hf_token = os.environ.get("HF_TOKEN")
|
| 71 |
+
client = InferenceClient(model="meta-llama/Meta-Llama-3-8B-Instruct", token=hf_token)
|
| 72 |
+
|
| 73 |
+
def search_script(user_query):
|
| 74 |
+
query_vector = model.encode(user_query)
|
| 75 |
+
hits = util.semantic_search(query_vector, vector_database, top_k=2)
|
| 76 |
+
|
| 77 |
+
retrieved_contexts = [ai_df['context_block'].iloc[hit['corpus_id']] for hit in hits[0]]
|
| 78 |
+
combined_context = "\n---\n".join(retrieved_contexts)
|
| 79 |
+
|
| 80 |
+
messages = [
|
| 81 |
+
{"role": "system", "content": "You are a data analyst answering questions using ONLY the provided script excerpts. Do not invent lore."},
|
| 82 |
+
{"role": "user", "content": f"Question: {user_query}\n\nScript Excerpts:\n{combined_context}"}
|
| 83 |
+
]
|
| 84 |
+
|
| 85 |
+
try:
|
| 86 |
+
response = client.chat.completions.create(messages=messages, max_tokens=250, temperature=0.2)
|
| 87 |
+
return response.choices[0].message.content.strip(), combined_context
|
| 88 |
+
except Exception as e:
|
| 89 |
+
return f"Error: {e}", combined_context
|
| 90 |
+
|
| 91 |
+
print("4. Launching Interface...")
|
| 92 |
+
with gr.Blocks() as demo:
|
| 93 |
+
gr.Markdown("# π¬ Unstructured Data AI: TV Script Search")
|
| 94 |
+
gr.Markdown("This agent processes messy, unstructured dialogue. Ask a question about the plot, and the AI will search the script to find the exact context.")
|
| 95 |
+
|
| 96 |
+
with gr.Row():
|
| 97 |
+
with gr.Column():
|
| 98 |
+
input_query = gr.Textbox(lines=3, label="Ask a question (e.g., 'Who is Ranko Zamani?' or 'Why does Reddington want Elizabeth?')")
|
| 99 |
+
submit_btn = gr.Button("Search Script")
|
| 100 |
+
|
| 101 |
+
with gr.Column():
|
| 102 |
+
output_reply = gr.Textbox(lines=5, label="AI Answer")
|
| 103 |
+
retrieved_doc = gr.Textbox(lines=5, label="Raw Context Retrieved by Python")
|
| 104 |
+
|
| 105 |
+
submit_btn.click(fn=search_script, inputs=input_query, outputs=[output_reply, retrieved_doc])
|
| 106 |
+
|
| 107 |
+
demo.launch()
|