Gen AIL
Gen AIL
print("Loading model...")
model = api.load("word2vec-google-news-300")
print("Model loaded!")
try:
except KeyError as e:
print(f"\n{title}")
# Custom input
reduced = PCA(n_components=2).fit_transform(vecs)
plt.figure(figsize=(10, 8))
inp = "algorithm"
result = similar(inp)
nltk.download('punkt')
# Save corpus
text = f.read().lower()
# Train model
model.save("custom_word2vec.model")
if word in m.wv:
print(f"Similar to '{word}':")
show_similar(model, "cell")
glove = api.load("glove-wiki-gigaword-300")
nltk.download('punkt', quiet=True)
vectors = api.load("glove-wiki-gigaword-100")
generator = pipeline("text-generation", model="gpt2")
def generate(text):
return generator(text, max_length=100, num_return_sequences=1)[0]['generated_text']
# Inputs
original = "Who is king?"
key = "king"
enriched = enrich_prompt(original, key, vectors)
# Generate
print("\nOriginal Response:\n", (o := generate(original)))
print("\nEnriched Response:\n", (e := generate(enriched)))
# Compare
print("\n--- Comparison ---")
print(f"Original Length: {len(o)} | Periods: {o.count('.')}")
print(f"Enriched Length: {len(e)} | Periods: {e.count('.')}")
Program 5:
import nltk, random, string
nltk.download('punkt', quiet=True)
vectors = api.load("glove-wiki-gigaword-100")
except: return []
templates = [
return random.choice(templates)
def generate_paragraph(seed):
sim = get_similar(seed)
if not sim: return "No similar words found."
def count_freq(text):
return Counter(text.split())
# Run it
para = generate_paragraph(seed)
freq = count_freq(para)
Program 6:
from transformers import pipeline
analyze = pipeline("sentiment-analysis")
texts = [
summarize = pipeline("summarization")
AI is used in healthcare, finance, and transport, and is growing more efficient with deep learning.
However, it raises concerns like bias, privacy, and job loss, which must be addressed."""
print("Summary:\n", summary)
Program 8:
from langchain import PromptTemplate
text = """Artificial intelligence is transforming industries with new capabilities and efficiencies.
{text}
Summary:
- Concise summary
Key Takeaways:
formatted_prompt = prompt.format(text=text)
response = cohere_llm.predict(formatted_prompt)
Program 9:
!pip install wikipedia-api pydantic ipywidgets
import wikipediaapi
class InstitutionDetails(BaseModel):
founder: Optional[str]
founded: Optional[str]
branches: Optional[List[str]]
number_of_employees: Optional[int]
summary: Optional[str]
page = wiki.page(name)
employees = None
l = line.lower()
k, _, v = line.partition('=')
val = v.strip()
elif 'employees' in l:
except: pass
return InstitutionDetails(
founder=founder, founded=founded,
branches=branches or None,
number_of_employees=employees,
summary=page.summary[:500]
def on_click(b):
name = input_box.value.strip()
btn.on_click(on_click)
display(input_box, btn)
Program 10:
def fetch_ipc_summary():
return page.text[:5000]
ipc_text = fetch_ipc_summary()
class IPCResponse(BaseModel):
section: Optional[str]
explanation: Optional[str]
prompt = PromptTemplate(
input_variables=["ipc_content", "question"],
template="""
You are a legal assistant specialized in the Indian Penal Code. Refer to the content below to answer:
{ipc_content}
Question: {question}
"""
r = llm.predict(prompt.format(ipc_content=ipc_text, question=q))
if "Section" in r:
sec = r.split('Section')[1].split(':')[0].strip()
else:
print(f"Explanation: {res.explanation}")
def on_click(b):
q = input_box.value
try: display_response(get_ipc_response(q))
ask_btn.on_click(on_click)
display(input_box, ask_btn)